From a4f79753244ea928d76f3db5136dec8b6356441a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:29:51 +0200 Subject: [PATCH 01/27] Removing the API key while sharing or Cloudflare runs is allowed (the key is optional); the remove dialog warns plainly --- apps/host/server/serving.mjs | 2 +- apps/host/tests/serving-key-optional.test.mjs | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 apps/host/tests/serving-key-optional.test.mjs diff --git a/apps/host/server/serving.mjs b/apps/host/server/serving.mjs index c98f3eb8..ced16fac 100644 --- a/apps/host/server/serving.mjs +++ b/apps/host/server/serving.mjs @@ -70,7 +70,7 @@ export function patch(body) { const s = getStore(); const serving = { ...(s.serving ?? {}) }; if (typeof body.otherDevices === 'boolean' && body.otherDevices !== !isLocal()) throw new Error('Change the host listen address and restart to update network access.'); - if (body.apiKey === null && (!isLocal() || sharing.active || tunnelActive())) throw new Error('Stop local sharing and Cloudflare before removing the API key.'); + // The key is optional (owner decision, 0.2.2): removing it while sharing or the tunnel runs is allowed; the app warns in plain words (local-share.mjs, cloudflare.mjs). if (body.apiKey === null) serving.apiKey = null; else if (typeof body.apiKey === 'string' && body.apiKey.trim()) serving.apiKey = body.apiKey.trim(); else if (body.generateKey) serving.apiKey = `sk-strata-${randomBytes(12).toString('hex')}`; diff --git a/apps/host/tests/serving-key-optional.test.mjs b/apps/host/tests/serving-key-optional.test.mjs new file mode 100644 index 00000000..83c550a8 --- /dev/null +++ b/apps/host/tests/serving-key-optional.test.mjs @@ -0,0 +1,23 @@ +/** The API key is optional (owner decision, 0.2.2): removing it while sharing or the Cloudflare tunnel runs is allowed, and the key stays removed. */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const home = mkdtempSync(join(tmpdir(), 'strata-serving-key-')); +process.env.STRATA_HOME = home; +const serving = await import('../server/serving.mjs'); + +test('removing the API key while local sharing and the tunnel run is allowed', () => { + serving.init({ send() {} }, { port: 8080, host: '127.0.0.1' }); + serving.patch({ generateKey: true }); + assert.equal(serving.state().access.apiKeySet, true); + serving.setSharing({ active: true, url: 'http://192.168.1.5:8792/v1' }); + serving.setTunnel({ status: 'connected', mode: 'quick', url: 'https://example.trycloudflare.com', error: null, installed: true, originUrl: null }); + assert.equal(serving.state().access.otherDevices, true); + const after = serving.patch({ apiKey: null }); + assert.equal(after.access.apiKeySet, false); + assert.equal(serving.authorized({ headers: {} }), true); +}); +test.after(() => { try { rmSync(home, { recursive: true, force: true }); } catch { /* temp folder */ } }); From b22206c7bc348b6c5e73fa60102fc14b99ebf5f9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:29:51 +0200 Subject: [PATCH 02/27] Serving: Remove key stays available while sharing; plain warning in the remove dialog --- apps/host/src/screens/Serving.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/host/src/screens/Serving.tsx b/apps/host/src/screens/Serving.tsx index ac8e43f5..ebe6609a 100644 --- a/apps/host/src/screens/Serving.tsx +++ b/apps/host/src/screens/Serving.tsx @@ -86,7 +86,7 @@ export function ServingScreen() {
{tr("API base URL")}
{serving.baseUrl} void copyConnectionValue(serving.baseUrl, 'API base URL')}/>
{tr(!multipleModels ?
{tr("Model ID")}
{loaded?.apiModelId ?? 'No model loaded'} { if (loaded) void copyConnectionValue(loaded.apiModelId, 'Model ID'); - }}/>
: null)}
{tr("Status")}
{tr(serving.running ? 'API listening' : 'API stopped')} · {tr(multipleModels ? `${runtime?.instances.length} models loaded` : loaded ? 'Model ready' : 'Model not ready')}
{tr("Local network")}
{tr(serving.sharing?.active ? "Shared on local network" : "Off")} { setError(''); setSharingOpen(true); }}>{tr(serving.sharing?.active ? "Manage / stop" : "Share")}
{tr(serving.tunnel?.status === "connected" && serving.tunnel.url ?
{tr("Cloudflare tunnel")}
{serving.tunnel.url} void navigator.clipboard.writeText(serving.tunnel!.url!)}/> setCloudflareOpen(true)}/>
: serving.tunnel?.status === "starting" ?
{tr("Cloudflare tunnel")}
{tr("Connecting\u2026")}
: null)}
{tr("API key")}
{tr(serving.access.apiKeySet ? {tr("Required \u00B7 ")}{tr(serving.access.apiKeyHint)} : null)}
{ setError(''); generateKey(); setKeyOpen(true); }}>{tr(serving.access.apiKeySet ? 'Change key' : 'Set key')}{tr(serving.access.apiKeySet ? { setError(''); setRemoveKeyOpen(true); }}>{tr("Remove key")} : null)}
{tr(serving.access.otherDevices ? {tr("Keep a key while the API is available to other devices.")} : null)}
+ }}/> : null)}
{tr("Status")}
{tr(serving.running ? 'API listening' : 'API stopped')} · {tr(multipleModels ? `${runtime?.instances.length} models loaded` : loaded ? 'Model ready' : 'Model not ready')}
{tr("Local network")}
{tr(serving.sharing?.active ? "Shared on local network" : "Off")} { setError(''); setSharingOpen(true); }}>{tr(serving.sharing?.active ? "Manage / stop" : "Share")}
{tr(serving.tunnel?.status === "connected" && serving.tunnel.url ?
{tr("Cloudflare tunnel")}
{serving.tunnel.url} void navigator.clipboard.writeText(serving.tunnel!.url!)}/> setCloudflareOpen(true)}/>
: serving.tunnel?.status === "starting" ?
{tr("Cloudflare tunnel")}
{tr("Connecting\u2026")}
: null)}
{tr("API key")}
{tr(serving.access.apiKeySet ? {tr("Required \u00B7 ")}{tr(serving.access.apiKeyHint)} : null)}
{ setError(''); generateKey(); setKeyOpen(true); }}>{tr(serving.access.apiKeySet ? 'Change key' : 'Set key')}{tr(serving.access.apiKeySet ? { setError(''); setRemoveKeyOpen(true); }}>{tr("Remove key")} : null)}
{tr(serving.access.otherDevices ? {tr("Keep a key while the API is available to other devices.")} : null)}
{tr(multipleModels ?

{tr("Available models")}

{tr("One API URL \u00B7 route by model ID")}
{tr(runtime?.instances.length ?
{tr(runtime.instances.map(i =>
{tr(i.family)}{tr(i.name)} · {tr(i.memory.context / 1024)}{tr("K \u00B7 ")}{tr(deviceLabel(i.gpuIds, hardware))}
{i.apiModelId} void copyConnectionValue(i.apiModelId, 'Model ID')}/>
))}
:

{tr("Load a model in Models to make it available here.")}

)}

{tr("Set ")}model{tr(" in each request. Each model has its own queue.")}{tr(runtime?.mode === 'simulated' ? ' Design preview · responses are illustrative.' : '')}

@@ -116,7 +116,7 @@ export function ServingScreen() { {tr(error ? : null)}
- !pending && setRemoveKeyOpen(false)} actions={<> setRemoveKeyOpen(false)}>{tr("Keep key")} void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}}>

{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}

{tr(error ? : null)}
+ !pending && setRemoveKeyOpen(false)} actions={<> setRemoveKeyOpen(false)}>{tr("Keep key")} void operation(async () => { await setServingAccess({ apiKey: null }); setRemoveKeyOpen(false); })}>{tr(pending ? 'Removing…' : 'Remove key')}}>

{tr("Apps on this computer will be able to send requests without a key. Existing clients can keep their current key field.")}

{tr(serving.access.otherDevices ?

{tr(" Without an API key, anyone who can reach this address can use your model.")}

: null)}{tr(error ? : null)}
setCloudflareOpen(false)} onCreateKey={() => { setReturnToTunnel(true); setCloudflareOpen(false); generateKey(); setKeyOpen(true); }}/> ; } From d69c9c4b4fdff755a8f41c753ff9c4319dd61c00 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:29:51 +0200 Subject: [PATCH 03/27] Settings > Storage shows the Documents-fallback notice (app.modelsDirNotice) with the existing storage notice line --- apps/host/src/components/SettingsStorage.tsx | 1 + apps/host/src/lib/types.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsx index ba0dab55..2ea7cfdf 100644 --- a/apps/host/src/components/SettingsStorage.tsx +++ b/apps/host/src/components/SettingsStorage.tsx @@ -95,6 +95,7 @@ export function SettingsStorage() {
{tr(directoryPending ? 'Checking files…' : changing && loadedCount > 0 ? 'Unload and change directory' : changing ? 'Use this directory' : 'Check folder')}
: void saveDirectory(currentDirectory)}>{tr(directoryPending ? 'Checking files…' : 'Check folder')})} {tr(directoryBlocked && !directoryPending ?

{tr(!lifecycle.allowed ? lifecycle.reason : 'Finish or cancel downloads and loading to change the directory.')}

: null)} + {tr(state.setup?.app.modelsDirNotice && !notice ?

{tr(state.setup.app.modelsDirNotice)}

: null)} {tr(notice ?

{tr(notice)}

: null)} {tr(directoryError ? : null)} diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index d5e8b4df..b4b37058 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -495,7 +495,7 @@ export interface SetupState { step: number; completedAt?: string; history: { step: number; at: string }[]; - app: { version: string; modelsDir: string; dataDir: string }; + app: { version: string; modelsDir: string; dataDir: string; modelsDirNotice?: string }; } export interface EngineEvent { From 703daada09bea8d7b099507d53927fc33f5702a2 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:29:52 +0200 Subject: [PATCH 04/27] Locales: keyless-sharing, own-GGUF, ports and models-folder strings in en, de, es, ja, ko, pt, ru, zh (s8301-s8313) --- apps/host/src/locales/de.json | 15 ++++++++++++++- apps/host/src/locales/en.json | 15 ++++++++++++++- apps/host/src/locales/es.json | 15 ++++++++++++++- apps/host/src/locales/ja.json | 15 ++++++++++++++- apps/host/src/locales/ko.json | 15 ++++++++++++++- apps/host/src/locales/pt.json | 15 ++++++++++++++- apps/host/src/locales/ru.json | 15 ++++++++++++++- apps/host/src/locales/zh.json | 15 ++++++++++++++- 8 files changed, 112 insertions(+), 8 deletions(-) diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 0c775832..43b4b39e 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3346,5 +3346,18 @@ "s8257": "alle {0} Min.", "s8258": "Diese Strata-Engine hat keinen Code für die Grafikkarte, die sie verwenden wollte.", "s8259": "Wähle unter „Ausführen auf“ eine andere Karte, oder öffne die Details: Dort steht, welche Karten gefunden wurden und wofür die Engine gebaut ist.", - "s8260": "Dieser Schalter bewirkt in der App nichts. Webseiten beliebiger Seiten können die unter „API-Server“ gezeigte API schon aufrufen. Um nur bestimmte Seiten zuzulassen oder den eigenen Server der Engine (Port 8080) zu nutzen, tragen Sie \"cors_origins\": [\"https://ihre.seite\"] in die Konfigurationsdatei des Modells ein." + "s8260": "Dieser Schalter bewirkt in der App nichts. Webseiten beliebiger Seiten können die unter „API-Server“ gezeigte API schon aufrufen. Um nur bestimmte Seiten zuzulassen oder den eigenen Server der Engine (Port 8080) zu nutzen, tragen Sie \"cors_origins\": [\"https://ihre.seite\"] in die Konfigurationsdatei des Modells ein.", + "s8301": "API-Schlüssel erstellen (empfohlen)", + "s8302": "Ohne API-Schlüssel kann jedes Gerät in diesem Netzwerk Ihr Modell nutzen.", + "s8303": "Es wird nur die Inferenz-API freigegeben. Clients brauchen Ihren API-Schlüssel, sofern einer gesetzt ist. Nutzen Sie ein vertrauenswürdiges lokales Netzwerk; diese Verbindung verwendet HTTP.", + "s8304": "Erstellen Sie einen Schlüssel, um Ihre API zu schützen. Danach kehren Sie hierher zurück. Sie können auch ohne Schlüssel fortfahren, dann kann aber jeder, der den Link findet, Ihr Modell nutzen.", + "s8305": "Sie haben schon ein unterstütztes Modell auf diesem Computer? Wählen Sie den Ordner mit den Dateien oder eine der .gguf-Dateien. Strata prüft sie, bereitet das Modell vor und lädt es. Es wird nichts kopiert oder heruntergeladen.", + "s8306": "Ordner mit den GGUF-Dateien oder eine .gguf-Datei", + "s8307": "Vollständiger Pfad zum Ordner oder zur Datei", + "s8308": "Ohne API-Schlüssel kann jeder, der diese Adresse erreicht, Ihr Modell nutzen.", + "s8309": "Strata konnte {0} nicht für Modelle verwenden ({1}); die Modelle werden daher in {2} abgelegt. Sie können in den Einstellungen einen anderen Ordner wählen.", + "s8310": "Port {0} wird bereits verwendet. Strata läuft vielleicht schon; schließen Sie es oder das andere Programm, oder starten Sie Strata mit einem anderen Port (STRATA_PORT).", + "s8311": "Windows oder eine Firewall erlaubt Strata nicht, Port {0} zu verwenden. Hyper-V, WSL und Docker reservieren Portbereiche für sich (siehe \"netsh int ipv4 show excludedportrange protocol=tcp\"). Starten Sie Strata mit einem anderen Port (STRATA_PORT), zum Beispiel 8801.", + "s8312": "{0} ist keine Adresse dieses Computers, daher kann Strata dort nicht lauschen. Prüfen Sie STRATA_BIND.", + "s8313": "Strata kann auf {0}:{1} nicht lauschen ({2})." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index a11ad97a..b2fb3cd9 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3346,5 +3346,18 @@ "s8257": "every {0} min", "s8258": "This Strata engine has no code for the graphics card it tried to use.", "s8259": "Pick another card under Run on, or open Details to see which cards were found and what the engine is built for.", - "s8260": "This switch does nothing in the app. Web pages from any site can already call the API shown under Serving. To allow only some sites, or to use the engine’s own server (port 8080), add \"cors_origins\": [\"https://your.site\"] to the model’s config file." + "s8260": "This switch does nothing in the app. Web pages from any site can already call the API shown under Serving. To allow only some sites, or to use the engine’s own server (port 8080), add \"cors_origins\": [\"https://your.site\"] to the model’s config file.", + "s8301": "Create an API key (recommended)", + "s8302": "Without an API key, any device on this network can use your model.", + "s8303": "Only the inference API is shared. Clients need your API key when one is set. Use a trusted local network; this connection uses HTTP.", + "s8304": "Create a key to protect your API. You’ll return here when it’s ready. You can also continue without one, but anyone who finds the link can then use your model.", + "s8305": "Already have a supported model on this computer? Choose the folder that holds its files, or one of its .gguf files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.", + "s8306": "Folder with the GGUF files, or one .gguf file", + "s8307": "Full path to the folder or the file", + "s8308": "Without an API key, anyone who can reach this address can use your model.", + "s8309": "Strata could not use {0} for models ({1}), so models go to {2}. You can pick another folder in Settings.", + "s8310": "Port {0} is already in use. Strata may already be running; close it or the other program, or start Strata with another port (STRATA_PORT).", + "s8311": "Windows or a firewall does not let Strata use port {0}. Hyper-V, WSL and Docker keep ranges of ports for themselves (see \"netsh int ipv4 show excludedportrange protocol=tcp\"). Start Strata with another port (STRATA_PORT), for example 8801.", + "s8312": "{0} is not an address of this computer, so Strata cannot listen on it. Check STRATA_BIND.", + "s8313": "Strata cannot listen on {0}:{1} ({2})." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index e6723f68..7abc032b 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3346,5 +3346,18 @@ "s8257": "cada {0} min", "s8258": "Este motor de Strata no tiene código para la tarjeta gráfica que intentó usar.", "s8259": "Elige otra tarjeta en «Ejecutar en», o abre los detalles para ver qué tarjetas se encontraron y para cuáles está compilado el motor.", - "s8260": "Este interruptor no hace nada en la app. Las páginas web de cualquier sitio ya pueden llamar a la API que se muestra en Servicio. Para permitir solo algunos sitios, o para usar el servidor propio del motor (puerto 8080), añada \"cors_origins\": [\"https://su.sitio\"] al archivo de configuración del modelo." + "s8260": "Este interruptor no hace nada en la app. Las páginas web de cualquier sitio ya pueden llamar a la API que se muestra en Servicio. Para permitir solo algunos sitios, o para usar el servidor propio del motor (puerto 8080), añada \"cors_origins\": [\"https://su.sitio\"] al archivo de configuración del modelo.", + "s8301": "Crear una clave de API (recomendado)", + "s8302": "Sin una clave de API, cualquier dispositivo de esta red puede usar tu modelo.", + "s8303": "Solo se comparte la API de inferencia. Los clientes necesitan tu clave de API si hay una. Usa una red local de confianza; esta conexión usa HTTP.", + "s8304": "Crea una clave para proteger tu API. Volverás aquí cuando esté lista. También puedes continuar sin ella, pero cualquiera que encuentre el enlace podrá usar tu modelo.", + "s8305": "¿Ya tienes un modelo compatible en este equipo? Elige la carpeta con sus archivos o uno de sus archivos .gguf. Strata los comprueba, prepara el modelo y lo carga. No se copia ni se descarga nada.", + "s8306": "Carpeta con los archivos GGUF, o un archivo .gguf", + "s8307": "Ruta completa de la carpeta o del archivo", + "s8308": "Sin una clave de API, cualquiera que pueda llegar a esta dirección podrá usar tu modelo.", + "s8309": "Strata no pudo usar {0} para los modelos ({1}), así que los modelos van a {2}. Puedes elegir otra carpeta en Ajustes.", + "s8310": "El puerto {0} ya está en uso. Puede que Strata ya se esté ejecutando; ciérralo o cierra el otro programa, o inicia Strata con otro puerto (STRATA_PORT).", + "s8311": "Windows o un cortafuegos no deja que Strata use el puerto {0}. Hyper-V, WSL y Docker reservan rangos de puertos para sí mismos (consulta \"netsh int ipv4 show excludedportrange protocol=tcp\"). Inicia Strata con otro puerto (STRATA_PORT), por ejemplo 8801.", + "s8312": "{0} no es una dirección de este equipo, así que Strata no puede escuchar en ella. Revisa STRATA_BIND.", + "s8313": "Strata no puede escuchar en {0}:{1} ({2})." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 8f527594..9c528cb7 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3346,5 +3346,18 @@ "s8257": "{0}分ごと", "s8258": "この Strata エンジンには、使おうとしたグラフィックスカード用のコードが含まれていません。", "s8259": "「実行先」で別のカードを選ぶか、「詳細」を開いて、見つかったカードとエンジンの対応状況を確認してください。", - "s8260": "このスイッチはアプリでは何もしません。どのサイトのWebページも、「配信」に表示されるAPIをすでに呼び出せます。一部のサイトだけを許可したい場合や、エンジン自身のサーバー(ポート8080)を使う場合は、モデルの設定ファイルに \"cors_origins\": [\"https://your.site\"] を追加してください。" + "s8260": "このスイッチはアプリでは何もしません。どのサイトのWebページも、「配信」に表示されるAPIをすでに呼び出せます。一部のサイトだけを許可したい場合や、エンジン自身のサーバー(ポート8080)を使う場合は、モデルの設定ファイルに \"cors_origins\": [\"https://your.site\"] を追加してください。", + "s8301": "APIキーを作成する(推奨)", + "s8302": "APIキーがないと、このネットワーク上のどの機器でもモデルを使えます。", + "s8303": "共有されるのは推論APIだけです。キーを設定している場合、クライアントにはAPIキーが必要です。信頼できるローカルネットワークで使ってください。この接続はHTTPを使います。", + "s8304": "APIを守るキーを作成します。準備ができたらここに戻ります。キーなしで続けることもできますが、その場合はリンクを見つけた人なら誰でもモデルを使えます。", + "s8305": "対応モデルがすでにこのコンピューターにありますか?ファイルがあるフォルダー、または.ggufファイルを1つ選んでください。Strataがファイルを確認し、モデルを準備して読み込みます。コピーやダウンロードは行いません。", + "s8306": "GGUFファイルのフォルダー、または.ggufファイル1つ", + "s8307": "フォルダーまたはファイルのフルパス", + "s8308": "APIキーがないと、このアドレスに接続できる人なら誰でもモデルを使えます。", + "s8309": "Strataは{0}をモデルの保存先として使えなかったため({1})、モデルは{2}に保存されます。別のフォルダーは設定で選べます。", + "s8310": "ポート{0}はすでに使われています。Strataがすでに起動しているかもしれません。それか別のプログラムを閉じるか、別のポート(STRATA_PORT)でStrataを起動してください。", + "s8311": "Windowsまたはファイアウォールが、Strataによるポート{0}の使用を許可していません。Hyper-V、WSL、Dockerは一部のポート範囲を自分用に確保します(\"netsh int ipv4 show excludedportrange protocol=tcp\"で確認できます)。別のポート(STRATA_PORT)、たとえば8801でStrataを起動してください。", + "s8312": "{0}はこのコンピューターのアドレスではないため、Strataはそこで待ち受けできません。STRATA_BINDを確認してください。", + "s8313": "Strataは{0}:{1}で待ち受けできません({2})。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 45f2b16e..72fee946 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3346,5 +3346,18 @@ "s8257": "{0}분마다", "s8258": "이 Strata 엔진에는 사용하려던 그래픽 카드용 코드가 없습니다.", "s8259": "“실행 장치”에서 다른 카드를 고르거나, “세부 정보”에서 찾은 카드와 엔진이 지원하는 카드를 확인하세요.", - "s8260": "이 스위치는 앱에서는 아무 일도 하지 않습니다. 어느 사이트의 웹 페이지든 ‘API 서비스’에 표시된 API를 이미 호출할 수 있습니다. 일부 사이트만 허용하거나 엔진의 자체 서버(포트 8080)를 쓰려면 모델의 설정 파일에 \"cors_origins\": [\"https://your.site\"] 를 추가하세요." + "s8260": "이 스위치는 앱에서는 아무 일도 하지 않습니다. 어느 사이트의 웹 페이지든 ‘API 서비스’에 표시된 API를 이미 호출할 수 있습니다. 일부 사이트만 허용하거나 엔진의 자체 서버(포트 8080)를 쓰려면 모델의 설정 파일에 \"cors_origins\": [\"https://your.site\"] 를 추가하세요.", + "s8301": "API 키 만들기(권장)", + "s8302": "API 키가 없으면 이 네트워크의 모든 기기가 모델을 사용할 수 있습니다.", + "s8303": "추론 API만 공유됩니다. 키를 설정한 경우 클라이언트에 API 키가 필요합니다. 신뢰할 수 있는 로컬 네트워크에서 사용하세요. 이 연결은 HTTP를 사용합니다.", + "s8304": "API를 보호할 키를 만드세요. 준비되면 이 화면으로 돌아옵니다. 키 없이 계속할 수도 있지만, 그러면 링크를 찾은 누구나 모델을 사용할 수 있습니다.", + "s8305": "이 컴퓨터에 이미 지원되는 모델이 있나요? 파일이 있는 폴더나 .gguf 파일 하나를 선택하세요. Strata가 파일을 확인하고 모델을 준비해 불러옵니다. 복사하거나 다운로드하지 않습니다.", + "s8306": "GGUF 파일이 있는 폴더 또는 .gguf 파일 하나", + "s8307": "폴더 또는 파일의 전체 경로", + "s8308": "API 키가 없으면 이 주소에 접속할 수 있는 누구나 모델을 사용할 수 있습니다.", + "s8309": "Strata가 {0}을(를) 모델 폴더로 사용할 수 없어({1}) 모델을 {2}에 저장합니다. 설정에서 다른 폴더를 고를 수 있습니다.", + "s8310": "포트 {0}을(를) 이미 사용 중입니다. Strata가 이미 실행 중일 수 있습니다. 해당 프로그램을 닫거나 다른 포트(STRATA_PORT)로 Strata를 시작하세요.", + "s8311": "Windows 또는 방화벽이 Strata의 포트 {0} 사용을 허용하지 않습니다. Hyper-V, WSL, Docker는 일부 포트 범위를 자체적으로 예약합니다(\"netsh int ipv4 show excludedportrange protocol=tcp\" 참고). 다른 포트(STRATA_PORT), 예를 들어 8801로 Strata를 시작하세요.", + "s8312": "{0}은(는) 이 컴퓨터의 주소가 아니어서 Strata가 해당 주소에서 연결을 받을 수 없습니다. STRATA_BIND를 확인하세요.", + "s8313": "Strata가 {0}:{1}에서 연결을 받을 수 없습니다({2})." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 3c4acce6..ec091c50 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3346,5 +3346,18 @@ "s8257": "a cada {0} min", "s8258": "Este motor do Strata não tem código para a placa de vídeo que tentou usar.", "s8259": "Escolha outra placa em «Executar em» ou abra os detalhes para ver quais placas foram encontradas e para quais o motor foi compilado.", - "s8260": "Este botão não faz nada no app. Páginas web de qualquer site já podem chamar a API mostrada em API. Para permitir só alguns sites, ou para usar o servidor próprio do motor (porta 8080), adicione \"cors_origins\": [\"https://seu.site\"] ao arquivo de configuração do modelo." + "s8260": "Este botão não faz nada no app. Páginas web de qualquer site já podem chamar a API mostrada em API. Para permitir só alguns sites, ou para usar o servidor próprio do motor (porta 8080), adicione \"cors_origins\": [\"https://seu.site\"] ao arquivo de configuração do modelo.", + "s8301": "Criar uma chave de API (recomendado)", + "s8302": "Sem uma chave de API, qualquer dispositivo desta rede pode usar o seu modelo.", + "s8303": "Apenas a API de inferência é compartilhada. Os clientes precisam da sua chave de API quando houver uma. Use uma rede local confiável; esta conexão usa HTTP.", + "s8304": "Crie uma chave para proteger a sua API. Você voltará aqui quando ela estiver pronta. Também pode continuar sem ela, mas qualquer pessoa que encontrar o link poderá usar o seu modelo.", + "s8305": "Já tem um modelo compatível neste computador? Escolha a pasta com os arquivos ou um dos arquivos .gguf. O Strata verifica os arquivos, prepara o modelo e o carrega. Nada é copiado nem baixado.", + "s8306": "Pasta com os arquivos GGUF ou um arquivo .gguf", + "s8307": "Caminho completo da pasta ou do arquivo", + "s8308": "Sem uma chave de API, qualquer pessoa que consiga acessar este endereço pode usar o seu modelo.", + "s8309": "O Strata não conseguiu usar {0} para os modelos ({1}), então os modelos vão para {2}. Você pode escolher outra pasta em Configurações.", + "s8310": "A porta {0} já está em uso. O Strata pode já estar em execução; feche-o ou o outro programa, ou inicie o Strata com outra porta (STRATA_PORT).", + "s8311": "O Windows ou um firewall não deixa o Strata usar a porta {0}. Hyper-V, WSL e Docker reservam faixas de portas para si (veja \"netsh int ipv4 show excludedportrange protocol=tcp\"). Inicie o Strata com outra porta (STRATA_PORT), por exemplo 8801.", + "s8312": "{0} não é um endereço deste computador, então o Strata não pode escutar nele. Verifique STRATA_BIND.", + "s8313": "O Strata não consegue escutar em {0}:{1} ({2})." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index e19c5da5..f040955b 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3346,5 +3346,18 @@ "s8257": "каждые {0} мин", "s8258": "В этом движке Strata нет кода для видеокарты, которую он попытался использовать.", "s8259": "Выберите другую карту в разделе «Запускать на» или откройте «Подробности»: там указано, какие карты найдены и для каких собран движок.", - "s8260": "Этот переключатель в приложении ничего не делает. Веб-страницы любого сайта уже могут обращаться к API, который показан в «API». Чтобы разрешить только некоторые сайты или использовать собственный сервер движка (порт 8080), добавьте \"cors_origins\": [\"https://your.site\"] в файл настроек модели." + "s8260": "Этот переключатель в приложении ничего не делает. Веб-страницы любого сайта уже могут обращаться к API, который показан в «API». Чтобы разрешить только некоторые сайты или использовать собственный сервер движка (порт 8080), добавьте \"cors_origins\": [\"https://your.site\"] в файл настроек модели.", + "s8301": "Создать ключ API (рекомендуется)", + "s8302": "Без ключа API любое устройство в этой сети сможет пользоваться вашей моделью.", + "s8303": "Доступен только API инференса. Если ключ задан, клиентам нужен ваш ключ API. Используйте доверенную локальную сеть: это соединение работает по HTTP.", + "s8304": "Создайте ключ, чтобы защитить API. Когда он будет готов, вы вернётесь сюда. Можно продолжить и без ключа, но тогда любой, кто найдёт ссылку, сможет пользоваться вашей моделью.", + "s8305": "Уже есть поддерживаемая модель на этом компьютере? Выберите папку с её файлами или один из файлов .gguf. Strata проверит их, подготовит модель и загрузит её. Ничего не копируется и не скачивается.", + "s8306": "Папка с файлами GGUF или один файл .gguf", + "s8307": "Полный путь к папке или файлу", + "s8308": "Без ключа API любой, кто может обратиться к этому адресу, сможет пользоваться вашей моделью.", + "s8309": "Strata не смогла использовать {0} для моделей ({1}), поэтому модели сохраняются в {2}. Другую папку можно выбрать в настройках.", + "s8310": "Порт {0} уже занят. Возможно, Strata уже запущена; закройте её или другую программу либо запустите Strata с другим портом (STRATA_PORT).", + "s8311": "Windows или брандмауэр не разрешает Strata использовать порт {0}. Hyper-V, WSL и Docker резервируют для себя диапазоны портов (см. \"netsh int ipv4 show excludedportrange protocol=tcp\"). Запустите Strata с другим портом (STRATA_PORT), например 8801.", + "s8312": "{0} не является адресом этого компьютера, поэтому Strata не может его прослушивать. Проверьте STRATA_BIND.", + "s8313": "Strata не может прослушивать {0}:{1} ({2})." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index dfcd0e46..7f426262 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3346,5 +3346,18 @@ "s8257": "每 {0} 分钟", "s8258": "此 Strata 引擎没有适用于它尝试使用的显卡的代码。", "s8259": "请在“运行于”中选择另一块显卡,或打开详情,查看找到了哪些显卡以及引擎支持哪些显卡。", - "s8260": "这个开关在应用中不起作用。任何网站的网页都已经可以调用“API 服务”页面显示的 API。如果只想允许部分网站,或要使用引擎自带的服务器(端口 8080),请在模型的配置文件中添加 \"cors_origins\": [\"https://your.site\"]。" + "s8260": "这个开关在应用中不起作用。任何网站的网页都已经可以调用“API 服务”页面显示的 API。如果只想允许部分网站,或要使用引擎自带的服务器(端口 8080),请在模型的配置文件中添加 \"cors_origins\": [\"https://your.site\"]。", + "s8301": "创建 API 密钥(推荐)", + "s8302": "没有 API 密钥时,此网络中的任何设备都可以使用你的模型。", + "s8303": "只共享推理 API。如果设置了密钥,客户端需要你的 API 密钥。请在可信的本地网络中使用;此连接使用 HTTP。", + "s8304": "创建一个密钥来保护你的 API。准备好后你会回到这里。你也可以不创建而继续,但这样任何找到链接的人都可以使用你的模型。", + "s8305": "这台电脑上已经有受支持的模型了吗?请选择存放其文件的文件夹,或其中一个 .gguf 文件。Strata 会检查文件、准备模型并加载。不会复制或下载任何内容。", + "s8306": "包含 GGUF 文件的文件夹,或一个 .gguf 文件", + "s8307": "文件夹或文件的完整路径", + "s8308": "没有 API 密钥时,任何能访问此地址的人都可以使用你的模型。", + "s8309": "Strata 无法使用 {0} 存放模型({1}),因此模型会保存到 {2}。你可以在设置中选择其他文件夹。", + "s8310": "端口 {0} 已被占用。Strata 可能已经在运行;请关闭它或另一个程序,或用其他端口(STRATA_PORT)启动 Strata。", + "s8311": "Windows 或防火墙不允许 Strata 使用端口 {0}。Hyper-V、WSL 和 Docker 会为自己保留一些端口范围(请查看 \"netsh int ipv4 show excludedportrange protocol=tcp\")。请用其他端口(STRATA_PORT)启动 Strata,例如 8801。", + "s8312": "{0} 不是这台电脑的地址,Strata 无法在其上监听。请检查 STRATA_BIND。", + "s8313": "Strata 无法在 {0}:{1} 上监听({2})。" } From 4fd5b0646df6f2150840e5aa15bbd2e20580388d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:29:52 +0200 Subject: [PATCH 05/27] setup.py: the three remaining os.replace calls use atomic.replace --- setup.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index ea81f4c1..787c4a92 100644 --- a/setup.py +++ b/setup.py @@ -63,6 +63,7 @@ import zipfile from pathlib import Path from strata_control import acquisition +from strata_control import atomic from strata_control import draft_layer from strata_control.discovery import in_trash from strata_control import user_args @@ -2108,7 +2109,7 @@ def _save_pieces(part: Path, total: int, done: set): side = part.with_name(part.name + ".chunks") tmp = side.with_name(side.name + ".tmp") tmp.write_text(json.dumps({"v": 1, "total": total, "chunk": DL_CHUNK, "done": _ranges(done)}), encoding="utf-8") - os.replace(tmp, side) + atomic.replace(tmp, side) except OSError: pass # only costs re-downloading a few pieces after a stop @@ -5436,7 +5437,7 @@ def move_into(src: Path, dst: Path) -> None: if not dst.exists(): try: dst.parent.mkdir(parents=True, exist_ok=True) - os.replace(src, dst) + atomic.replace(src, dst) return except OSError: if not src.is_dir(): @@ -5606,7 +5607,7 @@ def write_config(path: Path, cfg: dict): a setup stopped half-way (a closed window, a full disk) never leaves an empty strata-*.json behind.""" tmp = path.with_name(path.name + ".tmp") tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") - os.replace(tmp, path) + atomic.replace(tmp, path) # #629: the run config's keys setup writes itself (and rewrites on every setup run); any other key is the user's - a From 4aabf3b8f5b4183dac13d83965ca362b2abb2b8f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:31:01 +0200 Subject: [PATCH 06/27] Release notes 0.2.2: DRAFT paragraphs for the merged streams --- docs/release-notes-0.2.2.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/release-notes-0.2.2.md b/docs/release-notes-0.2.2.md index 77499fea..e9f04218 100644 --- a/docs/release-notes-0.2.2.md +++ b/docs/release-notes-0.2.2.md @@ -1,6 +1,17 @@ -**0.2.2 (draft).** Only the items of the `f-022-rx6000` and `f-022-numa` branches are written here; the coordinator adds the rest. +**0.2.2 (DRAFT, not released).** Written from the notes of each merged stream; the coordinator edits it before the release. Items of the `f-022-iopf`, `f-022-flow`, `f-022-pkgspeed` and `f-022-modelsdir` branches are not merged and are not listed. ## What is new - **An engine package for the RX 6000 series (built, not tested on a real RX 6000 card).** Linux has `rx6000` and Windows has `rdna2`, each with GPU code for gfx1030 and gfx1031 (RX 6800, 6900 and 6950 series, RX 6700 XT). They are offered to a PC whose card reports one of those two and to no other: the RX 7000, RX 9000 and Strix Halo packages are unchanged, and a PC with an RX 7000 or 9000 card next to an RX 6000 card keeps the package it had. The engine runs plain kernels on these cards (RDNA2 has no matrix cores, so none of the RX 7000 / RX 9000 or Radeon 780M prompt paths apply) and plain hipBLAS (hipBLASLt ships no kernels for gfx1030, so there is no tuning table). Setup and the app say once that this package was built and not tested on a real RX 6000 card. What was checked: the Linux package builds, every program in it has code for exactly gfx1030 and gfx1031, the rocBLAS kernel files for both are in it, every library it imports is in the package or belongs to the system, and the whole engine (all targets, tests included) compiles for gfx1030 and gfx1031. What was not: a model on an RX 6000 card, on either system, and the Windows package itself (the Windows build scripts take the new architecture list, but no Windows `rdna2` package has been built). Earlier reports on these cards came from people who built the engine from source ([docs/AMD_HIP.md](AMD_HIP.md#rdna2-gfx1030)). If something goes wrong, open an issue with the end of `strata-.log`. - **The CPU expert pool splits per NUMA node on a machine with two or more NUMA nodes (built from the report in #3201, not tested on a two-socket machine).** Until now the pool kept its workers on the host thread's socket, because workers on the other socket read the experts across the link and were slower. The split gives each socket its own slice of the pool with its own task counter, and places each socket's half of every CPU-side expert in that socket's memory, so a slice reads local memory only. The reporter measured +10 to +14 % decode on a dual Xeon Gold 6226 (59.3 against 54.05 tok/s with the IOMMU in passthrough); a second reporter's dual Xeon E5-2670 v2 preferred more workers across both sockets, which the split also uses. It starts by itself when the machine has two or more NUMA nodes with CPUs and runs only when it can (Linux, two nodes, pinned threads, enough free memory per node); otherwise the pool is exactly what it was and the log says why. **A machine with one NUMA node runs the same code path as 0.2.1:** the identity gate (10 prompts, exact_pp 4K and 20K) is byte-identical and the single-request speed A/B is not slower on the one-node test boxes (numbers in the notes of the branch). `STRATA_NUMA_POOL=0` turns the split off; `STRATA_NUMA_SPLIT=1` still asks for it on any machine. The start-up log says what it did: `NUMA pool on: 2 NUMA nodes found ...` or `NUMA pool off: `. On Windows the node count is read but the split itself is Linux-only for now, so a two-node Windows PC logs the reason and runs as before. The logic runs in unit tests on made-up two-, three- and four-node machines; we have no two-socket machine, so the placement and the speed on real ones are the reporters' numbers, not ours. Do not wrap the server in `numactl --cpunodebind` or `--membind`: it pulls both halves onto one node. Thanks to baptisterajaut for the branch this is built on, and to xrip and Tworks25 for their numbers. Please send the start-up lines and a decode run with and without `STRATA_NUMA_POOL=0` from a two-socket machine. +- **The API key is optional.** The server, `strata launch`, the Terminal and the app no longer refuse to share without a key. Say so (`--no-api-key`, or `"api_key": "none"` in the server config) and it starts, with one plain warning that anyone who can reach the port can use the model and its tools; a public Cloudflare address gets a stronger one. The Terminal and the app still offer to make a key and do by default. In the app, Remove key now also works while local sharing or the tunnel runs. Fixes the refusals reported in #3198 and #3401. +- **Your own GGUF files load again.** "Use a local GGUF", `strata launch --model-path` and `strata models import` now accept what `setup.py --gguf-dir` always accepted: a folder with the files, the folder above it (a whole Hugging Face download, or an old Strata data folder), or one `.gguf` file. Unsloth sets whose first file holds no tensors, linked files (Hugging Face cache, Ollama) and folders with several sizes work; when a file is unusable, the message names the file and says why. Setup no longer deletes your own file when its checksum differs. The download and prepare steps use plain words, the checksum pass shows its own progress instead of a stuck 99 % download bar, and a model folder you pick (a whole drive becomes `D:\Strata`) is accepted by the installer whatever it is called. Reports #3316, #3292, #3190. +- **Problems with the computer's own setup are repaired or explained, not refused.** If the Windows runtime folder lists another account, Strata locks it down itself instead of stopping. A Documents folder that cannot be used (Controlled folder access, an offline OneDrive) falls back to the Strata home folder and Settings > Storage says so. A port that is taken or reserved gets one sentence with the next step. Local requests ignore a system proxy. File-in-use errors and a full disk say what happened. `strata launch` asks plain questions in a terminal that reports a tty late. `strata update` copes with a slow `--version`, a busy graphics card is not held against an engine, pre-release Control builds hand over correctly, and a wrong PC clock is named as the reason a feed or certificate looks bad. install.sh and install.ps1 give clearer messages (ARM, TLS 1.2, proxy credentials, no `tar.exe`). +- **One speed number everywhere.** Answer speed is every token the model produced (thinking, answer, tool calls; with MTP the kept tokens) divided by decode time. The chat footer, the monitor, the model API and the server console used different definitions: an agent turn read about 632 tok/s in 0.2.0-beta, then fell to the real 50 to 75 in 0.2.1, and some places divided by the whole request, which reads about half. The footer now shows the last reply's own speed, the popover has a "Prompt reading" row, and the console no longer prints a million tok/s for a one-token reply. +- **`strata bench run`, first real runs.** Run on two test PCs with the 0.2.1 release, it showed that the release archive carried no commit (every run was `nonconforming`), that the drive lookup failed on LVM, that the CUDA runtime was missing from the nvidia-smi 615 output, and that the engine log in the result was empty. All four are fixed, the protocol text now says 2 to 4 minutes for the required part, and results get a Capped column for answers that stopped at the token limit. Package building refuses to make a distributable archive without a commit. +- **`strata update` takes effect on the next command.** When an update installs a newer Control, the Terminal hands over to it by itself. Terminals 0.1.46 and 0.1.46.1 cannot do this (the code is in the Terminal): reinstall the Terminal once. +- **A stale update notice goes away.** After a version change the app and the Terminal no longer keep showing an offer for a version you already have. +- **Idle GPU time was measured, with no default change.** On a two-card test PC decode leaves about half of the card time idle (batch 51 %), on a one-card PC 5 %. Overlap gave +0.3, +2.1 and -0.3 % against 2.8 % noise; pipeline windows and batch groups help in one case and cost 5 to 15 % in others, so nothing is switched on. Raw numbers are in `bench/results/2026-10-20-0.2.1-idle-gpu/`. +- **Small fixes.** `--mtp 2` is no longer checked as a folder (#3298); owner-only checks understand Windows account aliases (#3302, thanks jackbapa); `strata bench` with its own server sets its port (#3188); `calibrate` checks the report folder first (#3187); the CUDA 12.0 and 12.1 build error `__half_as_ushort` (#3368, thanks yudhanjaya, built with CUDA 12.6 only); the AMD picture reader builds position independent (#3359); the Mac setup installs cmake and ninja before it builds (#3403); the picture reader recreates its work folder if a temp cleaner removed it (#3370); a list of GPUs such as `"0,1"` is accepted (#3275, thanks MEsfits); `thinking_budget_tokens` is read (#2141) and the Anthropic usage numbers add up to the prompt (#2289, thanks xrip); an engine that cannot start is a 503 with the reason (#2496, thanks devYRPauli); the serve web page no longer scrolls sideways on a phone (#2971, thanks ctr-137); folders in a Trash or Recycle Bin are not offered as installs (#3410). Ported pull requests keep their authors. +- **From the issues labelled needs-format.** The app numbers Radeon cards the way HIP does when an integrated GPU is present (#3418). The hardware report counts physical cores, so the Work profile asks for 6 pool workers on an 8-core CPU instead of 12 (#3417; the reporter measured 27.9 against 38.1 tok/s). Three trellis CPU tests skip on a ggml without trellis types, and the ISA guard knows the AVX-512 files (#3358, tests and build only; the memory fault on gfx1011 is not touched). +- **Docker image build.** The terminal stage no longer needs git in the image (it failed with `FileNotFoundError`); the commit comes in as a build argument. From 3de97a88929a9f15bae85a1850d10f6f740cb734 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:41:30 +0200 Subject: [PATCH 07/27] Setup tests follow the merges: verify_sha256 takes own=, a tight disk margin warns and a real shortfall refuses --- tools/test_setup_unsloth.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index b758db55..c14b9ed8 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -193,7 +193,7 @@ class Base(unittest.TestCase): mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), mock.patch.object(setup, "download", fake_download), mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha, own=False: self.verified.append((s.name, size, sha))), mock.patch.object(setup, "run", fake_run), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), @@ -298,8 +298,17 @@ class Main(Base): import shutil shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) # #897: a draft layer already there needs less room (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) - with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing: no room + with mock.patch.dict(setup.MODELS[M], {"download_gb": 0.003}): # 1.5 MB still missing, but the 8 GB working room is only a guess (0.2.2): setup warns and goes on code, out, cfg = self.main(["--context", "8192"], free=8.001) + self.assertEqual(code, 0, out) + self.assertNotIn("not enough free disk space", out) + self.assertIn("little free disk space", out) + for f in d.iterdir(): + f.unlink() + shutil.rmtree(self.t / "data" / "mtp", ignore_errors=True) + (d / (list(setup.UNSLOTH_SHARDS)[0] + ".part")).write_bytes(b"x" * 1_500_000) + with mock.patch.dict(setup.MODELS[M], {"download_gb": 3.0}): # 1.5 GB of real files still to write, 1 GB free: refuse + code, out, cfg = self.main(["--context", "8192"], free=1.0) self.assertEqual(code, 1) self.assertIn("not enough free disk space", out) From 9dc1c963772ab39f008644c2ead25cf3740e4491 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:50:42 +0200 Subject: [PATCH 08/27] Own model files: a --model-path that is not there or holds no model is said in plain words before the engine or setup start (no 'missing /Qwen...gguf', no promise of a download), also in --plan and the screens --- strata_cli/launch/cmd.py | 8 +++-- strata_cli/launch/runner.py | 23 +++++++++++--- strata_cli/launch/screens.py | 7 +++-- strata_control/models.py | 52 +++++++++++++++++++++++++++++++ tests/terminal/test_launch.py | 14 ++++++--- tests/terminal/test_launch_tui.py | 15 +++++++-- 6 files changed, 104 insertions(+), 15 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 7abd7b79..36510792 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -559,6 +559,11 @@ def run_launch(a: argparse.Namespace) -> int: return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open)) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) + runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes) + try: + runner.check_own_files() # the person's own files: a wrong path is said now, and the files name the model + except LaunchError as e: + return fail(f"{e.text}" + (f" {e.next}" if e.next else ""), e.code) s, notes = apply_defaults(s, catalog) errors = [n for n in notes if n.level == "error"] if errors: @@ -569,8 +574,7 @@ def run_launch(a: argparse.Namespace) -> int: if not s.name: s.name = f"{s.model or 'model'} {S.context_label(s.context)}" move_data = _move_data_choice(a, s, catalog, machine) - runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, - move_data=move_data) + runner.s, runner.move_data = s, move_data if a.plan: plan = runner.plan() plan["warnings"] = [n.line() for n in notes] diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 709675b8..9cc81c48 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -331,6 +331,7 @@ class Runner: self.notices: list[str] = [] self.tune_result: dict | None = None self.config_path: Path | None = None + self._own_checked = False # ---- small helpers def emit(self, stage: str, text: str, pct: float | None = None, level: str = "info", **data: Any) -> None: @@ -625,8 +626,7 @@ class Runner: def ensure_model(self) -> Path: s, cat = self.s, self.catalog - if s.model_path: - self.resolve_own_files() + self.check_own_files() self.resolved_vision() if not (s.family and s.model): raise LaunchError("No model was chosen.", "Choose a model, or use --model NAME (strata launch --help lists them).", 2) @@ -641,7 +641,8 @@ class Runner: adopted = self.adopt_prepared_files("no Mac model installer in this Terminal") if adopted is not None: return adopted - self.emit("model", f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0) + self.emit("model", f"Preparing {title} from your model files…" if s.model_path else + f"Getting {title} ready (a download may be large; it continues where it stopped if interrupted)…", 0) argv = [self.python, str(cat.src / "setup.py"), *self.setup_args()] env = self._env() env.update(STRATA_CONTROL_INSTALL="1", STRATA_INSTALL_DIR=str(cat.root), PYTHONNOUSERSITE="1") @@ -695,7 +696,8 @@ class Runner: if adopted is not None: return adopted raise LaunchError("The model could not be installed." + (f" {err}." if err else ""), - hint or "Run it again: finished steps are skipped and a download continues where it stopped.", 6) + hint or ("Run it again: finished steps are skipped." if s.model_path else + "Run it again: finished steps are skipped and a download continues where it stopped."), 6) path, _desc = self.installed_state() if path is None: raise LaunchError("Setup finished but no run config was written for this model.", @@ -737,12 +739,22 @@ class Runner: self.emit("model", f"Used your prepared model files and wrote the run settings ({path.name}); this card is not one the built-in downloader sets up.", 100, level="warn") return path + def check_own_files(self) -> None: + """The person's own model files, looked at once: a path that is not there or holds no model is said in plain words first, and the + files are matched to the catalog model (resolve_own_files). Nothing else is done with a path that was already checked.""" + if self.s.model_path and not self._own_checked: + self.resolve_own_files() + self._own_checked = True + def resolve_own_files(self) -> None: """"Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot.""" from strata_control import models s = self.s + problem = models.own_path_problem(s.model_path) + if problem: # before the engine or setup are touched, with the path as typed + raise LaunchError(problem[0], problem[1], 2) given = bool(s.family and s.model) try: plan = models.plan_import(models.absolute(s.model_path)) @@ -760,7 +772,7 @@ class Runner: sel = plan.get("candidate_selection") or {} fam, model = sel.get("family"), sel.get("model") if not (fam and model) or plan.get("issues"): - issues = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" + issues = models.problem_words(plan.get("issues") or []) or "they are not a model Strata knows" more = " " + next((m for m in plan.get("messages") or [] if "holds" in m), "") raise LaunchError(f"These files cannot be used as they are ({issues}).{more.rstrip()}", "Choose the matching model in the list, or check that every shard is in the folder.", 5) @@ -941,6 +953,7 @@ class Runner: def run(self, *, start: bool = True) -> Result: try: + self.check_own_files() # a wrong --model-path is said before the engine is downloaded self.ensure_engine() self.check_cancel() base = self.ensure_model() diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index f2ec0db7..53730937 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -492,8 +492,11 @@ class ModelScreen(Base): self.check_own(path) def check_own(self, path: str) -> None: - from strata_cli.launch.runner import plain_issue from strata_control import models + problem = models.own_path_problem(path) + if problem: + self.say(f"{problem[0]} {problem[1]}", True) + return try: plan = models.plan_import(models.absolute(path)) except Exception as e: # noqa: BLE001 @@ -510,7 +513,7 @@ class ModelScreen(Base): self.menu().select((sel["family"], sel["model"])) self.paint() else: - why = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows" + why = models.problem_words(plan.get("issues") or []) or "they are not a model Strata knows" holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") self.say(f"These files cannot be used as they are ({why}). " + (holds + " " if holds else "") + "Check that every shard is in the folder, or pick a model from the list.", True) diff --git a/strata_control/models.py b/strata_control/models.py index 74914ed2..a42d8539 100644 --- a/strata_control/models.py +++ b/strata_control/models.py @@ -339,6 +339,34 @@ def plain_issue(code: str) -> str: return f"{name}: {words}" if name else words +def problem_words(issues: list, limit: int = 3) -> str: + """The problems of a file set as ONE sentence part, each said once: the same reason for several files names the files together + ("a.gguf and b.gguf: the file is cut short"), a reason that was already given is not given again, and a long list is cut with a count. + A folder that holds several models does not also say "not a size Strata knows".""" + codes = [str(x) for x in issues or []] + if "multiple_model_groups" in codes: + codes = [x for x in codes if x != "unrecognized_or_unsupported_model_variant"] + by_reason: dict[str, list[str]] = {} + for code in codes: + words = plain_issue(code) + name, sep, reason = words.partition(": ") + if sep and name.lower().endswith(".gguf"): + by_reason.setdefault(reason, []).append(name) + else: + by_reason.setdefault(words, []) + parts = [] + for reason, names in by_reason.items(): + if not names: + parts.append(reason) + elif len(names) <= 2: + parts.append(f"{' and '.join(names)}: {reason}") + else: + parts.append(f"{names[0]}, {names[1]} and {len(names) - 2} more files: {reason}") + if len(parts) > limit: + parts = parts[:limit] + [f"and {len(parts) - limit} more problem" + ("s" if len(parts) - limit > 1 else "")] + return "; ".join(parts) + + UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. " "Add it as a Custom model API (llama-server) instead.") # The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model). @@ -496,6 +524,30 @@ def import_target(picked: str, plan: dict) -> str: return plan.get("model_dir") or picked +def own_path_problem(picked: str) -> tuple[str, str] | None: + """(what is wrong, what to do) when the path a person gave for their own model files is not there or holds no model file, in plain + words; None when there is something to look at. Said before anything is installed or downloaded, with the path the person typed.""" + path = Path(absolute(picked)) + kind = "file" if path.name.lower().endswith(".gguf") else "folder" + try: + if not path.exists(): + if path.is_symlink(): + return (f"This {kind} is a shortcut to something that is not there any more: {path}.", + "Point it at the real folder, or at the .gguf file itself. Nothing was downloaded or changed.") + return (f"This {kind} does not exist: {path}.", + "Check the spelling, and that the drive or folder is connected (in Docker or a virtual machine it has to be shared with it). " + "Nothing was downloaded or changed.") + if path.is_dir(): + has_files = any(entry.name.lower().endswith(".gguf") for entry in os.scandir(path)) + if not has_files and not _folders_with_models(path): + return (f"There are no .gguf model files in {path}, nor in the folders inside it.", + "Point it at the folder that holds the model's .gguf files (names like ...-00001-of-00002.gguf), or at one of the files. " + "Nothing was downloaded or changed.") + except OSError: + return None + return None + + def plan_import(raw_path: str) -> dict: """Inspect a local candidate without copying, parsing tensors or adopting it. diff --git a/tests/terminal/test_launch.py b/tests/terminal/test_launch.py index a6255e8d..18fd91bd 100644 --- a/tests/terminal/test_launch.py +++ b/tests/terminal/test_launch.py @@ -795,10 +795,16 @@ class FlagsCommand(unittest.TestCase): self.assertEqual(p["settings"]["api_key"], "set") def test_model_path_is_used_instead_of_a_catalog_model(self): - p = self.plan("--model-path", "/data/models/IQ3_XXS") - s = p["settings"] - self.assertEqual(s["model_path"], str(Path("/data/models/IQ3_XXS"))) - self.assertIsNone(s["model"]) + import tempfile + from tests.terminal.test_own_files import IQ3XXS, gguf_bytes + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) / "IQ3_XXS" + folder.mkdir() + for n in IQ3XXS: + (folder / n).write_bytes(gguf_bytes(["IQ3_XXS"])) + s = self.plan("--model-path", str(folder))["settings"] + self.assertEqual(s["model_path"], str(folder)) + self.assertEqual((s["family"], s["model"]), ("qwen", "IQ3_XXS")) # the files say which model they are def test_no_choices_and_no_terminal_does_not_start_anything(self): with mock.patch.dict(os.environ, {"CI": "1"}), mock.patch.object(Runner, "run", side_effect=AssertionError("must not run")): diff --git a/tests/terminal/test_launch_tui.py b/tests/terminal/test_launch_tui.py index 003fb305..e9b0a6f5 100644 --- a/tests/terminal/test_launch_tui.py +++ b/tests/terminal/test_launch_tui.py @@ -259,7 +259,7 @@ class ModelStep(Base): async def case(app, pilot, ctx): await press(pilot, "enter", "o") self.assertIn("Type or paste the folder", text_of(app)) - with mock.patch("strata_control.models.plan_import", return_value=plan) as pi: + with mock.patch("strata_control.models.plan_import", return_value=plan) as pi, mock.patch("strata_control.models.own_path_problem", return_value=None): await typed(pilot, "/data/models/IQ3_XXS") await press(pilot, "enter") self.assertEqual(ctx.settings.model_path, os.path.abspath("/data/models/IQ3_XXS")) @@ -274,7 +274,7 @@ class ModelStep(Base): async def case(app, pilot, ctx): await press(pilot, "enter", "o") - with mock.patch("strata_control.models.plan_import", return_value=plan): + with mock.patch("strata_control.models.plan_import", return_value=plan), mock.patch("strata_control.models.own_path_problem", return_value=None): await typed(pilot, "/x") await press(pilot, "enter") t = flat(app) @@ -283,6 +283,17 @@ class ModelStep(Base): self.assertIsNone(ctx.settings.model_path) self.run_app(case) + def test_own_files_folder_that_is_not_there_is_named(self): + async def case(app, pilot, ctx): + await press(pilot, "enter", "o") + await typed(pilot, "/no/such/folder") + await press(pilot, "enter") + t = flat(app) + self.assertIn("does not exist", t) + self.assertIn("Nothing was downloaded", t) + self.assertIsNone(ctx.settings.model_path) + self.run_app(case) + def test_own_files_path_from_the_start_screen(self): async def case(app, pilot, ctx): await press(pilot, "down", "enter") From 226b5f549273be6e1185e8732670a946e8d5906c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:50:48 +0200 Subject: [PATCH 09/27] Own model files: links to shards are accepted with or without --model, and a problem that applies to several files is said once (problem_words), in the Terminal, the screens and 'models import'; tests for items 2 and 3 --- strata_cli/cli.py | 7 +- tests/terminal/test_flow2_022.py | 160 +++++++++++++++++++++++++++++++ 2 files changed, 162 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_flow2_022.py diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 80e66518..6e476bb6 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -591,11 +591,8 @@ def _models(a: argparse.Namespace) -> int: def _import_problem(plan: dict) -> str: """Why `models import --plan` refused, in plain words (the codes stay in --output json).""" - from strata_cli.launch.runner import plain_issue - issues = [str(x) for x in plan.get("issues") or []] - if "multiple_model_groups" in issues: # several models in one folder: "not a size Strata knows" would only confuse - issues = [x for x in issues if x != "unrecognized_or_unsupported_model_variant"] - words = "; ".join(dict.fromkeys(plain_issue(x) for x in issues)) + from strata_control import models as own_models + words = own_models.problem_words(plan.get("issues") or []) text = f"These files cannot be used as they are: {words}." holds = next((m for m in plan.get("messages") or [] if "holds" in m), "") if holds: diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py new file mode 100644 index 00000000..45bd8170 --- /dev/null +++ b/tests/terminal/test_flow2_022.py @@ -0,0 +1,160 @@ +"""0.2.2 flow walk, second round (phaseA-tests/flow-findings-022.md): what `strata launch` says and does with your own model files, the +plan, the download figure, the long silent step and a tuning result that already exists.""" + +from __future__ import annotations + +import json +import os +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_cli.launch import settings as S +from strata_cli.launch.catalog import Catalog +from strata_cli.launch.runner import LaunchError, Runner +from tests.terminal.launch_support import HW_12, Home, run_cli +from tests.terminal.test_own_files import IQ3XXS, Q2, gguf_bytes + + +class Base(unittest.TestCase): + def setUp(self): + self.home = Home().__enter__() + self.addCleanup(self.home.__exit__, None, None, None) + p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0)) + p.start() + self.addCleanup(p.stop) + self.tmp = tempfile.TemporaryDirectory(prefix="strata-flow2-") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + + def files(self, folder: Path, names: list[str], kind: str) -> Path: + folder.mkdir(parents=True, exist_ok=True) + for n in names: + (folder / n).write_bytes(gguf_bytes([kind])) + return folder + + def runner(self, **kw) -> Runner: + return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12)) + + +class MissingOwnFiles(Base): + """Finding 2: a --model-path that is not there, or holds no model, is said in plain words before anything starts.""" + + def test_a_folder_that_does_not_exist_is_named_and_nothing_is_promised(self): + missing = self.base / "models" + code, out, err = run_cli(["launch", "--plan", "--model-path", str(missing)]) + self.assertEqual(code, 2) + self.assertIn(f"This folder does not exist: {missing}", err) + self.assertNotIn("Qwen", err) + self.assertNotIn("continues where it stopped", err) + self.assertNotIn("could not be installed", err) + + def test_a_missing_file_says_file(self): + code, out, err = run_cli(["launch", "--plan", "--model-path", str(self.base / "x-00001-of-00002.gguf")]) + self.assertEqual(code, 2) + self.assertIn("This file does not exist", err) + + def test_an_empty_folder_says_there_are_no_gguf_files(self): + empty = self.base / "empty" + empty.mkdir() + code, out, err = run_cli(["launch", "--plan", "--model", "q2_0", "--model-path", str(empty)]) + self.assertEqual(code, 2) + self.assertIn("no .gguf model files", err) + self.assertIn("...-00001-of-00002.gguf", err) + + def test_machine_output_carries_the_same_words(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(self.base / "gone")]) + self.assertEqual(code, 2) + self.assertIn("This folder does not exist", json.loads(out)["error"]["message"]) + + def test_the_engine_is_not_touched_for_a_wrong_path(self): + r = self.runner(model_path=str(self.base / "gone")) + with mock.patch.object(Runner, "ensure_engine", side_effect=AssertionError("engine step must not start")): + with self.assertRaises(LaunchError) as ctx: + r.run() + self.assertEqual(ctx.exception.code, 2) + self.assertIn("does not exist", ctx.exception.text) + + def test_the_failure_hint_of_own_files_promises_no_download(self): + r = self.runner(model_path=str(self.files(self.base / "m", Q2, "Q2_0")), family="qwen", model="Q2_0") + proc = mock.Mock() + proc.stdout = iter(["=== Step 5: Getting the model files ===", "[X] missing /m/x.gguf"]) + proc.wait.return_value = 1 + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError) as ctx: + r.ensure_model() + self.assertNotIn("download", ctx.exception.next) + self.assertIn("finished steps are skipped", ctx.exception.next) + + def test_the_screens_say_the_same(self): + from strata_control import models + text, nxt = models.own_path_problem(str(self.base / "nope")) + self.assertIn("This folder does not exist", text) + self.assertIn("Nothing was downloaded", nxt) + self.assertIsNone(models.own_path_problem(str(self.files(self.base / "ok", IQ3XXS, "IQ3_XXS")))) + + def test_a_folder_one_level_above_the_files_is_not_called_empty(self): + self.files(self.base / "repo" / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + from strata_control import models + self.assertIsNone(models.own_path_problem(str(self.base / "repo"))) + + +class LinkedShards(Base): + """Finding 3: shards that are links are accepted with no --model, as with --model, and a problem is said once.""" + + def links(self, names: list[str], real: bool = True) -> Path: + blobs = self.base / "blobs" + snap = self.base / "snap" + blobs.mkdir(exist_ok=True) + snap.mkdir(exist_ok=True) + for i, n in enumerate(names): + target = blobs / f"sha{i}" + if real: + target.write_bytes(gguf_bytes(["Q2_0"])) + try: + os.symlink(target, snap / n) + except (OSError, NotImplementedError): + self.skipTest("this account cannot create symbolic links") + return snap + + def test_linked_shards_without_a_model_name_are_used(self): + snap = self.links(Q2) + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(snap)]) + self.assertEqual(code, 0, err or out) + s = json.loads(out)["plan"]["settings"] + self.assertEqual((s["family"], s["model"]), ("qwen", "Q2_0")) + self.assertEqual(Path(s["model_path"]), snap) # the link names stay (the shard names are what setup reads) + + def test_linked_shards_with_the_model_named_give_the_same_folder(self): + snap = self.links(Q2) + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--model-path", str(snap)]) + self.assertEqual(code, 0, err or out) + self.assertEqual(Path(json.loads(out)["plan"]["settings"]["model_path"]), snap) + + def test_links_to_nothing_are_one_sentence_not_one_per_file(self): + snap = self.links(Q2, real=False) + code, out, err = run_cli(["launch", "--plan", "--model-path", str(snap)]) + self.assertEqual(code, 5) + self.assertEqual(err.count("shortcut"), 1, err) + self.assertIn(Q2[0], err) + self.assertIn(Q2[1], err) + + def test_the_same_problem_for_many_files_is_said_once(self): + from strata_control import models + issues = [f"m-0000{i}-of-00005.gguf: GGUF metadata is truncated" for i in range(1, 6)] + ["incomplete_or_invalid_shard_set"] + words = models.problem_words(issues) + self.assertEqual(words.count("the file is cut short"), 1) + self.assertIn("m-00001-of-00005.gguf, m-00002-of-00005.gguf and 3 more files", words) + self.assertEqual(models.problem_words(["a.gguf: GGUF metadata is truncated", "b.gguf: GGUF metadata is truncated"]), + "a.gguf and b.gguf: the file is cut short (a download or copy that did not finish)") + self.assertEqual(models.problem_words(["multiple_model_groups", "unrecognized_or_unsupported_model_variant"]), + "the folder holds more than one model") + many = [f"unsupported_or_missing_architecture", "incomplete_or_invalid_shard_set", "multiple_model_groups", + "unsupported_or_incomplete_tokenizer_metadata", "missing_or_unexpected_expert_quantization"] + self.assertTrue(models.problem_words(many).endswith("and 2 more problems")) + + + +if __name__ == "__main__": + unittest.main() From fd4f7d445cfb6032626b0c809c652b3f5b8a58c0 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:55:39 +0200 Subject: [PATCH 10/27] launch --plan: names the model your files are (title, size, picture setting, a copyable line with --model) instead of placeholders, and says what would be downloaded and how big (0 when everything is here, the draft layer and picture reader counted, engine mentioned) --- strata_cli/launch/cmd.py | 13 +++++- strata_cli/launch/runner.py | 70 +++++++++++++++++++++++++++++++- strata_cli/launch/settings.py | 2 +- tests/terminal/test_flow2_022.py | 56 +++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 4 deletions(-) diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 36510792..477d43b9 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -30,6 +30,9 @@ examples: """ +PICTURE_WORDS = {"off": "off", "on": "on", "cpu": "on (the reader runs on the processor)", "gpu": "on (the reader runs on the graphics card)"} + + def _choice(label: str, options: tuple[str, ...]): def convert(value: str) -> str: v = str(value).strip().lower() @@ -582,8 +585,14 @@ def run_launch(a: argparse.Namespace) -> int: print(json.dumps({"schema_version": 1, "ok": True, "plan": plan})) else: _say(f"Plan for '{s.name}':") - _say(f" model {s.family} {s.model}" if s.model else f" model your files at {s.model_path}") - _say(f" context {S.context_label(s.context)} pictures {s.vision} parallel {s.parallel or 'fit to your card'}") + m = plan.get("model") or {} + size = f", {m['model_gb']:.0f} GB" if m.get("model_gb") else "" + if s.model_path: + _say(f" model {m.get('title') or 'your model files'}{size} (your files in {s.model_path})") + else: + _say(f" model {m.get('title') or f'{s.family} {s.model}'}{size}") + _say(f" context {S.context_label(s.context)} pictures {PICTURE_WORDS.get(s.vision or 'off', s.vision)} parallel {s.parallel or 'fit to your card'}") + _say(f" download {(plan.get('download') or {}).get('text', '')}") _say(f" tuning {s.tune} access {S.ACCESS_WORDS[s.access]}, port {s.port}" + (" API key on" if s.api_key else "")) for n in notes: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 9cc81c48..ba20a5ea 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -945,11 +945,79 @@ class Runner: return tunnel # ---- all of it + def row(self): + """The catalog row of the chosen model (None for a model the list does not carry).""" + s = self.s + return next((r for r in self.catalog.rows() if (r.family, r.model) == (s.family, s.model)), None) + + def download_plan(self) -> dict: + """What this launch would download, in numbers and words (nothing is changed): the model's missing files, and for a model that is + not on this computer yet also the draft layer and the picture reader that setup fetches after it. 0 when everything is here.""" + from strata_control import engine_component + from strata_control.discovery import MMPROJ_GB, MTP_FETCH_GB + s = self.s + st = self.model_state() + parts = [{"kind": p.kind, "label": p.label, "gb": round(p.gb, 1)} for p in st.parts] + fresh = any(p.kind == "weights" for p in st.parts) and not st.own_files + row = self.row() + helpers = s.family in ("qwen", "swift", "coder", "unsloth") + wants_pictures = s.vision not in (None, "off") and row is not None and bool(row.images) + have = {p["kind"] for p in parts} + if fresh and helpers: + if s.mtp != "off": + parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) + if wants_pictures: + parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) + elif st.own_files and helpers: + # the person's files come with no draft layer or picture reader: setup fetches them next to the prepared data, unless they are there + try: + data = Path(st.folder) if st.folder else (self.existing_data_dir() or self.catalog.data_dir()) + if s.mtp != "off" and "mtp" not in have and not (data / "mtp" / "rt" / "experts.bin").is_file(): + parts.append({"kind": "mtp", "label": "the draft layer", "gb": MTP_FETCH_GB}) + if wants_pictures and "mmproj" not in have and not list((data / "models").glob("mmproj*.gguf")): + parts.append({"kind": "mmproj", "label": "the picture reader", "gb": MMPROJ_GB}) + except OSError: + pass + gb = round(sum(p["gb"] for p in parts), 1) + engine = True + try: + engine = bool(engine_component.status(Path(self.components_dir) if self.components_dir else None).get("usable")) + except Exception: # noqa: BLE001 - the plan must not fail on this + pass + if gb < 0.05: + text = ("Nothing to download: your model files are used where they are." if st.own_files + else "Nothing to download: the model is already on this computer.") + else: + names = [f"{p['label']} ({p['gb']:.1f} GB)" for p in parts] + what = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] + text = f"About {gb:.1f} GB to download: {what}." + if st.on_disk_gb >= 1: + text += f" {st.on_disk_gb:.0f} GB of the model is already in its folder." + if st.own_files: + text += " Your model files are used where they are." + if not engine: + text += " The engine for your graphics card is downloaded first (from the update source; its size is shown when it starts)." + return {"gb": gb, "parts": parts, "engine_missing": not engine, "own_files": st.own_files, "text": text} + def plan(self) -> dict: s = self.s + self.check_own_files() warns = [n.line() for n in (*S.check_access(s),)] + row = self.row() + try: + self.resolved_vision() + except Exception: # noqa: BLE001 + pass + try: + download = self.download_plan() + except Exception: # noqa: BLE001 - a plan that cannot count the download still shows the rest + download = {"gb": None, "parts": [], "engine_missing": None, "own_files": bool(s.model_path), + "text": "How much would be downloaded could not be worked out here."} + title = row.title if row is not None else (f"{s.family} {s.model}" if s.model else None) + model = {"title": title, "family": s.family, "model": s.model, "model_gb": row.download_gb if row is not None else None, + "own_files": bool(s.model_path), "folder": s.model_path} return {"profile": self.profile, "settings": s.to_dict(with_key=False), "warnings": warns, - "flags": S.flags_text(s), "steps": list(STAGES)} + "flags": S.flags_text(s), "steps": list(STAGES), "model": model, "download": download} def run(self, *, start: bool = True) -> Result: try: diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index 8079fb16..26588879 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -270,7 +270,7 @@ def flags_text(s: LaunchSettings, *, preset: str | None = None) -> str: else: if s.model_path: parts.append(f'--model-path "{s.model_path}"') - elif s.model: + if s.model: # own files the table recognised say which model they are, so the line stays exact parts.append(f"--model {s.model.lower()}" + (f" --family {s.family}" if s.family and s.family != "qwen" else "")) if s.data_dir: parts.append(f'--data-dir "{s.data_dir}"') diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 45bd8170..067a2aa3 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -156,5 +156,61 @@ class LinkedShards(Base): +class PlanWords(Base): + """Findings 1 and 7: --plan shows the real model, the picture setting, a copyable line, and what would be downloaded.""" + + def plan_text(self, *args): + code, out, err = run_cli(["launch", "--plan", *args]) + self.assertEqual(code, 0, err or out) + return out + + def test_own_files_show_the_model_they_are(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + out = self.plan_text("--model-path", str(folder)) + self.assertIn("Plan for 'IQ3_XXS", out) + self.assertNotIn("model default", out) + self.assertNotIn("None", out) + self.assertIn("Qwen3.8-Flash-Next IQ3_XXS", out) + self.assertIn(f"your files in {folder}", out) + self.assertRegex(out, r"pictures (on|off)") + self.assertIn("--model iq3_xxs", out.split("same as")[1]) # the copyable line names the model too + self.assertIn(f'--model-path "{folder}"', out.split("same as")[1]) + + def test_a_named_catalog_model_shows_its_size_and_the_download(self): + out = self.plan_text("--model", "q2_0") + self.assertIn("Qwen3.8-Flash-Next Q2_0, 66 GB", out) + self.assertRegex(out, r"download\s+About 7\d\.\d GB to download: the model \(66\.4 GB\), the draft layer \(5\.2 GB\)") + self.assertIn("The engine for your graphics card is downloaded first", out) + + def test_nothing_is_downloaded_when_everything_is_here(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + data = self.base / "Strata" + (data / "models" / "x").mkdir(parents=True) + (data / "mtp" / "rt").mkdir(parents=True) + (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x") + (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x") + # the files sit under /models/: the draft layer and the picture reader are found beside them + moved = data / "models" / "iq3_xxs" + folder.rename(moved) + out = self.plan_text("--model-path", str(moved)) + self.assertIn("download Nothing to download: your model files are used where they are.", out) + + def test_own_files_with_no_draft_layer_say_what_is_fetched(self): + folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS") + with mock.patch.object(Runner, "existing_data_dir", return_value=None), mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"): + out = self.plan_text("--model-path", str(folder), "--vision", "off") + self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). Your model files are used where they are.", out) + + def test_json_plan_carries_the_numbers(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--mtp", "off", "--vision", "off"]) + self.assertEqual(code, 0, err) + plan = json.loads(out)["plan"] + self.assertEqual(plan["model"]["title"], "Qwen3.8-Flash-Next Q2_0") + self.assertEqual(plan["model"]["model_gb"], 66.4) + self.assertEqual(plan["download"]["gb"], 66.4) + self.assertEqual([p["kind"] for p in plan["download"]["parts"]], ["weights"]) + + + if __name__ == "__main__": unittest.main() From 594e379291b8412d6590dbc243ade2915d06a94c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:56:33 +0200 Subject: [PATCH 11/27] Download label: the total counts every shard and the picture reader, in the data folder setup is given (--data-dir), not the first shard only --- strata_cli/launch/runner.py | 25 ++++++++++++++++++--- tests/terminal/test_flow2_022.py | 37 ++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index ba20a5ea..f24801ea 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -624,6 +624,26 @@ class Runner: """(title, text) of the question before a download starts, naming exactly what is fetched.""" return self.model_state().question() + def progress_job(self) -> dict: + """What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the + person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards + shows 'of 66.4 GB' from the start and not the size of the file being fetched.""" + s, cat = self.s, self.catalog + data = Path(s.data_dir) if s.data_dir else (self.existing_data_dir() or cat.data_dir()) + models_dir = data / "models" + job = {"folder": str(models_dir / cat.tag_of(s.family, s.model)), + "total_gb": float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0)} + try: + setup_module = cat.strata.setup_module() + if setup_module is not None and not s.model_path: + job["files"] = cat.mcp.expected_files(setup_module, str(s.family), str(s.model), models_dir, self.vision_word() != "no") + first = next((f for f in job["files"] if f.get("role") == "model"), None) + if first: # the folder setup names it (Q2_0), not the lower-case run-config tag (q2_0) + job["folder"] = str(Path(first["path"]).parent) + except Exception: # noqa: BLE001 - progress is a convenience; the folder scan still counts + pass + return job + def ensure_model(self) -> Path: s, cat = self.s, self.catalog self.check_own_files() @@ -657,8 +677,7 @@ class Runner: p = self._spawn(argv, env=env, cwd=str(cat.src)) lines: list[str] = [] already: bool | None = None # all the model's files were on disk before this run wrote anything - folder = str(cat.data_dir() / "models" / cat.tag_of(s.family, s.model)) - total = float(next((r.download_gb for r in cat.rows() if r.family == s.family and r.model == s.model), 0) or 0) + job = self.progress_job() for line in p.stdout: # type: ignore[union-attr] if self.cancel.is_set(): self._stop_children() @@ -669,7 +688,7 @@ class Runner: lines.append(line) lines[:] = lines[-1500:] prog = cat.mcp.install_progress(lines) - prog = cat.mcp.combined_progress(prog, {"folder": folder, "total_gb": total}) + prog = cat.mcp.combined_progress(prog, job) dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): if phase == "download" and already is None: diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 067a2aa3..9e773565 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -212,5 +212,42 @@ class PlanWords(Base): +class DownloadTotal(Base): + """Finding 4: the figure counts every shard (and the picture reader), in the folder the setup is really given.""" + + def run_lines(self, runner: Runner, lines: list[str]) -> list[str]: + seen: list[str] = [] + runner.emit_cb = lambda ev: seen.append(ev.text) + proc = mock.Mock() + proc.stdout = iter(lines) + proc.wait.return_value = 1 # stop after the lines: the failure path is not what is looked at + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError): + runner.ensure_model() + return seen + + def test_the_total_is_the_whole_model_in_the_chosen_data_folder(self): + data = self.base / "mydata" + folder = data / "models" / "Q2_0" + folder.mkdir(parents=True) + first = folder / (Q2[0] + ".part") + first.write_bytes(bytes(100_000_000)) + r = self.runner(family="qwen", model="Q2_0", data_dir=str(data), vision="on", context=32768) + job = r.progress_job() + self.assertEqual(Path(job["folder"]), folder) + self.assertEqual(len(job["files"]), 3) # two shards and the picture reader + seen = self.run_lines(r, ["=== Step 5: Getting the model files ===", f"{Q2[0]}: 0.10 / 37.60 GB (0%)"]) + text = [x for x in seen if "GB" in x] + self.assertTrue(text, seen) + self.assertIn("of 67.3 GB", text[-1]) # 66.4 GB of shards + 0.9 GB picture reader + self.assertNotIn("37.6", " ".join(text)) + + def test_the_default_data_folder_is_used_when_none_was_chosen(self): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + self.assertEqual(Path(r.progress_job()["folder"]).parts[-2:], ("models", "Q2_0")) + self.assertEqual(len(r.progress_job()["files"]), 2) + + + if __name__ == "__main__": unittest.main() From 17cb817594ffd06c52f1ef773080442a272c5776 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 15:58:11 +0200 Subject: [PATCH 12/27] launch: setup step 6 (packing, converting) is no longer silent - the plain sentence for what it does is shown and a 'still working, N min so far' line comes every 30 s of silence; a cancel is seen at once --- strata_cli/launch/runner.py | 50 +++++++++++++++++++++++++++++- tests/terminal/test_flow2_022.py | 52 ++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 1 deletion(-) diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index f24801ea..c51f0967 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -310,6 +310,15 @@ def download_text(dl: dict, already: bool, label: str | None = None) -> str: return f"{label}: {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" if label else f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" +_END = object() + + +def _elapsed(seconds: float) -> str: + """'40 s', '3 min' (plain, rounded down).""" + seconds = int(seconds) + return f"{seconds} s" if seconds < 90 else f"{seconds // 60} min" + + class Runner: def __init__(self, s: S.LaunchSettings, *, catalog: Catalog | None = None, emit: Callable[[Event], None] | None = None, cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None, @@ -624,6 +633,32 @@ class Runner: """(title, text) of the question before a download starts, naming exactly what is fetched.""" return self.model_state().question() + #: seconds of silence from setup before a "still working" line (packing a 40 GB model prints nothing for minutes) + HEARTBEAT_S = 30.0 + + def _read_lines(self, p: subprocess.Popen): + """The lines setup prints, and None whenever a second passes with none, so a silent step can say it is still going and a cancel is + seen at once.""" + import queue + q: queue.Queue = queue.Queue() + + def pump() -> None: + try: + for ln in p.stdout: # type: ignore[union-attr] + q.put(ln) + finally: + q.put(_END) + threading.Thread(target=pump, daemon=True).start() + while True: + try: + ln = q.get(timeout=min(1.0, max(0.05, self.HEARTBEAT_S / 2))) + except queue.Empty: + yield None + continue + if ln is _END: + return + yield ln + def progress_job(self) -> dict: """What the download figure is counted over: the folder setup writes the model into (the data folder it is GIVEN, which may be the person's --data-dir and not the default one) and every file of the install with the catalog's total, so a model in several shards @@ -678,10 +713,17 @@ class Runner: lines: list[str] = [] already: bool | None = None # all the model's files were on disk before this run wrote anything job = self.progress_job() - for line in p.stdout: # type: ignore[union-attr] + step_seen, step_since, quiet_since, said = None, time.monotonic(), time.monotonic(), None + for line in self._read_lines(p): if self.cancel.is_set(): self._stop_children() raise Cancelled() + if line is None: # nothing printed for a while: the long steps (packing, converting) are silent + if said and said[1] != "download" and time.monotonic() - quiet_since >= self.HEARTBEAT_S: + quiet_since = time.monotonic() + self.emit("model", f"{said[0]} (still working, {_elapsed(time.monotonic() - step_since)} so far)", None, step=step_seen) + continue + quiet_since = time.monotonic() line = line.rstrip() if not line: continue @@ -690,6 +732,12 @@ class Runner: prog = cat.mcp.install_progress(lines) prog = cat.mcp.combined_progress(prog, job) dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") + if prog.get("step") != step_seen: + step_seen, step_since = prog.get("step"), time.monotonic() + if label and not dl: + said = (label, phase) + else: + said = None if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): if phase == "download" and already is None: already = float(dl["percent"]) >= 99.5 diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 9e773565..2cd8c38f 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -249,5 +249,57 @@ class DownloadTotal(Base): +class QuietStep(Base): + """Finding 5: setup step 6 (packing) prints nothing for minutes: the person sees the plain sentence and a 'still working' line.""" + + def slow(self, steps): + import time + for delay, line in steps: + time.sleep(delay) + yield line + "\n" + + def run_steps(self, steps, heartbeat=0.3): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + r.HEARTBEAT_S = heartbeat + seen = [] + r.emit_cb = lambda ev: seen.append(ev.text) + proc = mock.Mock() + proc.stdout = self.slow(steps) + proc.wait.return_value = 1 + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError): + r.ensure_model() + return seen + + def test_a_silent_pack_step_says_what_it_does_and_that_it_is_still_going(self): + seen = self.run_steps([(0, "=== Step 5: Getting the model files ==="), (0, "all model files present"), + (0, "=== Step 6: Preparing the model for Strata ==="), + (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin"), (1.6, "[X] stopped for the test")]) + pack = [x for x in seen if x.startswith("Packing the experts into one file")] + self.assertTrue(pack, seen) + self.assertEqual(pack[0], "Packing the experts into one file for low-memory mode (one time)") + beats = [x for x in pack if "still working" in x] + self.assertGreaterEqual(len(beats), 2, seen) # a line every interval of silence + self.assertNotIn("Setup step 6", " ".join(seen)) + + def test_no_heartbeat_while_lines_keep_coming(self): + seen = self.run_steps([(0, "=== Step 6: Preparing the model for Strata ==="), (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin")] + + [(0.1, f" layer {i}") for i in range(5)] + [(0, "[X] stopped")], heartbeat=2.0) + self.assertFalse([x for x in seen if "still working" in x]) + + def test_the_plain_printer_shows_each_heartbeat(self): + import io + from strata_cli.launch import cmd + from strata_cli.launch.runner import Event + buf = io.StringIO() + with mock.patch.object(cmd.sys, "stdout", buf): + emit = cmd._printer() + emit(Event("model", "Packing (still working, 30 s so far)")) + emit(Event("model", "Packing (still working, 60 s so far)")) + emit(Event("model", "Packing (still working, 60 s so far)")) + self.assertEqual(buf.getvalue().count("still working"), 2) + + + if __name__ == "__main__": unittest.main() From ee8e6404b0176e7bb5a75508dfb428fcefba21b6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:02:35 +0200 Subject: [PATCH 13/27] launch: a run by flags reuses the tuning result stored for the same model, choices and computer and says so; --retune measures again --- docs/TERMINAL_LAUNCH.md | 2 +- strata_cli/launch/app.py | 7 +-- strata_cli/launch/cmd.py | 10 +++- strata_cli/launch/runner.py | 45 ++++++++++++++---- tests/terminal/test_flow2_022.py | 82 ++++++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 16 deletions(-) diff --git a/docs/TERMINAL_LAUNCH.md b/docs/TERMINAL_LAUNCH.md index 80549729..23444e1d 100644 --- a/docs/TERMINAL_LAUNCH.md +++ b/docs/TERMINAL_LAUNCH.md @@ -70,7 +70,7 @@ strata launch --list-presets | --delete-preset NAME | --status | --stop [--prese `strata launch --help` lists everything with examples. An unknown model or flag gets a plain message with the closest match. Presets are small files in `launch-presets/` beside the profiles folder; the run uses the shared profile `launch-` and the shared tuning presets (`strata presets`), so the app sees them too. Flags next to `--preset` change that start only -(add `--save-preset` to keep them). +(add `--save-preset` to keep them). `--plan` shows the model (also for your own files, which it recognises), the context, the picture setting and what would be downloaded and how big (0 when everything is already here). A model that was tuned before for the same choices on the same computer is not measured again by `--tune quick`; the stored result is used and the run says so. Add `--retune` to measure again. ## Connect your apps: `strata connect` diff --git a/strata_cli/launch/app.py b/strata_cli/launch/app.py index b0a8500a..8a327b95 100644 --- a/strata_cli/launch/app.py +++ b/strata_cli/launch/app.py @@ -43,6 +43,7 @@ class Ctx: glyphs: Glyphs = field(default_factory=Glyphs) feed: str | None = None move_data: bool = False + retune: bool = False notes: list[str] = field(default_factory=list) start_own_files: bool = False picked_in_list: bool = False @@ -263,7 +264,7 @@ class LaunchApp(App): s = self.ctx.settings self.cancel = threading.Event() self.runner = Runner(s, catalog=self.ctx.catalog, emit=self._emit, cancel=self.cancel, feed=self.ctx.feed, confirm=self._ask_from_run, - move_data=self.ctx.move_data) + move_data=self.ctx.move_data, retune=self.ctx.retune) gb = getattr(self.runner, "download_gb", lambda: 0.0)() if not confirmed else 0.0 if gb >= 1.0: free = self.ctx.catalog.disk_free(s.data_dir or self.ctx.catalog.data_dir()) @@ -404,7 +405,7 @@ def run_monitor(info: dict, *, keep_default: bool = True, color: str = "auto") - def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None, feed: str | None = None, auto_run: bool = False, - save: bool = False, open_page: bool = False, move_data: bool = False) -> int: + save: bool = False, open_page: bool = False, move_data: bool = False, retune: bool = False) -> int: """Open the launch screens. `settings` given and `auto_run`: skip the questions and go straight to the run.""" catalog = catalog or Catalog() print("Looking at this computer…", flush=True) @@ -419,7 +420,7 @@ def run_tui(settings: S.LaunchSettings | None, *, catalog: Catalog | None = None s.name = f"{s.model or 'model'} {S.context_label(s.context)}" if save: store.save(s, s.name) - ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data) + ctx = Ctx(catalog=catalog, computer=computer, rows=rows, settings=s, glyphs=Glyphs(), feed=feed, move_data=move_data, retune=retune) app = LaunchApp(ctx, auto_run=auto_run) result = app.run() if getattr(app, "return_code", 0) not in (0, None) or getattr(app, "_exception", None) is not None: diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 477d43b9..62807cf7 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -113,6 +113,9 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser] a.add_argument("--no-api-key", action="store_true", help="share beyond this computer without an API key (a warning is shown, nothing is refused)") o = p.add_argument_group("running") o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name") + o.add_argument("--retune", action="store_true", + help="with --tune (quick is used when --tune is not given): measure again even when this model was already tuned on this computer " + "(by default a stored tuning result is reused and no measuring is done)") o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return") o.add_argument("--open", action="store_true", help="open the server's web page in your browser once it is serving (nothing opens a browser without this)") o.add_argument("--yes", action="store_true", help="do not ask questions (for one: whether to download the model on a computer with no engine yet)") @@ -562,7 +565,10 @@ def run_launch(a: argparse.Namespace) -> int: return _tui(app.run_tui, None, catalog=catalog, feed=a.feed, open_page=bool(a.open)) if catalog is None: return fail("This Terminal does not carry the model list. Install it again with the one-line installer.", 5) - runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes) + if getattr(a, "retune", False) and s.tune == "skip": + s.tune = "quick" + runner = Runner(s, catalog=catalog, emit=_printer(machine), feed=a.feed, assume_yes=bool(a.yes or machine), confirm=_ask_yes, + retune=bool(getattr(a, "retune", False))) try: runner.check_own_files() # the person's own files: a wrong path is said now, and the files name the model except LaunchError as e: @@ -618,7 +624,7 @@ def run_launch(a: argparse.Namespace) -> int: if interactive and have_choices: from strata_cli.launch import app return _tui(app.run_tui, s, catalog=catalog, feed=a.feed, auto_run=True, save=bool(a.save_preset), open_page=bool(a.open), - move_data=move_data) + move_data=move_data, retune=bool(getattr(a, "retune", False))) try: result = runner.run() except LaunchError as e: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index c51f0967..078ccc9f 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -323,8 +323,10 @@ class Runner: def __init__(self, s: S.LaunchSettings, *, catalog: Catalog | None = None, emit: Callable[[Event], None] | None = None, cancel: threading.Event | None = None, feed: str | None = None, python: str | None = None, components_dir: str | None = None, hardware: dict | None = None, - confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False): + confirm: Callable[[str, str], bool] | None = None, assume_yes: bool = False, move_data: bool = False, + retune: bool = False): self.s = s + self.retune = retune # --retune: measure again even when a tuning result for this model on this computer is stored self.move_data = move_data # --move-data / the answer "move": the model files already here go to the new --data-dir self.confirm = confirm # asked (title, text) before a model is downloaded with no engine; True = go on self.assume_yes = assume_yes # --yes: no questions @@ -890,16 +892,23 @@ class Runner: if s.tune == "skip": return from strata_control import presets - if s.tuned_preset: - try: - presets.find(s.tuned_preset) - self.emit("tune", "This preset is already tuned for this computer.", 100) + if not self.retune: + if s.tuned_preset: + try: + presets.find(s.tuned_preset) + self.emit("tune", "This preset is already tuned for this computer.", 100) + return + except presets.PresetError: + pass + elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved + self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100) + return + stored = self.stored_tuning() + if stored: # the same model and choices were tuned on this computer before (a run by flags, no preset) + s.tuned_preset, s.tuned_at = stored["id"], stored["date"] + self.emit("tune", f"This model was already tuned for this computer on {stored['date']} ('{stored['name']}'), so that result is used " + "and nothing is measured again. Add --retune to measure again.", 100) return - except presets.PresetError: - pass - elif s.tuned_at: # measured before: the standard settings were already the fastest, nothing was saved - self.emit("tune", f"Already tuned on {s.tuned_at}: this computer runs best with the standard settings. Nothing to do.", 100) - return mode = "thorough" if s.tune == "thorough" else "quick" status_file = launch_dir() / f"{self.name}.tune.json" try: @@ -945,6 +954,22 @@ class Runner: s.tuned_at = time.strftime("%Y-%m-%d") self.emit("tune", f"Tuning result: {word}. {sentence}", 100, level="info" if word in ("faster", "already fastest") else "warn", word=word) + def stored_tuning(self) -> dict | None: + """The tuning result stored for this launch's model, choices and computer (the active preset of its slot in the shared presets store, + which the start applies), or None. A result whose computer changed in a way that matters (a different card, processor or memory, + another model file) is not reused: it is measured again.""" + if self.config_path is None: + return None + from strata_control import presets + try: + _cfg, info = presets.overlay(read_config(self.config_path)) + if not info.get("applied") or not info.get("preset"): + return None + made = str(presets.load(info["preset"]["id"]).get("created") or "")[:10] + return {"id": info["preset"]["id"], "name": info["preset"]["name"], "date": made or time.strftime("%Y-%m-%d")} + except Exception: # noqa: BLE001 - an unreadable store means: measure + return None + tune_word: str | None = None # ---- 5. start diff --git a/tests/terminal/test_flow2_022.py b/tests/terminal/test_flow2_022.py index 2cd8c38f..5a6d2f31 100644 --- a/tests/terminal/test_flow2_022.py +++ b/tests/terminal/test_flow2_022.py @@ -301,5 +301,87 @@ class QuietStep(Base): +class StoredTuning(Base): + """Finding 6: a run by flags (no saved preset) reuses the tuning result stored for the same model, choices and computer.""" + + IDENT = {"hardware": {"hard": {"gpus": ["RTX 5070"], "cpu": "test", "logical": 16, "ram_gib": 64}, "soft": {}}, + "engine": {"backend": "cuda"}, "model": {"sha256_shard1": "abc"}} + + def setUp(self): + super().setUp() + from strata_control import presets + self.presets = presets + self.cfg_path = self.base / "launch.json" + self.cfg = {"args": ["--native", "x/model-00001-of-00002.gguf", "--max-context", "32768", "--kv", "int8"], "model_name": "qwen"} + self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8") + self.ident = json.loads(json.dumps(self.IDENT)) + p = mock.patch.object(presets, "current_identity", lambda cfg, **kw: self.ident) + p.start() + self.addCleanup(p.stop) + + def store(self): + return self.presets.create({"settings": {"args": {}, "env": {}, "per_request": {}}, "outcome": "improved"}, + choices=self.presets.choices_from_config(self.cfg), identity=self.ident, name="Q2 32K - Full speed") + + def runner_for_tune(self, retune=False): + r = self.runner(family="qwen", model="Q2_0", tune="quick") + r.retune = retune + r.config_path = self.cfg_path + return r + + def run_tune(self, r): + seen = [] + r.emit_cb = lambda ev: seen.append(ev.text) + with mock.patch.object(Runner, "_spawn", side_effect=RuntimeError("the tuner started")) as spawn: + try: + r.tune() + started = False + except RuntimeError: + started = True + return seen, started + + def test_nothing_stored_means_it_is_measured(self): + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_a_stored_result_is_used_and_said(self): + saved = self.store() + r = self.runner_for_tune() + seen, started = self.run_tune(r) + self.assertFalse(started) + text = seen[-1] + self.assertIn("already tuned for this computer", text) + self.assertIn("Q2 32K - Full speed", text) + self.assertIn("--retune", text) + self.assertEqual(r.s.tuned_preset, saved["id"]) + self.assertTrue(r.s.is_tuned) + + def test_retune_measures_again(self): + self.store() + seen, started = self.run_tune(self.runner_for_tune(retune=True)) + self.assertTrue(started) + + def test_another_context_is_another_result(self): + self.store() + self.cfg["args"][3] = "65536" + self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8") + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_a_changed_graphics_card_is_measured_again(self): + self.store() + self.ident["hardware"]["hard"]["gpus"] = ["RTX 4090"] + seen, started = self.run_tune(self.runner_for_tune()) + self.assertTrue(started) + + def test_the_flag_asks_for_a_new_measurement_and_implies_quick(self): + code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--retune"]) + self.assertEqual(code, 0, err) + self.assertEqual(json.loads(out)["plan"]["settings"]["tune"], "quick") + code, out, err = run_cli(["launch", "--help"]) + self.assertIn("--retune", out) + + + if __name__ == "__main__": unittest.main() From 970c75c8f652966d2e718c63f9d1d8556693fb0e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:03:23 +0200 Subject: [PATCH 14/27] iq_pack: an interrupted experts.bin write continues at the next layer (finished layers are flushed and recorded, the last kept one is checked against the GGUF) instead of starting from zero; says so --- tools/iq_pack.py | 36 ++++++++++++++++- tools/test_iq_pack.py | 89 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+), 2 deletions(-) diff --git a/tools/iq_pack.py b/tools/iq_pack.py index b48af1aa..b33723a0 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -731,16 +731,48 @@ def main() -> int: # experts.bin, and an experts.bin without its sidecar is never reused sidecar.unlink(missing_ok=True) part = out / "experts.bin.tmp" - with open(part, "wb") as fo: - for l, gt, dt, off, blob, ts in layout: + progress = out / "experts.bin.tmp.json" + # A stop part-way (a kill, a power cut) used to cost the whole write again (40 GB, minutes). The finished layers are kept: + # after every layer the file is flushed to disk and experts.bin.tmp.json says how many layers are in it and which source they were + # cut from. The next run continues at that layer when the source is the same and the last kept layer still matches the GGUF. + start = 0 + if part.exists(): + done = read_json(progress) + k = done.get("layers") if isinstance(done, dict) and done.get("want") == want else None + if isinstance(k, int) and 0 < k <= len(layout) and part.stat().st_size >= (layout[k][3] if k < len(layout) else offset): + l, gt, dt, off, blob, ts = layout[k - 1] + last = layer_blobs(l, blob, ts) + if last is not None: + with open(part, "rb") as f: + f.seek(off) + kept = f.read(n_expert * blob) + if kept == last.tobytes(): + start = k + if start: + print("the earlier packing was interrupted: keeping its first %d of %d layers and continuing with layer %d" + % (start, len(layout), start), flush=True) + else: + print("the earlier packing was interrupted and cannot be continued: starting it again", flush=True) + resume_at = layout[start][3] if start < len(layout) else offset + with open(part, "r+b" if start else "wb") as fo: + if start: + fo.truncate(resume_at) # whatever followed the last recorded layer is a partial write + fo.seek(resume_at) + for l, gt, dt, off, blob, ts in layout[start:]: chunk = layer_blobs(l, blob, ts) if chunk is None: return 1 fo.write(chunk.tobytes()) + fo.flush() + os.fsync(fo.fileno()) + note = out / "experts.bin.tmp.json.new" + note.write_text(json.dumps({"want": want, "layers": l + 1}), encoding="utf-8") + note.replace(progress) if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) part.replace(path) + progress.unlink(missing_ok=True) side_tmp = out / "experts.bin.src.json.tmp" side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8") side_tmp.replace(sidecar) diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 580bf274..0e0f5e8b 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -515,6 +515,95 @@ class SplitArtifactTests(unittest.TestCase): self.assertEqual(rc, 0, log) self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + def test_interrupted_pack_continues_at_the_next_layer(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + want = expected_experts(iq_pack.Model(paths[0])) + lines = [ln.split() for ln in (pack / "native_experts.txt").read_text().splitlines() if ln and not ln.startswith("#")] + one_layer = int(lines[1][3]) # where layer 1 starts + self.assertFalse((pack / "experts.bin").exists()) + self.assertEqual((pack / "experts.bin.tmp").stat().st_size, one_layer) # layer 0 is on disk + self.assertEqual(json.loads((pack / "experts.bin.tmp.json").read_text())["layers"], 1) + # a partial write after the recorded layer (the kill came mid-write) is cut off + with open(pack / "experts.bin.tmp", "ab") as f: + f.write(b"garbage") + written = [] + real_layer = iq_pack.np.concatenate + + def counting(parts, axis): + written.append(1) + return real_layer(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", counting): + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertIn("keeping its first 1 of 2 layers and continuing with layer 1", log) + self.assertEqual((pack / "experts.bin").read_bytes(), want) + self.assertEqual(len(written), 2) # one layer re-read to check the kept one, one layer written + self.assertFalse((pack / "experts.bin.tmp").exists()) + self.assertFalse((pack / "experts.bin.tmp.json").exists()) + self.assertEqual(json.loads((pack / "experts.bin.src.json").read_text())["bytes"], len(want)) + + def test_interrupted_pack_of_another_model_is_not_continued(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + (root / "a").mkdir() + (root / "b").mkdir() + other = split_model(root / "a", name="other", seed=100) + paths = split_model(root / "b") + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(other[0], pack, "--experts-bin") + rc, log = run_pack(paths[0], pack, "--experts-bin") # the same geometry, other weights + self.assertEqual(rc, 0, log) + self.assertIn("cannot be continued: starting it again", log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + + def test_a_kept_layer_that_no_longer_matches_is_not_trusted(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + paths = split_model(root) + pack = root / "pack" + real = np.concatenate + calls = [] + + def dies_on_layer_1(parts, axis): + calls.append(1) + if len(calls) == 2: + raise KeyboardInterrupt("killed") + return real(parts, axis=axis) + with patch.object(iq_pack.np, "concatenate", dies_on_layer_1): + with self.assertRaises(KeyboardInterrupt): + run_pack(paths[0], pack, "--experts-bin") + data = bytearray((pack / "experts.bin.tmp").read_bytes()) + data[0] ^= 0xFF # the disk lost a bit + (pack / "experts.bin.tmp").write_bytes(bytes(data)) + rc, log = run_pack(paths[0], pack, "--experts-bin") + self.assertEqual(rc, 0, log) + self.assertIn("cannot be continued", log) + self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0]))) + def test_stale_same_size_experts_bin(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) From d408fa2ff139148946706e4dc56ed8917c9cb46d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:04:05 +0200 Subject: [PATCH 15/27] tools tests: the verify_sha256 stand-in takes the new own= argument (34 setup tests errored on it) --- tools/test_setup_unsloth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index b758db55..6348f56e 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -193,7 +193,7 @@ class Base(unittest.TestCase): mock.patch.object(setup, "get_prebuilt", lambda *a, **k: eng), mock.patch.object(setup, "download", fake_download), mock.patch.object(setup, "check_shards", lambda shards: None), - mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.verified.append((s.name, size, sha))), + mock.patch.object(setup, "verify_sha256", lambda s, size, sha, own=False: self.verified.append((s.name, size, sha))), mock.patch.object(setup, "run", fake_run), mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None), mock.patch.object(setup, "write_run_script", lambda tag, cfg, port, *_: self.t / f"start-{tag}.bat"), From d511c5102e5cfc9eeee7c8a976f05e99806ce1d3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:08:13 +0200 Subject: [PATCH 16/27] Updater tests reset a signature verifier left behind by an earlier test file --- tests/terminal/test_updater.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py index 29f77922..f8b6747c 100644 --- a/tests/terminal/test_updater.py +++ b/tests/terminal/test_updater.py @@ -48,6 +48,7 @@ class UpdaterCase(unittest.TestCase): patch = mock.patch.object(target, value, return_value=["sm_86"] if value == "cuda_archs_present" else "610.47") patch.start() self.addCleanup(patch.stop) + ec.register_signature_verifier(None) # a verifier an earlier test file left behind (it holds the shipped keys only) must not decide here self.addCleanup(ec.register_signature_verifier, None) # the tests sign with throwaway keys that they hand over explicitly: the release key shipped in update_keys.json is not in play here # (ReleaseKeys below checks the shipped file itself) From 2fcc25aab638a272feb9a297cdb675f548526b31 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:08:31 +0200 Subject: [PATCH 17/27] Release notes 0.2.2 draft: shared models folder and Docker flow fixes --- docs/release-notes-0.2.2.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/release-notes-0.2.2.md b/docs/release-notes-0.2.2.md index e9f04218..15a55b09 100644 --- a/docs/release-notes-0.2.2.md +++ b/docs/release-notes-0.2.2.md @@ -15,3 +15,5 @@ - **Small fixes.** `--mtp 2` is no longer checked as a folder (#3298); owner-only checks understand Windows account aliases (#3302, thanks jackbapa); `strata bench` with its own server sets its port (#3188); `calibrate` checks the report folder first (#3187); the CUDA 12.0 and 12.1 build error `__half_as_ushort` (#3368, thanks yudhanjaya, built with CUDA 12.6 only); the AMD picture reader builds position independent (#3359); the Mac setup installs cmake and ninja before it builds (#3403); the picture reader recreates its work folder if a temp cleaner removed it (#3370); a list of GPUs such as `"0,1"` is accepted (#3275, thanks MEsfits); `thinking_budget_tokens` is read (#2141) and the Anthropic usage numbers add up to the prompt (#2289, thanks xrip); an engine that cannot start is a 503 with the reason (#2496, thanks devYRPauli); the serve web page no longer scrolls sideways on a phone (#2971, thanks ctr-137); folders in a Trash or Recycle Bin are not offered as installs (#3410). Ported pull requests keep their authors. - **From the issues labelled needs-format.** The app numbers Radeon cards the way HIP does when an integrated GPU is present (#3418). The hardware report counts physical cores, so the Work profile asks for 6 pool workers on an 8-core CPU instead of 12 (#3417; the reporter measured 27.9 against 38.1 tok/s). Three trellis CPU tests skip on a ggml without trellis types, and the ISA guard knows the AVX-512 files (#3358, tests and build only; the memory fault on gfx1011 is not touched). - **Docker image build.** The terminal stage no longer needs git in the image (it failed with `FileNotFoundError`); the commit comes in as a build argument. +- **The app and the Terminal share one models folder.** Each of the two settings files now remembers when the models folder was chosen; the one changed last wins and the other follows. Nothing is moved. A folder picked in the Terminal was not seen by the app before, so the same model could be downloaded twice. +- **Docker.** An old (0.1.x) volume with `/data/models`, `/data/packs` and `/data/mtp` is moved into `/data/Strata-data` by rename instead of being downloaded and packed again (it used to start a 70 GB download). A card without `--gpus` stops at once with the `--gpus all` hint instead of after minutes of setup. A missing or empty `MODEL_PATH` gets a plain message. Settings that name another image's component folder (a CUDA 12 image on a CUDA 13 volume) are made again. Tested on one RTX 3060 PC; no AMD or Intel image and no Docker Desktop. From a0e09803ac8b2ddc8c1253d8aedfeeaf093ed671 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:20:27 +0200 Subject: [PATCH 18/27] Models folder: move the model files to another folder (strata models move): copied and checked file by file, stoppable, run configs follow --- strata_cli/cli.py | 52 +++- strata_control/models_move.py | 477 +++++++++++++++++++++++++++++ tests/terminal/test_models_move.py | 283 +++++++++++++++++ 3 files changed, 811 insertions(+), 1 deletion(-) create mode 100644 strata_control/models_move.py create mode 100644 tests/terminal/test_models_move.py diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 80e66518..d36946f3 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -159,6 +159,13 @@ def parser() -> argparse.ArgumentParser: models_import.add_argument("--plan", action="store_true", required=True, help="inspect only; adoption requires a qualified model workflow") models_import.add_argument("--output", choices=("human", "json"), default="human") + models_move = models_sp.add_parser("move", help="move the model files (models, packs, mtp) to another folder: copied, checked, then the old copies removed") + models_move.add_argument("to", metavar="NEW_FOLDER") + models_move.add_argument("--from", dest="source", metavar="OLD_FOLDER", help="the folder the models are in now (default: the data folder in use)") + models_move.add_argument("--install-dir", help="absolute path to a Strata installation whose run configs should follow the files") + models_move.add_argument("--plan", action="store_true", help="say what would happen and change nothing") + models_move.add_argument("--cancel-file", metavar="PATH", help="stop (safely) when this file appears") + models_move.add_argument("--output", choices=("human", "json", "jsonl"), default="human") engine = sp.add_parser("engine", help="engine tuning and component actions") engine_sp = engine.add_subparsers(dest="engine_command", required=True) calibrate = engine_sp.add_parser("calibrate", help="measure, review and apply engine tuning") @@ -495,7 +502,7 @@ def parser() -> argparse.ArgumentParser: code_sessions.add_argument("--output", choices=("human", "json"), default="human") for one_shot in (profile_create, profile_list, profile_show, profile_validate, profile_set, profile_source, profile_edit, profile_history, profile_rollback, doctor, - components_verify, models_list, models_inspect, models_import, calibrate, + components_verify, models_list, models_inspect, models_import, models_move, calibrate, runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_cleanup, runtime_restart, *ops_items, bench_run, bench_report, bench_compare, code_sessions, *update_parsers): one_shot.add_argument("--json", action="store_true", help="alias for --output json") @@ -547,6 +554,8 @@ def _models(a: argparse.Namespace) -> int: print(_import_problem(result), file=sys.stderr) return 5 return _success({"plan": result}, machine=a.output == "json", human=_import_words(result)) + if a.models_command == "move": + return _models_move(a) if a.models_command == "list": if a.served: if a.install_dir: @@ -603,6 +612,47 @@ def _import_problem(plan: dict) -> str: return text +def _models_move(a: argparse.Namespace) -> int: + from strata_control import discovery, models, models_move as mm + machine = a.output in ("json", "jsonl") + old = Path(a.source) if a.source else discovery.data_dir(Path.home() / "Strata")[0] + new = Path(a.to).expanduser() + if a.plan: + result = mm.plan(old, new) + if machine: + print(json.dumps({"schema_version": 1, "ok": result["ok"], "plan": result}, ensure_ascii=False, allow_nan=False)) + else: + print(result["issue"]["message"] if result["issue"] else + f"{len(result['models'])} model(s), {result['models_bytes'] / 1e9:.1f} GB; {result['free_bytes'] / 1e9:.1f} GB free in {new}.") + return 0 if result["ok"] else 5 + try: + installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()] + except Exception: + installs = [] + configs = [c for i in installs for c in mm.config_files(i)] + cancel = Path(a.cancel_file) if a.cancel_file else None + + def show(event: dict) -> None: + if a.output == "jsonl": + print(json.dumps(event, ensure_ascii=False, allow_nan=False), flush=True) + elif not machine: + print(f"\r{event['done'] / 1e9:.1f} of {event['total'] / 1e9:.1f} GB {event['file']}", end="", flush=True) + try: + summary = mm.move(old, new, on_progress=show, cancelled=(lambda: cancel.exists()) if cancel else None, configs=configs) + except mm.MoveError as e: + extra = getattr(e, "summary", {}) + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}, **extra}, ensure_ascii=False)) + else: + print(f"\nstrata: {e} {e.details}".rstrip(), file=sys.stderr) + return 5 + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "event": "result", **summary}, ensure_ascii=False)) + else: + print("\n" + ("Your models are moved." if summary["done"] else "Moving stopped. Nothing was lost.")) + return 0 if summary["done"] else 6 + + def _import_words(plan: dict) -> str: """The plain-words result of `strata models import --plan`: what the files are, what is already set up, what changes (nothing).""" cand = plan.get("candidate_selection") or {} diff --git a/strata_control/models_move.py b/strata_control/models_move.py new file mode 100644 index 00000000..36eb6fc2 --- /dev/null +++ b/strata_control/models_move.py @@ -0,0 +1,477 @@ +"""Move the model files (models, packs, mtp) from one data folder to another (0.2.2, Settings > Storage > Models folder). + +The desktop app and the Terminal both use this: ``strata models move``. Rules, in the order they matter: + +* Nothing is deleted until its copy is whole and checked. One file at a time: copy to ``name.part``, compare the size, read the copy + back and compare its SHA-256 with the original's (and with the pinned SHA-256 in the file's ``.done`` mark when it has one), rename it + into place, only then remove the original. The extra space needed is never more than the move itself. +* Stopping is safe. The file in flight is discarded (its ``.part`` is removed), files already moved stay, and the run configs are + rewritten for every model whose files are all in the new folder. The data folder in the settings is changed by the caller only + when the whole move is done, so the app is never pointed at an incomplete folder. +* The same drive is a rename (instant). Another drive is a copy. +* A crash leaves at worst a model in both folders; ``name.part`` files are never trusted. +""" + +from __future__ import annotations + +import errno +import hashlib +import json +import os +import re +import shutil +import tempfile +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +ITEMS = ("models", "packs", "mtp") +STATE_FILE = "models-move.json" +MARGIN = 1.05 # room beside the files themselves: 5 % +CHUNK = 8 * 1024 * 1024 + + +class MoveError(Exception): + """A move that stopped for a reason the person can act on. ``code`` is one of: not_found, not_writable, inside, disk_full, verify, busy, io.""" + + def __init__(self, code: str, message: str, details: str = ""): + super().__init__(message) + self.code = code + self.details = details + + +class Stopped(Exception): + """The person asked to stop.""" + + +@dataclass +class Entry: + rel: str # path under the data folder, with "/" (models//file.gguf) + size: int + group: str # the model it belongs to: "models/", "packs/", "mtp" + + +# ----------------------------------------------------------------------------------------------- what is there + +def _item_dirs(data: Path) -> list[Path]: + """The models / packs / mtp folders of a data folder (any spelling of the name: ``Models`` and ``models`` are one library).""" + try: + names = sorted(p for p in data.iterdir() if p.is_dir() and p.name.lower() in ITEMS) + except OSError: + return [] + return names + + +def inventory(data: Path) -> list[Entry]: + """Every file Strata keeps in a data folder: nothing else is touched. Unfinished downloads (``.part``) are left where they are.""" + found: list[Entry] = [] + for top in _item_dirs(data): + for root, _dirs, files in os.walk(top): + for name in files: + if name.endswith(".part"): + continue + path = Path(root) / name + try: + size = path.stat().st_size + except OSError: + continue + rel = path.relative_to(data).as_posix() + parts = rel.split("/") + kind = parts[0].lower() + group = kind if kind == "mtp" or len(parts) < 3 else parts[1].lower() # a model's GGUF files and its pack are one model + found.append(Entry(rel, size, group)) + found.sort(key=lambda e: (e.group, e.rel)) + return found + + +def groups(entries: list[Entry]) -> list[dict]: + """The models in a list of files, for the person: name (the folder name), bytes.""" + out: dict[str, int] = {} + for e in entries: + out[e.group] = out.get(e.group, 0) + e.size + return [{"group": g, "name": g, "bytes": b} for g, b in out.items()] + + +def _near(path: Path) -> Path: + """The folder that exists and holds ``path`` (or ``path`` itself).""" + p = path + while not p.exists() and p.parent != p: + p = p.parent + return p + + +def same_drive(a: Path, b: Path) -> bool: + try: + return os.stat(_near(a)).st_dev == os.stat(_near(b)).st_dev + except OSError: + return False + + +def _same(a: Path, b: Path) -> bool: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + +def _inside(child: Path, parent: Path) -> bool: + c, p = os.path.normcase(os.path.abspath(child)), os.path.normcase(os.path.abspath(parent)) + return c != p and c.startswith(p.rstrip(os.sep) + os.sep) + + +def _write_test(folder: Path) -> str | None: + """None when files can be written in ``folder`` (made if missing); else the raw refusal.""" + try: + folder.mkdir(parents=True, exist_ok=True) + fd, name = tempfile.mkstemp(prefix=".strata-write-test", dir=folder) + os.close(fd) + os.remove(name) + return None + except OSError as e: + return f"{errno.errorcode.get(e.errno, e.errno)}: {e.strerror or e}, {e.filename or folder}" + + +# ----------------------------------------------------------------------------------------------- plan + +def plan(old: Path, new: Path, *, free=None, write_test: bool = True) -> dict: + """What picking ``new`` for the models folder means, without changing anything. + + Returns ``{ok, issue, old, new, same, same_drive, free_bytes, models_bytes, needed_bytes, models, choices}``. ``issue`` is None or + ``{code, message, details}``: not_found (the folder or its drive is gone), not_writable, inside (one folder inside the other), + same (nothing to do). ``choices`` says which of move / keep / empty can be done and why not. + """ + old, new = Path(old), Path(new) + free = free or (lambda p: shutil.disk_usage(p).free) + entries = inventory(old) if old.is_dir() else [] + total = sum(e.size for e in entries) + result = {"ok": False, "issue": None, "old": str(old), "new": str(new), "same": False, "same_drive": False, "free_bytes": 0, + "models_bytes": total, "needed_bytes": 0, "models": groups(entries), "choices": {}} + + def refuse(code, message, details=""): + result["issue"] = {"code": code, "message": message, "details": details} + result["choices"] = {k: {"possible": False, "reason": message} for k in ("move", "keep", "empty")} + return result + + if _same(old, new): + result["same"] = True + return refuse("same", "That is the folder Strata already uses.") + if _inside(new, old) or _inside(old, new): + return refuse("inside", "Pick a folder outside the current one.") + if not new.exists(): + # a folder that will be made is fine when its parent is there; a drive that is not plugged in is not + drive = Path(new.anchor) if new.anchor else None + if drive is not None and not drive.exists(): + return refuse("not_found", f"Strata can't find {new}.", f"{drive} does not exist") + if write_test: + raw = _write_test(new) + if raw: + return refuse("not_writable", f"Strata can't save files in {new}.", raw) + result["same_drive"] = same_drive(old, new) + try: + result["free_bytes"] = int(free(_near(new))) + except OSError: + result["free_bytes"] = 0 + # a same-drive move is a rename: it needs no room + needed = 0 if result["same_drive"] else int(total * MARGIN) + result["needed_bytes"] = needed + can_move = bool(entries) and result["free_bytes"] >= needed + reason_move = "" if can_move else ("You have no models to move." if not entries + else f"Your models need {_gb(needed)}, this drive has {_gb(result['free_bytes'])} free.") + result["choices"] = {"move": {"possible": can_move, "reason": reason_move}, "keep": {"possible": True, "reason": ""}, + "empty": {"possible": True, "reason": ""}} + result["ok"] = True + return result + + +def _gb(n: int) -> str: + g = n / 1e9 + return f"{g:.0f} GB" if g >= 10 else f"{g:.1f} GB" + + +# ----------------------------------------------------------------------------------------------- the move + +def _sha256_of(path: Path, stop: Callable[[], bool], tick: Callable[[int], None] | None = None) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + while True: + if stop(): + raise Stopped() + block = f.read(CHUNK) + if not block: + break + h.update(block) + if tick: + tick(len(block)) + return h.hexdigest() + + +def _pinned(src: Path) -> str | None: + """The SHA-256 a finished download wrote in its ``.done`` mark (setup.py: ``sha256 ``), when there is one.""" + mark = src.with_name(src.name + ".done") + try: + m = re.search(r"sha256\s+([0-9a-fA-F]{64})", mark.read_text(encoding="utf-8", errors="replace")) + except OSError: + return None + return m.group(1).lower() if m else None + + +def _disk_full(e: OSError) -> bool: + return e.errno in (errno.ENOSPC, errno.EDQUOT) or getattr(e, "winerror", None) in (112, 39) + + +def _copy_verified(src: Path, dst: Path, size: int, stop: Callable[[], bool], tick: Callable[[int], None]) -> None: + """Copy src to dst (through dst.part), prove the copy is the same file, rename it into place. The source is left alone.""" + part = dst.with_name(dst.name + ".part") + dst.parent.mkdir(parents=True, exist_ok=True) + h = hashlib.sha256() + try: + with open(src, "rb") as fin, open(part, "wb") as fout: + while True: + if stop(): + raise Stopped() + block = fin.read(CHUNK) + if not block: + break + h.update(block) + fout.write(block) + tick(len(block)) + fout.flush() + os.fsync(fout.fileno()) + if part.stat().st_size != size: + raise MoveError("verify", f"The copy of {src.name} has the wrong size.", f"{part.stat().st_size} != {size}") + want = h.hexdigest() + pinned = _pinned(src) + if pinned and pinned != want: + raise MoveError("verify", f"{src.name} does not match its saved checksum, so it was not moved.", f"sha256 {want} != pinned {pinned}") + got = _sha256_of(part, stop) + if got != want: + raise MoveError("verify", f"The copy of {src.name} did not match the original.", f"sha256 {got} != {want}") + os.replace(part, dst) + except OSError as e: + _quiet_remove(part) + if _disk_full(e): + raise MoveError("disk_full", "The drive ran out of space.", f"{errno.errorcode.get(e.errno, e.errno)}: {e.strerror}, {e.filename or dst}") from e + raise MoveError("io", f"Strata could not copy {src.name}.", f"{type(e).__name__}: {e}") from e + except BaseException: + _quiet_remove(part) + raise + + +def _quiet_remove(path: Path) -> None: + try: + os.remove(path) + except OSError: + pass + + +def _read_state(new: Path) -> dict: + try: + return json.loads((new / STATE_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +def interrupted(data: Path) -> dict | None: + """The unfinished move recorded in a data folder (``models-move.json``), for 'A move was interrupted'.""" + st = _read_state(data) + return st if st.get("state") == "running" else None + + +def _write_state(new: Path, **fields) -> None: + try: + tmp = new / (STATE_FILE + ".tmp") + tmp.write_text(json.dumps(fields, indent=1), encoding="utf-8") + os.replace(tmp, new / STATE_FILE) + except OSError: + pass + + +def repoint_config(cfg_file: Path, old: Path, new: Path) -> bool: + """A run config whose model files moved from ``old`` to ``new`` names them there (each path only when its file is now there and no longer + at the old place). Same rule as setup.py repoint_config. Returns whether the file changed.""" + try: + cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + return False + + def fix(v): + if isinstance(v, list): + return [fix(x) for x in v] + if isinstance(v, dict): + return {k: fix(x) for k, x in v.items()} + if isinstance(v, str): + o = str(old) + nv, no = os.path.normcase(v), os.path.normcase(o) + if nv.startswith(no + os.sep) or nv.startswith(no + "/"): + rest = v[len(o):] + if re.split(r"[\\/]", rest.lstrip("\\/"))[0].lower() in ITEMS: + n = str(new) + rest + if Path(n).exists() and not Path(v).exists(): + return n + return v + + fixed = fix(cfg) + if fixed == cfg: + return False + tmp = cfg_file.with_name(cfg_file.name + ".move-tmp") + tmp.write_text(json.dumps(fixed, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, cfg_file) + return True + + +def config_files(install: Path | None) -> list[Path]: + """The ``strata-.json`` run configs of an install folder.""" + if not install or not Path(install).is_dir(): + return [] + return [p for p in Path(install).glob("strata-*.json") if not p.name.endswith(".shared-settings.json")] + + +def _prune(folder: Path, stop_at: Path) -> None: + """Remove empty folders from ``folder`` upward, never ``stop_at`` itself.""" + p = folder + while p != stop_at and _inside(p, stop_at): + try: + p.rmdir() + except OSError: + return + p = p.parent + + +def move(old: Path, new: Path, *, on_progress: Callable[[dict], None] | None = None, cancelled: Callable[[], bool] | None = None, + configs: list[Path] | None = None, now: Callable[[], float] = time.time) -> dict: + """Move the model files from ``old`` to ``new``. Returns the summary; raises MoveError (nothing lost) or Stopped. + + ``summary = {done: bool, stopped: bool, moved: [group], remaining: [group], bytes_moved, total_bytes, files_moved, same_drive}``. + """ + old, new = Path(old), Path(new) + emit = on_progress or (lambda _e: None) + stop = cancelled or (lambda: False) + p = plan(old, new, write_test=True) + if p["issue"]: + raise MoveError(p["issue"]["code"], p["issue"]["message"], p["issue"]["details"]) + entries = inventory(old) + total = sum(e.size for e in entries) + if not p["choices"]["move"]["possible"] and entries: + raise MoveError("disk_full", p["choices"]["move"]["reason"]) + # unfinished copies of an earlier run are never trusted + for top in _item_dirs(new): + for root, _d, files in os.walk(top): + for name in files: + if name.endswith(".part"): + _quiet_remove(Path(root) / name) + same = p["same_drive"] + todo = {e.group: [] for e in entries} + for e in entries: + todo[e.group].append(e) + left = {g: len(v) for g, v in todo.items()} + moved_groups: list[str] = [] + state = {"state": "running", "from": str(old), "to": str(new), "started": now(), "bytes": total} + _write_state(new, **state) + done_bytes = 0 + files_moved = 0 + last_emit = [0.0] + started = now() + seen_inodes: dict[tuple, Path] = {} + base_event = lambda **kw: {"event": "progress", "total": total, "same_drive": same, **kw} + + def progress(current: str, group: str, index: int, force: bool = False): + t = now() + if not force and t - last_emit[0] < 0.25: + return + last_emit[0] = t + rate = done_bytes / max(t - started, 0.001) + emit(base_event(done=done_bytes, file=current, group=group, index=index, count=len(entries), + seconds_left=(int((total - done_bytes) / rate) if rate > 0 and not same else 0))) + + def repoint(only_whole: bool = True): + for cfg in (configs or []): + try: + repoint_config(cfg, old, new) + except OSError: + pass + + try: + for index, e in enumerate(entries, 1): + if stop(): + raise Stopped() + src, dst = old / e.rel, new / e.rel + progress(e.rel, e.group, index, force=True) + if not src.exists(): + done_bytes += e.size + left[e.group] -= 1 + else: + if same: + dst.parent.mkdir(parents=True, exist_ok=True) + try: + if dst.exists(): + os.remove(dst) + os.replace(src, dst) + except OSError as err: + raise MoveError("io", f"Strata could not move {src.name}.", f"{type(err).__name__}: {err}") from err + done_bytes += e.size + else: + ino = None + try: + st = src.stat() + ino = (st.st_dev, st.st_ino) if st.st_nlink > 1 and st.st_ino else None + except OSError: + pass + if ino and ino in seen_inodes and seen_inodes[ino].exists(): + # the same file under two names (a shared pack): one copy, the second name links to it + try: + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists(): + os.remove(dst) + os.link(seen_inodes[ino], dst) + except OSError: + _copy_verified(src, dst, e.size, stop, lambda n: None) + done_bytes += e.size + else: + resumed = False + if dst.exists() and dst.stat().st_size == e.size: + # a crash between the rename and the delete: the copy may be whole; prove it before the original goes + resumed = _sha256_of(dst, stop) == _sha256_of(src, stop) + if resumed: + done_bytes += e.size + else: + def tick(n, group=e.group, rel=e.rel, idx=index): + nonlocal done_bytes + done_bytes += n + progress(rel, group, idx) + before = done_bytes + try: + _copy_verified(src, dst, e.size, stop, tick) + except BaseException: + done_bytes = before + raise + if ino: + seen_inodes[ino] = dst + try: + os.remove(src) + except OSError as err: + raise MoveError("io", f"Strata copied {src.name} but could not remove the old copy.", f"{type(err).__name__}: {err}") from err + _prune(src.parent, old) + files_moved += 1 + left[e.group] -= 1 + if left[e.group] == 0: + moved_groups.append(e.group) + repoint() + repoint() + state.update(state="done", finished=now()) + _write_state(new, **state) + _quiet_remove(new / STATE_FILE) + return {"done": True, "stopped": False, "moved": moved_groups, "remaining": [], "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved, "same_drive": same} + except Stopped: + repoint() + state.update(state="stopped") + _write_state(new, **state) + _quiet_remove(new / STATE_FILE) if not moved_groups and not files_moved else None + remaining = [g for g, n in left.items() if n > 0] + return {"done": False, "stopped": True, "moved": moved_groups, "remaining": remaining, "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved, "same_drive": same} + except MoveError as err: + repoint() + state.update(state="failed", error=err.code) + _write_state(new, **state) + err.summary = {"moved": moved_groups, "remaining": [g for g, n in left.items() if n > 0], "bytes_moved": done_bytes, "total_bytes": total, + "files_moved": files_moved} + raise diff --git a/tests/terminal/test_models_move.py b/tests/terminal/test_models_move.py new file mode 100644 index 00000000..80a1408b --- /dev/null +++ b/tests/terminal/test_models_move.py @@ -0,0 +1,283 @@ +"""Moving the models to another folder (strata models move): same drive, another drive, stop, a failed check, disk full, resume.""" +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import models_move as mm + + +def sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +class MoveCase(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="strata-move-") + self.addCleanup(self.tmp.cleanup) + self.base = Path(self.tmp.name) + self.old = self.base / "old" + self.new = self.base / "new" + self.files = { + "models/gyro-s/a.gguf": b"A" * 300_000, + "models/gyro-s/b.gguf": b"B" * 200_000, + "packs/gyro-s/dense.bin": b"D" * 100_000, + "models/coder/c.gguf": b"C" * 150_000, + "mtp/rt/experts.bin": b"M" * 50_000, + } + for rel, data in self.files.items(): + f = self.old / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_bytes(data) + # a finished download carries the pinned checksum in its mark + (self.old / "models/gyro-s/a.gguf.done").write_text(f"done sha256 {sha(self.files['models/gyro-s/a.gguf'])}\n") + (self.old / "notes.txt").write_text("not a model file") # Strata moves its own folders only + self.install = self.base / "install" + self.install.mkdir() + self.config = self.install / "strata-gyro-s.json" + self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gyro-s/a.gguf"), "--pack", str(self.old / "packs/gyro-s")], + "mtp": str(self.old / "mtp/rt")})) + self.total = sum(len(v) for v in self.files.values()) + + def tree(self, root: Path) -> set[str]: + return {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file() and p.name != mm.STATE_FILE} + + def copy_mode(self): + """Another drive: the files are copied, whatever this machine's volumes are.""" + return mock.patch.object(mm, "same_drive", return_value=False) + + def run_move(self, **kw): + events = [] + summary = mm.move(self.old, self.new, on_progress=events.append, configs=[self.config], **kw) + return summary, events + + +class PlanTests(MoveCase): + def test_plan_numbers_and_choices(self): + with self.copy_mode(): + p = mm.plan(self.old, self.new, free=lambda _p: 10**9) + self.assertTrue(p["ok"]) + self.assertGreaterEqual(p["models_bytes"], self.total) + self.assertGreater(p["needed_bytes"], p["models_bytes"]) # the 5 % margin + self.assertTrue(p["choices"]["move"]["possible"]) + self.assertEqual({m["name"] for m in p["models"]}, {"gyro-s", "coder", "mtp"}) + + def test_not_enough_room_switches_move_off(self): + with self.copy_mode(): + p = mm.plan(self.old, self.new, free=lambda _p: 1000) + self.assertTrue(p["ok"]) + self.assertFalse(p["choices"]["move"]["possible"]) + self.assertIn("free", p["choices"]["move"]["reason"]) + self.assertTrue(p["choices"]["keep"]["possible"] and p["choices"]["empty"]["possible"]) + + def test_same_drive_needs_no_room(self): + p = mm.plan(self.old, self.new, free=lambda _p: 0) + self.assertTrue(p["same_drive"]) + self.assertTrue(p["choices"]["move"]["possible"]) + + def test_inside_and_same_are_refused(self): + self.assertEqual(mm.plan(self.old, self.old / "sub")["issue"]["code"], "inside") + self.assertEqual(mm.plan(self.old / "sub", self.old)["issue"]["code"], "inside") + self.assertEqual(mm.plan(self.old, self.old)["issue"]["code"], "same") + + def test_a_folder_that_cannot_be_written_is_refused(self): + with mock.patch.object(mm, "_write_test", return_value="EPERM: operation not permitted, mkdir 'x'"): + p = mm.plan(self.old, self.new) + self.assertEqual(p["issue"]["code"], "not_writable") + self.assertIn("EPERM", p["issue"]["details"]) + + def test_nothing_is_changed_by_a_plan(self): + before = self.tree(self.old) + mm.plan(self.old, self.new) + self.assertEqual(self.tree(self.old), before) + + +class MoveTests(MoveCase): + def check_whole(self): + self.assertEqual({k for k in self.tree(self.new) if not k.endswith(".done")}, set(self.files)) + for rel, data in self.files.items(): + self.assertEqual((self.new / rel).read_bytes(), data) + self.assertEqual(self.tree(self.old), {"notes.txt"}) # only what is not Strata's own is left + cfg = json.loads(self.config.read_text()) + self.assertEqual(Path(cfg["args"][1]), self.new / "models/gyro-s/a.gguf") + self.assertEqual(Path(cfg["mtp"]), self.new / "mtp/rt") + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_same_drive_is_a_rename(self): + with mock.patch.object(shutil, "copyfileobj", side_effect=AssertionError("copied")), mock.patch.object(mm, "_copy_verified", side_effect=AssertionError("copied")): + summary, _events = self.run_move() + self.assertTrue(summary["done"] and summary["same_drive"]) + self.check_whole() + + def test_another_drive_copies_checks_and_removes(self): + with self.copy_mode(): + summary, events = self.run_move() + self.assertTrue(summary["done"] and not summary["same_drive"]) + self.assertEqual(summary["files_moved"], len(self.files) + 1) # + the .done mark + self.check_whole() + self.assertTrue(events and events[-1]["done"] <= self.total + 100) + self.assertEqual(events[0]["event"], "progress") + + def test_stop_keeps_what_moved_and_removes_the_partial_copy(self): + calls = {"n": 0} + + def stop(): + calls["n"] += 1 + return calls["n"] > 6 # a few chunks into the second file or so + with self.copy_mode(): + summary, _events = self.run_move(cancelled=stop) + self.assertTrue(summary["stopped"] and not summary["done"]) + self.assertEqual([p for p in self.new.rglob("*.part")], []) + # every file is in exactly one place, nothing is lost + for rel, data in self.files.items(): + places = [r for r in (self.old, self.new) if (r / rel).exists()] + self.assertEqual(len(places), 1, rel) + self.assertEqual((places[0] / rel).read_bytes(), data) + self.assertTrue(summary["remaining"]) + # a model that moved whole now points at the new folder; one that did not stays where it is + cfg = json.loads(self.config.read_text()) + for value in (cfg["args"][1], cfg["args"][3], cfg["mtp"]): + self.assertTrue(Path(value).exists(), value) + + def test_stop_before_anything_leaves_the_old_folder_as_it_was(self): + with self.copy_mode(): + summary, _ = self.run_move(cancelled=lambda: True) + self.assertTrue(summary["stopped"]) + self.assertEqual(summary["files_moved"], 0) + self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"}) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_a_copy_that_does_not_match_is_never_trusted(self): + real = mm._sha256_of + calls = {"n": 0} + + def lies(path, stop, tick=None): + calls["n"] += 1 + return "0" * 64 if str(path).endswith(".part") and calls["n"] == 1 else real(path, stop, tick) + with self.copy_mode(), mock.patch.object(mm, "_sha256_of", side_effect=lies): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "verify") + self.assertEqual(list(self.new.rglob("*.part")), []) + self.assertEqual({k for k in self.tree(self.old) if not k.endswith(".done")}, set(self.files) | {"notes.txt"}) # the original is untouched + + def test_a_file_that_differs_from_its_pinned_checksum_is_not_moved(self): + (self.old / "models/gyro-s/a.gguf.done").write_text("done sha256 " + "1" * 64) + with self.copy_mode(): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "verify") + self.assertTrue((self.old / "models/gyro-s/a.gguf").exists()) + self.assertFalse((self.new / "models/gyro-s/a.gguf").exists()) + + def test_disk_full_stops_at_once_and_loses_nothing(self): + real = mm._copy_verified + seen = {"n": 0} + + def full(src, dst, size, stop, tick): + seen["n"] += 1 + if seen["n"] == 3: + part = dst.with_name(dst.name + ".part") + part.parent.mkdir(parents=True, exist_ok=True) + part.write_bytes(b"half") + try: + raise OSError(28, "No space left on device", str(dst)) + except OSError as e: + mm._quiet_remove(part) + raise mm.MoveError("disk_full", "The drive ran out of space.", str(e)) from e + return real(src, dst, size, stop, tick) + with self.copy_mode(), mock.patch.object(mm, "_copy_verified", side_effect=full): + with self.assertRaises(mm.MoveError) as caught: + self.run_move() + self.assertEqual(caught.exception.code, "disk_full") + self.assertEqual(list(self.new.rglob("*.part")), []) + for rel, data in self.files.items(): + places = [r for r in (self.old, self.new) if (r / rel).exists()] + self.assertEqual(len(places), 1, rel) + self.assertIn("remaining", caught.exception.summary) + + def test_a_real_disk_full_error_is_named(self): + with mock.patch("builtins.open", side_effect=OSError(28, "No space left on device", "x")): + with self.assertRaises(mm.MoveError) as caught: + mm._copy_verified(self.old / "models/coder/c.gguf", self.new / "x.gguf", 1, lambda: False, lambda n: None) + self.assertEqual(caught.exception.code, "disk_full") + + def test_a_crash_leaves_a_part_and_the_next_run_finishes(self): + stale = self.new / "models/gyro-s/a.gguf.part" + stale.parent.mkdir(parents=True) + stale.write_bytes(b"cut off") + # a file that was copied and renamed, but whose original was not removed yet + done = self.new / "models/coder/c.gguf" + done.parent.mkdir(parents=True) + done.write_bytes(self.files["models/coder/c.gguf"]) + with self.copy_mode(): + summary, _ = self.run_move() + self.assertTrue(summary["done"]) + self.check_whole() + + def test_an_interrupted_move_is_remembered(self): + with self.copy_mode(): + with self.assertRaises(mm.MoveError): + with mock.patch.object(mm, "_copy_verified", side_effect=mm.MoveError("io", "x")): + self.run_move() + self.assertEqual(mm.interrupted(self.new), None) # failed is not "running" + mm._write_state(self.new, state="running", **{"from": str(self.old), "to": str(self.new)}) + self.assertEqual(mm.interrupted(self.new)["from"], str(self.old)) + + def test_configs_are_rewritten_only_for_files_that_are_there(self): + self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gone.gguf")]})) + with self.copy_mode(): + self.run_move() + self.assertEqual(json.loads(self.config.read_text())["args"][1], str(self.old / "models/gone.gguf")) + + @unittest.skipUnless(os.environ.get("STRATA_TEST_OTHER_VOLUME"), "set STRATA_TEST_OTHER_VOLUME to a folder on another volume (e.g. a subst or USB drive)") + def test_a_real_second_volume(self): + other = Path(os.environ["STRATA_TEST_OTHER_VOLUME"]) / f"strata-move-{os.getpid()}" + self.addCleanup(shutil.rmtree, other, True) + self.new = other + summary, _ = self.run_move() + self.assertTrue(summary["done"]) + self.check_whole() + + +class CommandLineTests(MoveCase): + def test_json_plan_and_run(self): + from strata_cli import cli + import contextlib + import io + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--plan", "--output", "json"]) + self.assertEqual(code, 0) + self.assertTrue(json.loads(out.getvalue())["plan"]["choices"]["move"]["possible"]) + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--install-dir", str(self.install), "--output", "jsonl"]) + self.assertEqual(code, 0, out.getvalue()) + lines = [json.loads(line) for line in out.getvalue().splitlines() if line.startswith("{")] + self.assertEqual(lines[-1]["event"], "result") + self.assertTrue(lines[-1]["done"]) + self.assertTrue((self.new / "models/coder/c.gguf").exists()) + + def test_the_cancel_file_stops_the_run(self): + from strata_cli import cli + import contextlib + import io + cancel = self.base / "cancel" + cancel.write_text("x") + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(): + code = cli.main(["models", "move", str(self.new), "--from", str(self.old), "--cancel-file", str(cancel), "--output", "json"]) + self.assertEqual(code, 6) + self.assertTrue(json.loads(out.getvalue().splitlines()[-1])["stopped"]) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) + + +if __name__ == "__main__": + unittest.main() From 1d6a040129ac0a11ff822ca372f55ab94dfd58cc Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:29:44 +0200 Subject: [PATCH 19/27] Settings > Storage: Models folder card with the three choices (move, keep, start empty), progress, stop, and plain errors; host routes and Control calls; 78 strings in 8 languages; tests --- apps/host/server/control-runtime.mjs | 17 ++ apps/host/server/index.mjs | 10 +- apps/host/server/native-control.mjs | 80 +++++- .../src/components/ModelsFolderDialog.tsx | 230 ++++++++++++++++++ apps/host/src/components/SettingsStorage.tsx | 3 + apps/host/src/components/ui.tsx | 6 +- apps/host/src/lib/native.ts | 2 +- apps/host/src/locales/de.json | 80 +++++- apps/host/src/locales/en.json | 80 +++++- apps/host/src/locales/es.json | 80 +++++- apps/host/src/locales/ja.json | 80 +++++- apps/host/src/locales/ko.json | 80 +++++- apps/host/src/locales/pt.json | 80 +++++- apps/host/src/locales/ru.json | 80 +++++- apps/host/src/locales/zh.json | 80 +++++- apps/host/src/styles/annotation-fixes.css | 22 ++ apps/host/tests/models-folder.test.mjs | 161 ++++++++++++ 17 files changed, 1153 insertions(+), 18 deletions(-) create mode 100644 apps/host/src/components/ModelsFolderDialog.tsx create mode 100644 apps/host/tests/models-folder.test.mjs diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 6f352b54..0447572d 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -207,6 +207,23 @@ export function createControl({ control = findControl(), env = process.env, run if (result.json?.plan && Array.isArray(result.json.plan.issues)) return result.json.plan; throw failure(result, 'The files could not be checked.'); }, + /** What picking `to` as the models folder means (sizes, free space, which choices are possible, why not): nothing is changed. */ + async planModelsMove(from, to) { + const result = await call(['models', 'move', to, ...(from ? ['--from', from] : []), '--plan', '--output', 'json'], { timeoutMs: 120_000 }); + if (result.json?.plan) return result.json.plan; + throw failure(result, 'The folder could not be checked.'); + }, + /** + * Move the model files to `to` (copied, checked, then the old copies removed). `onEvent` gets the progress lines; a file at `cancelFile` stops it + * safely. Resolves with the summary (done / stopped, what moved, what is left); a failure is a ControlError whose `output` carries the details. + */ + async moveModels(from, to, { installDir = null, cancelFile = null, onEvent = null } = {}) { + const args = ['models', 'move', to, ...(from ? ['--from', from] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl']; + const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) }); + if (result.json?.ok && result.json.event === 'result') return result.json; + const error = result.json?.error; + throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' }); + }, async saveProfile(name, configPath) { const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 }); const known = (listed.json?.profiles ?? []).some(p => p.id === name); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 30a5557a..eb454cb4 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -966,6 +966,14 @@ async function api(req, res, path, method, url) { if(path==='/api/native'&&method==='GET')return json(res,200,await native.refresh(url.searchParams.get('refresh')==='1')); if(path==='/api/native'&&method==='PATCH')return json(res,200,await native.configure(await readBody(req))); if(path==='/api/native/directory'&&method==='POST')return json(res,200,native.setDownloadDirectory((await readBody(req)).directory)); + /* Settings > Storage > Models folder: pick (or type) a folder, say what it means, then start the choice. Copying is Control's (strata models move). */ + if(path==='/api/native/models-folder/plan'&&method==='POST'){ + const typed=await typedFolder((await readBody(req)).path,{isAbsolute}); + const picked=typed?{path:typed}:await chooseFolder('Choose a folder for your models'); + if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});} + if(picked.cancelled)return json(res,200,{cancelled:true}); + return json(res,200,{plan:await native.planModelsFolder(picked.path)});} + if(path==='/api/native/models-folder/start'&&method==='POST'){const body=await readBody(req);const result=await native.startModelsFolder({folder:body.path,choice:body.choice,stopRunning:body.stopRunning===true});return json(res,result.id?202:200,result);} if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req))); if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); @@ -1010,7 +1018,7 @@ async function api(req, res, path, method, url) { if(nativeSettingsFile&&method==='POST')return json(res,200,await native.openSettingsFile(nativeSettingsFile[1])); // Credentials are handled only on the host. Responses and events expose a key-set flag. - return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message);}} + return error(res,404,'Unknown native control action.');}catch(e){return error(res,/Finish|Unload|running|current operation/.test(e.message)?409:400,e.message,{...(e.code&&typeof e.code==='string'?{code:e.code}:{}),...(e.details?{details:String(e.details)}:{})});}} if (path === '/api/model-providers' && method === 'GET') return json(res, 200, withPictureAnswers(modelProviders.list())); if (path === '/api/model-providers/discover' && method === 'POST') { diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 618abeed..75f7c0ce 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -2,8 +2,8 @@ import { spawn } from 'node:child_process'; import {chooseParallel,applyParallel,withoutParallel,FALLBACK_NOTE} from './native-parallel.mjs'; import { randomBytes, randomUUID, createHash } from 'node:crypto'; -import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; -import { join, resolve, dirname, basename } from 'node:path'; +import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, realpathSync, copyFileSync, renameSync, rmSync, statfsSync, unlinkSync, chmodSync, statSync, accessSync, constants } from 'node:fs'; +import { join, resolve, dirname, basename, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createServer } from 'node:net'; import { NATIVE_FIELDS, APP_OWNED_FIELDS, withoutDraftLayer, validateNativeSettings, validateMcpServers, publicMcpServers, publicNativeEnv, restoreNativeEnv } from './native-settings.mjs'; @@ -52,7 +52,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp let defaultId=null,timer=null,closing=false,polling=false; const emit=()=>{const value=state();writeFileSync(join(directory,'native-jobs.json'),JSON.stringify(value.jobs),{mode:0o600});changed(value);}; const append=(instanceId,line)=>{logs.push({at:new Date().toISOString(),instanceId,line:String(line).slice(0,2000)});if(logs.length>400)logs.shift();}; - function state(){return {...snapshot,downloadDirectory:preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} + function diskSpace(path){try{const s=statfsSync(path);return {free:Number(s.bavail)*Number(s.bsize),total:Number(s.blocks)*Number(s.bsize)};}catch{return null;}} + function state(){const folder=preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder),space=folder?diskSpace(folder):null;return {...snapshot,downloadDirectory:folder,downloadFreeBytes:space?.free??null,downloadTotalBytes:space?.total??null,fields:nativeFields(),instances:[...instances.values()].map(({key,configPath,fingerprint,mcpServers,...i})=>structuredClone(i)),defaultId,jobs:[...jobs.values()].slice(-12).map(({process,abort,engineAbort,rawResult,...j})=>j),capabilities:{responses:sourceText().includes('/v1/responses'),updates:!!snapshot.available,rollback:previousEngine(),componentUpdates:packaged&&typeof control.update==='function',calibration:packaged?false:snapshot.hardware?.gpus?.some(g=>/nvidia/i.test(g.name??''))??false}};} let sourceCache={path:'',time:0,text:''}; function sourceText(){try{const path=join(packaged?control.control.dir:preferences.repo,'serve/server.py'),time=statSync(path).mtimeMs;if(sourceCache.path===path&&sourceCache.time===time)return sourceCache.text;sourceCache={path,time,text:readFileSync(path,'utf8')};return sourceCache.text;}catch{return '';}} function nativeFields(){const source=sourceText();return NATIVE_FIELDS.map(field=>({...field,supported:APP_OWNED_FIELDS.includes(field.id)||field.id.startsWith('vision_')||field.id.startsWith('mcp_')||field.id==='vram_reserve_mib'||source.includes(field.id)}));} @@ -126,7 +127,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run; } function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);} - function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();} + function setDownloadDirectory(input,{insideJob=false}={}){if(!insideJob&&[...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path,Date.now()/1000,true);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});shareDataFolder();emit();return state();} function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};} function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};} /* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */ @@ -377,10 +378,77 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}}); } function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} - async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} + /* ---- The models folder card (0.2.2): what a picked folder means, and the three choices. The copying is Control's (strata models move). ---- */ + const currentModelsFolder=()=>preferences.downloadDirectory??(modelsDirectory?modelsDirectory():snapshot.installed?.data_folder)??null; + const moveFile=()=>join(directory,'models-move.cancel'); + const folderWords=error=>({message:error.message,details:error.details||''}); + /** A picked folder as the data folder: a whole drive (D:\) becomes D:\Strata, and the person is told (the models then live in D:\Strata\Models). */ + function pickedModelsFolder(input){ + if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a models folder.'); + const picked=resolve(input.trim()),target=dataFolderFromPick(picked); + return {picked,folder:target.path,wholeDrive:!!target.note,shown:target.note?join(target.path,'Models'):target.path}; + } + async function planModelsFolder(input){ + if(!packaged)throw new Error('Changing the models folder is part of the Strata app.'); + const now=currentModelsFolder();if(!now)throw new Error('Strata is still reading your models folder. Try again in a moment.'); + const pick=pickedModelsFolder(input),plan=await control.planModelsMove(now,pick.folder); + return {...plan,...pick,current:now,running:instances.size,busy:[...jobs.values()].some(j=>j.state==='running')}; + } + /* "Start empty": the old models are no longer listed. Their run configs are moved (not deleted) into old-models beside the others; the model files are not touched. */ + function setAsideConfigs(old){ + const folder=repo(),kept=join(folder,'old-models'),aside=[]; + const under=value=>typeof value==='string'&&[ 'models','packs','mtp' ].some(item=>{const base=join(old,item).toLowerCase();const v=value.toLowerCase();return v===base||v.startsWith(base+sep)||v.startsWith(base+'/');}); + const scan=value=>Array.isArray(value)?value.some(scan):value&&typeof value==='object'?Object.values(value).some(scan):under(value); + for(const name of readdirSync(folder)){ + if(!/^strata-[a-z0-9_-]+\.json$/i.test(name)||name.endsWith('.shared-settings.json'))continue; + if(!scan(readJson(join(folder,name))))continue; + mkdirSync(kept,{recursive:true});renameSync(join(folder,name),join(kept,name));aside.push(name); + } + return aside; + } + async function startModelsFolder({folder:input,choice,stopRunning=false}){ + if(!packaged)throw new Error('Changing the models folder is part of the Strata app.'); + if(!['move','keep','empty'].includes(choice))throw new Error('Choose what to do with your models.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + const plan=await planModelsFolder(input); + if(plan.issue)throw Object.assign(new Error(plan.issue.message),{details:plan.issue.details,code:plan.issue.code}); + if(!plan.choices[choice].possible)throw Object.assign(new Error(plan.choices[choice].reason||'That choice is not possible here.'),{code:'not_possible'}); + if(instances.size){ + if(!stopRunning)throw Object.assign(new Error('A model is running. Stop it first, then change the folder.'),{code:'running'}); + for(const id of [...instances.keys()])await unload(id); + } + const old=plan.current,target=plan.folder; + if(choice!=='move'){ + makeFolder(target); + const aside=choice==='empty'?setAsideConfigs(old):[]; + setDownloadDirectory(target);lastRead=0;await refresh(true); + return {done:true,choice,folder:target,oldFolder:old,setAside:aside}; + } + rmSync(moveFile(),{force:true}); + return begin('models-move',async job=>{ + job.cancelFile=moveFile();job.summary='Starting…'; + try{ + const result=await control.moveModels(old,target,{installDir:repo(),cancelFile:moveFile(),onEvent:event=>{ + if(event.event!=='progress')return; + job.progress={done:event.done,total:event.total,file:event.file,group:event.group,index:event.index,count:event.count,secondsLeft:event.seconds_left||0,sameDrive:!!event.same_drive}; + job.summary=`${Math.round(event.done/1e8)/10} of ${Math.round(event.total/1e8)/10} GB`;emit();}}); + const finished={done:!!result.done,stopped:!!result.stopped,moved:result.moved??[],remaining:result.remaining??[],bytes:result.bytes_moved??0,total:result.total_bytes??0,from:old,to:target,files:result.files_moved??0,sameDrive:!!result.same_drive}; + /* Only a whole move changes the folder the app uses: a stopped move leaves it where it was, and every model works where it is. */ + if(result.done){setDownloadDirectory(target,{insideJob:true});finished.folder=target;} + job.progress=null; + return {summary:result.done?'Your models are moved.':'Moving stopped. Nothing was lost.',...finished}; + }catch(error){ + const left=error.output; + job.result={failed:true,code:error.code,moved:left?.moved??[],remaining:left?.remaining??[],bytes:left?.bytes_moved??0,total:left?.total_bytes??0,from:old,to:target}; + job.progress=null; + throw error; + }finally{rmSync(moveFile(),{force:true});} + },{family:undefined}); + } + async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.kind==='models-move'){/* a safe stop: the copy in flight is dropped, files already moved stay */try{writeFileSync(job.cancelFile,'stop');}catch{/* the run ends anyway */}job.summary='Stopping…';emit();return state();}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;}; async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} - return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; + return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; } diff --git a/apps/host/src/components/ModelsFolderDialog.tsx b/apps/host/src/components/ModelsFolderDialog.tsx new file mode 100644 index 00000000..bf628542 --- /dev/null +++ b/apps/host/src/components/ModelsFolderDialog.tsx @@ -0,0 +1,230 @@ +import { tr, localeTag } from '../lib/i18n'; +import { useEffect, useMemo, useState } from 'react'; +import { Bar, Btn, Dialog, Icon } from './ui'; +import { api, ApiError } from '../lib/client'; +import { nativeAction, refreshNative, useNative, type NativeJob, type NativeState } from '../lib/native'; +import { nativeShortName } from '../lib/native-names'; +import { sizeGb } from '../lib/format'; + +type Choice = 'move' | 'keep' | 'empty'; +interface Plan { + ok: boolean; + issue: { code: string; message: string; details: string } | null; + old: string; new: string; same_drive: boolean; + free_bytes: number; models_bytes: number; needed_bytes: number; + models: { group: string; name: string; bytes: number }[]; + choices: Record; + folder: string; picked: string; wholeDrive: boolean; shown: string; current: string; running: number; busy: boolean; +} +interface Outcome { done?: boolean; stopped?: boolean; failed?: boolean; code?: string; moved?: string[]; remaining?: string[]; bytes?: number; total?: number; from?: string; to?: string; sameDrive?: boolean } + +const gb = (bytes: number) => sizeGb(bytes / 1e9); +const driveOf = (path: string) => /^[A-Za-z]:/.test(path) ? path.slice(0, 2) : path; +const list = (items: string[]) => { try { return new Intl.ListFormat(localeTag(), { type: 'conjunction' }).format(items); } catch { return items.join(', '); } }; + +/** The model a folder name belongs to, in the words the Storage list uses ("Gyro-S"); the draft layer and loose files have no name of their own. */ +function modelName(group: string, native: NativeState | null) { + const hit = native?.installed?.models.find(m => m.model.toLowerCase() === group.toLowerCase()); + return hit ? nativeShortName(hit.model) : null; +} + +function timeLeft(seconds: number) { + if (seconds <= 0) return null; + if (seconds < 60) return tr('Less than a minute left'); + const minutes = Math.ceil(seconds / 60); + if (minutes <= 1) return tr('About a minute left'); + if (minutes < 120) return tr('About {0} minutes left', [minutes]); + return tr('About {0} hours left', [Math.ceil(minutes / 60)]); +} + +function Failure({ message, next, details }: { message: string; next?: string; details?: string }) { + return
{tr(message)}{next ?

{tr(next)}

: null}{details ?
{tr('Details')}
{details}
: null}
; +} + +/** Settings > Storage > Models folder: the card, the folder dialog with its three choices, the progress of a move and what came of it. */ +export function ModelsFolderCard({ blocked }: { blocked: boolean }) { + const native = useNative(); + const [plan, setPlan] = useState(null); + const [stage, setStage] = useState<'issue' | 'drive' | 'choose' | null>(null); + const [choice, setChoice] = useState('move'); + const [pending, setPending] = useState(false); + const [error, setError] = useState<{ message: string; details?: string } | null>(null); + const [typing, setTyping] = useState(false), [typed, setTyped] = useState(''); + const [jobId, setJobId] = useState(null); + const [outcome, setOutcome] = useState<{ job: NativeJob } | null>(null); + const [notice, setNotice] = useState(''); + const [stopping, setStopping] = useState(false); + const folder = native?.downloadDirectory ?? ''; + const free = native?.downloadFreeBytes ?? null; + const usage = native?.installed?.usage?.total_bytes ?? 0; + const moving = native?.jobs.find(j => j.kind === 'models-move' && j.state === 'running') ?? null; + const finished = jobId ? native?.jobs.find(j => j.id === jobId && j.kind === 'models-move' && j.state !== 'running') : undefined; + useEffect(() => { if (finished && !outcome) { setOutcome({ job: finished }); setStopping(false); void refreshNative(true); } }, [finished, outcome]); + const total = native?.downloadTotalBytes ?? null; + const used = free !== null && total ? Math.min(100, Math.max(1, ((total - free) / total) * 100)) : 0; + useEffect(() => { if (moving && !jobId) setJobId(moving.id); }, [moving, jobId]); + + function leave() { setPlan(null); setStage(null); setError(null); setTyping(false); } + async function pick(path = '') { + setPending(true); + setError(null); + setNotice(''); + try { + const result = await api.post<{ cancelled?: boolean; plan?: Plan }>('/api/native/models-folder/plan', { path }); + if (result.cancelled || !result.plan) return; + const next = result.plan; + setTyping(false); + setPlan(next); + if (next.issue?.code === 'same') { setPlan(null); return; } + setChoice(next.choices.move.possible ? 'move' : 'keep'); + setStage(next.issue ? 'issue' : next.wholeDrive ? 'drive' : 'choose'); + } + catch (e) { + if (e instanceof ApiError && e.status === 501) { setTyping(true); setError({ message: e.message }); } + else setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); + } + finally { setPending(false); } + } + async function start() { + if (!plan) return; + setPending(true); + setError(null); + try { + const result = await api.post('/api/native/models-folder/start', { path: plan.picked, choice, stopRunning: true }); + if (result.id) { setJobId(result.id); setOutcome(null); setStage(null); await refreshNative(true); setPlan(prev => prev); return; } + setNotice(choice === 'keep' ? tr('Strata now also uses {0}. New downloads go there, and your current models stay where they are.', [plan.shown]) + : tr('Strata now uses {0}. Your old model files are still in {1}; Strata does not delete them.', [plan.shown, plan.current])); + await refreshNative(true); + leave(); + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + async function stop() { + if (!moving) return; + setStopping(true); + try { await nativeAction(`operations/${moving.id}/cancel`); } + catch (e) { setError({ message: (e as Error).message }); } + } + function closeResult() { setOutcome(null); setJobId(null); leave(); setNotice(''); } + + const progress = moving?.progress as { done: number; total: number; file: string; group: string; index: number; count: number; secondsLeft: number; sameDrive: boolean } | null | undefined; + const percent = progress && progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0; + const planNames = useMemo(() => (plan?.models ?? []).map(m => ({ ...m, label: modelName(m.group, native) })).filter(m => m.label), [plan, native]); + const savedPlan = useMemo(() => plan, [plan]); + + return <> +
+
{tr('Models folder')} void pick()}>{tr(pending && !plan ? 'Waiting for the folder…' : 'Change folder')}
+

{tr('Strata saves the big model files here.')}

+ {folder || tr('Reading model directory…')} + {free !== null ?
{tr('{0} free', [gb(free)])} {tr('on this drive')}{tr('Your models use {0}', [gb(usage)])}
: null} + {blocked && !moving ?

{tr('Finish or stop the download to change the folder.')}

: null} + {typing ?
{ e.preventDefault(); if (typed.trim()) void pick(typed.trim()); }}> + + setTyped(e.target.value)} placeholder={tr('Full path to an existing folder')} spellCheck={false} autoFocus/> +
{tr('Use this directory')}
+
: null} + {notice ?

{notice}

: null} + {error && !stage ? : null} +
+ + {plan?.issue?.code === 'not_found' ? null : {tr('Cancel')}} { leave(); void pick(); }}>{tr('Choose another folder')}}> + {plan?.issue ? : null} + + + {tr('Cancel')} setStage('choose')}>{tr('Continue')}}> + {plan ? <> +
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
+
{tr('You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.', [plan.picked, plan.shown])}
+

{tr('The three choices follow, as in step 2.')}

+ : null} +
+ + { if (!pending) leave(); }} + actions={plan ? <>{plan.choices.move.possible ? {tr('Cancel')} : { leave(); void pick(); }}>{tr('Choose another folder')}} void start()}>{tr(pending ? 'Working…' : choice === 'move' ? 'Move my models' : choice === 'keep' ? 'Use both folders' : 'Start empty')} : null}> + {plan ? : null} + + + undefined} + actions={ void stop()}>{tr(stopping ? 'Stopping…' : 'Stop moving')}}> +
{tr('{0} of {1} GB', [progress ? (progress.done / 1e9 >= 10 ? Math.round(progress.done / 1e9) : (progress.done / 1e9).toFixed(1)) : 0, Math.round((progress?.total ?? 0) / 1e9)])}{progress && !progress.sameDrive ? timeLeft(progress.secondsLeft) : null}
+

{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}

+ {progress ?
{tr('Details')}
    +
  • {tr('Now copying: {0}, file {1} of {2}', [modelName(progress.group, native) ?? progress.group, progress.index, progress.count])}
  • +
  • {tr('From {0} to {1}', [savedPlan?.current ?? '', savedPlan?.folder ?? ''])}
: null} +
+ + { closeResult(); void pick(); }}/> + ; +} + +function ChooseBody({ plan, choice, setChoice, names, error }: { plan: Plan; choice: Choice; setChoice: (c: Choice) => void; names: (Plan['models'][number] & { label: string | null })[]; error: { message: string; details?: string } | null }) { + const none = plan.models_bytes === 0; + const short = !none && !plan.choices.move.possible; + const lacking = Math.max(0, plan.needed_bytes - plan.free_bytes); + const options: { id: Choice; title: string; text: string; need: string }[] = [ + { id: 'move', title: 'Move my models there', text: none ? 'You have no models to move.' : plan.same_drive ? 'Strata moves your {0} of models to the new folder. This is the same drive, so it takes a moment.' : 'Strata copies your {0} of models to the new folder, checks them, then removes the old copies.', + need: none ? '' : plan.same_drive ? 'Needs no extra space.' : 'Needs {0} free in the new folder. You have {1}.' }, + { id: 'keep', title: 'Keep them where they are and also use the new folder', text: 'Nothing is copied. Your current models keep working, and new downloads go to the new folder.', need: short ? 'Needs no space now. New downloads must fit in {1}.' : 'Needs no space now.' }, + { id: 'empty', title: 'Start empty', text: 'Strata uses the new folder from now on and does not list your current models. Your old files are not deleted.', need: 'Needs no space now. Each model you download later needs its own space.' }, + ]; + const values = [gb(plan.models_bytes), gb(plan.free_bytes)]; + const running = plan.running > 0; + return <> +
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
+ {short ?
{tr('Your models need {0}, this drive has {1} free.', [gb(plan.needed_bytes), gb(plan.free_bytes)])}
{tr('Free up about {0} there, pick another folder, or choose one of the other two options.', [gb(lacking)])}
: null} +
+ {options.map(o => { const possible = plan.choices[o.id].possible; return ; })} +
+ {running ?

{tr('A running model is stopped first; load it again when the move is done.')}

: null} + {error ? : null} +
{tr('Details')}
    + {names.length ?
  • {tr('{0} would move.', [list(names.map(m => `${m.label}, ${gb(m.bytes)}`))])}
  • : null} + {short ?
  • {tr('Free space is measured on the drive that holds {0}.', [plan.shown])}
  • : <> +
  • {tr('Old folder: {0}', [plan.current])}
  • +
  • {tr('Strata copies one file at a time and checks its size before it removes the old one.')}
  • +
  • {tr('You can stop at any time; files already moved stay usable.')}
  • } +
+ ; +} + +function ResultDialog({ outcome, plan, native, onClose, onAgain }: { outcome: NativeJob | null; plan: Plan | null; native: NativeState | null; onClose: () => void; onAgain: () => void }) { + if (!outcome) return null; + const result = (outcome.result ?? {}) as Outcome; + const sized = (groups: string[]) => list(groups.map(g => { const m = plan?.models.find(x => x.group === g); const name = modelName(g, native); return name ? `${name} (${gb(m?.bytes ?? 0)})` : null; }).filter((x): x is string => !!x)); + if (outcome.state === 'error') { + const full = result.code === 'disk_full'; + const where = driveOf(result.to ?? ''); + const some = (result.moved?.length ?? 0) > 0; + return {tr('Close')}{tr('Choose another folder')}}> +
+ {full ? tr('{0} filled up after {1}, so the move stopped.', [where, gb(result.bytes ?? 0)]) : tr(outcome.error ?? 'The models could not be moved.')} +

{full ? (some ? tr('Nothing was lost. Models already moved are in the new folder, the rest are still in {0}, and the half-copied file was removed. Free up space on {1} or choose another folder, then try again.', [result.from ?? '', where]) + : tr('Nothing was lost. All your models are still in {0}, and the half-copied file was removed. Free up space on {1} or choose another folder, then try again.', [result.from ?? '', where])) + : tr('Nothing was lost. Your models that were not moved are still in {0}. Choose another folder to try again.', [result.from ?? ''])}

+ {outcome.details ?
{tr('Details')}
{outcome.details}
: null} +
+
; + } + if (result.stopped) { + const moved = sized(result.moved ?? []), left = sized(result.remaining ?? []); + return {tr('Close')}}> +
{tr('Nothing was lost.')}
+ {moved ? tr('{0} is in the new folder.', [moved]) + ' ' : ''}{left ? tr('{0} is still in the old folder.', [left]) + ' ' : ''}{moved && left ? tr('Both work.') : ''}
+

{tr('Models in both folders are listed as normal. You can finish moving later with Change folder.')}

+
; + } + return {tr('Done')}}> +
{tr('{0} now live in {1}', [gb(result.total ?? 0), plan?.shown ?? result.to ?? ''])} + {result.sameDrive ? null : <>
{tr('The old copies were removed and {0} is free again on {1}.', [gb(result.total ?? 0), driveOf(result.from ?? '')])}}
+
; +} diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsx index ba0dab55..9fbf9344 100644 --- a/apps/host/src/components/SettingsStorage.tsx +++ b/apps/host/src/components/SettingsStorage.tsx @@ -6,6 +6,7 @@ import { pickerGroups, pickerVersionState } from '../lib/model-picker'; import { sizeGb } from '../lib/format'; import { useNative } from '../lib/native'; import { NativeDeleteDialog } from './NativeDelete'; +import { ModelsFolderCard } from './ModelsFolderDialog'; import { nativeShortName } from '../lib/native-names'; export function SettingsStorage() { const state = useStore(s => s); @@ -77,7 +78,9 @@ export function SettingsStorage() { setPending(false); } } + const downloading = !!native?.jobs.some(j => j.state === 'running' && j.kind !== 'models-move') || !!library?.downloads.active || !!state.imageModels?.variants.some(v => v.state === 'downloading'); return <> + {native?.available && native.downloadDirectory ? : null}
{tr("Model directory")} { setDirectory(currentDirectory); setEditing(!editing); setDirectoryError(''); setNotice(''); }}>{tr(editing ? 'Cancel' : 'Change directory')}

{tr("Your models are saved here. Use an existing folder to reuse supported downloads.")}

diff --git a/apps/host/src/components/ui.tsx b/apps/host/src/components/ui.tsx index a319355f..8a475f0e 100644 --- a/apps/host/src/components/ui.tsx +++ b/apps/host/src/components/ui.tsx @@ -384,7 +384,7 @@ export function Select({ value, valueSuffix, options, onChange ); } /** One modal surface for confirmations and narrow-screen inspectors. */ -export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className }: { +export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className, noClose = false }: { open: boolean; title: ReactNode; onClose: () => void; @@ -396,6 +396,8 @@ export function Dialog({ open, title, onClose, children, actions, headerActions, wide?: boolean; hideTitle?: boolean; className?: string; + /** No close button: the person must use the dialog's own buttons (a move that is running). */ + noClose?: boolean; }) { const ref = useRef(null); const id = useId(); @@ -418,7 +420,7 @@ export function Dialog({ open, title, onClose, children, actions, headerActions, return createPortal(
- {plan?.issue?.code === 'not_found' ? null : {tr('Cancel')}} { leave(); void pick(); }}>{tr('Choose another folder')}}> {plan?.issue ? : null} - {tr('Cancel')} setStage('choose')}>{tr('Continue')}}> {plan ? <>
{tr('New folder')}{plan.shown}{tr('{0} free on this drive', [gb(plan.free_bytes)])}
{tr('You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.', [plan.picked, plan.shown])}
-

{tr('The three choices follow, as in step 2.')}

+

{tr('The three choices come next.')}

: null}
- { if (!pending) leave(); }} + { if (!pending) leave(); }} actions={plan ? <>{plan.choices.move.possible ? {tr('Cancel')} : { leave(); void pick(); }}>{tr('Choose another folder')}} void start()}>{tr(pending ? 'Working…' : choice === 'move' ? 'Move my models' : choice === 'keep' ? 'Use both folders' : 'Start empty')} : null}> {plan ? : null} - undefined} + undefined} actions={ void stop()}>{tr(stopping ? 'Stopping…' : 'Stop moving')}}>
{tr('{0} of {1} GB', [progress ? (progress.done / 1e9 >= 10 ? Math.round(progress.done / 1e9) : (progress.done / 1e9).toFixed(1)) : 0, Math.round((progress?.total ?? 0) / 1e9)])}{progress && !progress.sameDrive ? timeLeft(progress.secondsLeft) : null}

{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}

@@ -224,7 +224,7 @@ function ResultDialog({ outcome, plan, native, onClose, onAgain }: { outcome: Na
; } return {tr('Done')}}> -
{tr('{0} now live in {1}', [gb(result.total ?? 0), plan?.shown ?? result.to ?? ''])} +
{(() => { const [before, after] = tr('{0} now live in {1}', [gb(result.total ?? 0), '@@']).split('@@'); return <>{before}{plan?.shown ?? result.to ?? ''}{after}; })()} {result.sameDrive ? null : <>
{tr('The old copies were removed and {0} is free again on {1}.', [gb(result.total ?? 0), driveOf(result.from ?? '')])}}
; } diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 7fead023..449d2b35 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3367,7 +3367,7 @@ "s8278": "Neuer Ordner", "s8279": "{0} frei auf diesem Laufwerk", "s8280": "Sie haben das ganze Laufwerk {0} gewählt. Strata legt seine Dateien in einem eigenen Ordner ab, Ihre Modelle liegen daher in {1}.", - "s8281": "Danach folgen die drei Möglichkeiten wie in Schritt 2.", + "s8281": "Als Nächstes folgen die drei Möglichkeiten.", "s8282": "Meine Modelle verschieben", "s8283": "Beide Ordner verwenden", "s8284": "Leer beginnen", diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 0f6eb0a6..fb3f94b3 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3367,7 +3367,7 @@ "s8278": "New folder", "s8279": "{0} free on this drive", "s8280": "You picked the whole drive {0}. Strata keeps its files in a folder of their own, so your models go in {1}.", - "s8281": "The three choices follow, as in step 2.", + "s8281": "The three choices come next.", "s8282": "Move my models", "s8283": "Use both folders", "s8284": "Start empty", diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index a0f3f33d..716bee35 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3367,7 +3367,7 @@ "s8278": "Carpeta nueva", "s8279": "{0} libres en esta unidad", "s8280": "Has elegido toda la unidad {0}. Strata guarda sus archivos en una carpeta propia, así que tus modelos irán en {1}.", - "s8281": "A continuación vienen las tres opciones, como en el paso 2.", + "s8281": "A continuación verás las tres opciones.", "s8282": "Mover mis modelos", "s8283": "Usar ambas carpetas", "s8284": "Empezar vacío", diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 3d3d0929..344db3ea 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3367,7 +3367,7 @@ "s8278": "新しいフォルダ", "s8279": "このドライブの空き: {0}", "s8280": "ドライブ全体 {0} を選びました。Strata は専用のフォルダにファイルを置くため、モデルは {1} に保存されます。", - "s8281": "次に、手順 2 と同じ 3 つの選択肢が表示されます。", + "s8281": "次に 3 つの選択肢が表示されます。", "s8282": "モデルを移動する", "s8283": "両方のフォルダを使う", "s8284": "空の状態で始める", diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 498dfb34..bbf5989b 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3367,7 +3367,7 @@ "s8278": "새 폴더", "s8279": "이 드라이브의 여유 공간: {0}", "s8280": "드라이브 전체 {0}을(를) 선택했습니다. Strata는 자체 폴더에 파일을 보관하므로 모델은 {1}에 저장됩니다.", - "s8281": "다음으로 2단계와 같은 세 가지 선택지가 나옵니다.", + "s8281": "다음으로 세 가지 선택지가 나옵니다.", "s8282": "내 모델 이동", "s8283": "두 폴더 모두 사용", "s8284": "빈 상태로 시작", diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 678d549f..cecc2f1a 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3367,7 +3367,7 @@ "s8278": "Pasta nova", "s8279": "{0} livres nesta unidade", "s8280": "Você escolheu a unidade inteira {0}. O Strata guarda seus arquivos em uma pasta própria, então seus modelos ficam em {1}.", - "s8281": "Em seguida vêm as três opções, como na etapa 2.", + "s8281": "Em seguida, você verá as três opções.", "s8282": "Mover meus modelos", "s8283": "Usar as duas pastas", "s8284": "Começar vazio", diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index da83fc83..670c0531 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3367,7 +3367,7 @@ "s8278": "Новая папка", "s8279": "Свободно на этом диске: {0}", "s8280": "Вы выбрали весь диск {0}. Strata хранит свои файлы в отдельной папке, поэтому модели будут в {1}.", - "s8281": "Дальше будут три варианта, как на шаге 2.", + "s8281": "Дальше будут три варианта.", "s8282": "Переместить мои модели", "s8283": "Использовать обе папки", "s8284": "Начать с пустой", diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 61e95aab..b670fc47 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3367,7 +3367,7 @@ "s8278": "新文件夹", "s8279": "此驱动器可用 {0}", "s8280": "你选择了整个驱动器 {0}。Strata 会把文件放在自己的文件夹里,因此你的模型将存放在 {1}。", - "s8281": "接下来会出现三个选项,与第 2 步相同。", + "s8281": "接下来会出现三个选项。", "s8282": "移动我的模型", "s8283": "同时使用两个文件夹", "s8284": "从空文件夹开始", diff --git a/apps/host/src/styles/annotation-fixes.css b/apps/host/src/styles/annotation-fixes.css index de133dc6..8d31cb62 100644 --- a/apps/host/src/styles/annotation-fixes.css +++ b/apps/host/src/styles/annotation-fixes.css @@ -768,3 +768,6 @@ html[data-motion='reduced'] .task-tree-row[data-leaving] { opacity: 0; } .models-details ul { margin:8px 0 0; padding-left:18px; color:var(--st-ink-soft); font-size:var(--st-fs-sm); } .models-ok { display:flex; align-items:center; gap:12px; } .models-ok__mark { display:grid; place-items:center; flex:none; width:44px; height:44px; border-radius:50%; background:var(--st-accent-tint); color:var(--st-accent-text); } +.models-dialog .dialog-body { display:grid; gap:14px; } +.models-path { font-family:var(--st-font-mono); font-size:12px; font-weight:400; background:var(--st-surface-2); padding:2px 6px; border-radius:6px; overflow-wrap:anywhere; } +.models-dialog .storage-directory__path { margin:0; } diff --git a/apps/host/tests/models-folder.test.mjs b/apps/host/tests/models-folder.test.mjs index cf950ec2..7ff268ed 100644 --- a/apps/host/tests/models-folder.test.mjs +++ b/apps/host/tests/models-folder.test.mjs @@ -159,3 +159,23 @@ test('a move needs the app: the Control command line is built from the plan and const failing = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async () => ({ code: 5, json: { ok: false, error: { code: 'disk_full', message: 'The drive ran out of space.', details: 'ENOSPC' }, moved: [] }, text: '', stderr: '' }) }); await assert.rejects(failing.moveModels('/o', '/n'), e => e.code === 'disk_full' && e.details === 'ENOSPC' && /ran out of space/.test(e.message)); }); + +test('the models folder strings exist in all 8 languages with the same placeholders', () => { + const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8')); + const en = read('en'); + const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8261 && Number(k.slice(1)) <= 8338); + assert.equal(ours.length, 78); + for (const lang of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { + const text = read(lang); + for (const key of ours) { + assert.ok(text[key], `${lang} ${key}`); + assert.deepEqual((text[key].match(/\{\d\}/g) ?? []).sort(), (en[key].match(/\{\d\}/g) ?? []).sort(), `${lang} ${key} placeholders`); + } + } + // every string the dialog shows through tr() is in the catalogue + const source = readFileSync(new URL('../src/components/ModelsFolderDialog.tsx', import.meta.url), 'utf8'); + const values = new Set(Object.values(en)); + for (const text of ['Models folder', 'Change folder', 'Move my models', 'Use both folders', 'Start empty', 'Stop moving', 'Your models are moved', 'Moving stopped']) { + assert.ok(source.includes(text) && values.has(text), text); + } +}); diff --git a/docs/INSTALL.md b/docs/INSTALL.md index d860d042..afb1e866 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -311,7 +311,9 @@ The model files are the only big part (70 to 190 GB). Put them where there is ro - **In the app:** the first screen shows the model folder with a button to change it, and Settings > Storage changes it later. Pick a folder you can save files in; a whole drive (`D:\`) becomes `D:\Strata`, which Strata makes and says so. - Models you already have in the old folder stay there and keep working; nothing is moved or deleted for you. + Change folder then asks what to do with your models: move them (copied file by file and checked before the old copies are removed; you can stop at any time), + keep them where they are and also use the new folder, or start empty (the old files are never deleted). From the Terminal the same move is + `strata models move NEW_FOLDER` (add `--plan` to see what it would do first). - **In the Terminal:** `strata launch --data-dir D:\Strata` once. The folder is remembered for the next `strata launch` and `strata models list`. Until you give it one, the Terminal uses the folder the app chose; the app keeps its own setting (Settings > Storage) and does not read the Terminal's. `--move-data` moves the models you already have into it; without it they stay where they diff --git a/strata_control/models_move.py b/strata_control/models_move.py index 36eb6fc2..e42a4b8d 100644 --- a/strata_control/models_move.py +++ b/strata_control/models_move.py @@ -102,6 +102,9 @@ def _near(path: Path) -> Path: def same_drive(a: Path, b: Path) -> bool: + """Both folders are on one volume (a move is then a rename). STRATA_MOVE_ALWAYS_COPY=1 copies anyway: for testing the copy path on one disk.""" + if os.environ.get("STRATA_MOVE_ALWAYS_COPY") == "1": + return False try: return os.stat(_near(a)).st_dev == os.stat(_near(b)).st_dev except OSError: From 72f66767ca6d3b306fb2d2e5037bb092c237caba Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:48:21 +0200 Subject: [PATCH 22/27] Test: the models-folder strings moved to s8339-s8416 when the locale merge renumbered them --- apps/host/tests/models-folder.test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/tests/models-folder.test.mjs b/apps/host/tests/models-folder.test.mjs index 7ff268ed..ef2769bc 100644 --- a/apps/host/tests/models-folder.test.mjs +++ b/apps/host/tests/models-folder.test.mjs @@ -163,7 +163,7 @@ test('a move needs the app: the Control command line is built from the plan and test('the models folder strings exist in all 8 languages with the same placeholders', () => { const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8')); const en = read('en'); - const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8261 && Number(k.slice(1)) <= 8338); + const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8339 && Number(k.slice(1)) <= 8416); assert.equal(ours.length, 78); for (const lang of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { const text = read(lang); From 0a35538b745a705977dab712259e6aea997f4b20 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:53:14 +0200 Subject: [PATCH 23/27] Models move: remember an unfinished move in the old folder; strata models move --resume/--leave/--status; one-line notice at strata launch --- strata_cli/cli.py | 55 +++++++++++- strata_cli/launch/cmd.py | 13 +++ strata_control/models_move.py | 119 +++++++++++++++++++++++--- tests/terminal/test_models_move.py | 129 +++++++++++++++++++++++++++-- 4 files changed, 296 insertions(+), 20 deletions(-) diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 94863cb0..97b8554a 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -160,7 +160,10 @@ def parser() -> argparse.ArgumentParser: help="inspect only; adoption requires a qualified model workflow") models_import.add_argument("--output", choices=("human", "json"), default="human") models_move = models_sp.add_parser("move", help="move the model files (models, packs, mtp) to another folder: copied, checked, then the old copies removed") - models_move.add_argument("to", metavar="NEW_FOLDER") + models_move.add_argument("to", metavar="NEW_FOLDER", nargs="?", help="not needed with --resume, --leave or --status") + models_move.add_argument("--resume", action="store_true", help="finish a move that was interrupted") + models_move.add_argument("--leave", action="store_true", help="give up an interrupted move: keep the old folder and remove the partial copies") + models_move.add_argument("--status", action="store_true", help="say whether a move was interrupted (changes nothing)") models_move.add_argument("--from", dest="source", metavar="OLD_FOLDER", help="the folder the models are in now (default: the data folder in use)") models_move.add_argument("--install-dir", help="absolute path to a Strata installation whose run configs should follow the files") models_move.add_argument("--plan", action="store_true", help="say what would happen and change nothing") @@ -613,6 +616,11 @@ def _models_move(a: argparse.Namespace) -> int: from strata_control import discovery, models, models_move as mm machine = a.output in ("json", "jsonl") old = Path(a.source) if a.source else discovery.data_dir(Path.home() / "Strata")[0] + if a.status or a.resume or a.leave: + return _models_move_unfinished(a, old) + if not a.to: + print("strata: name the new folder, or use --resume / --leave / --status for an interrupted move.", file=sys.stderr) + return 2 new = Path(a.to).expanduser() if a.plan: result = mm.plan(old, new) @@ -650,6 +658,51 @@ def _models_move(a: argparse.Namespace) -> int: return 0 if summary["done"] else 6 +def _interrupted_words(st: dict) -> str: + return (f"A move of your models was interrupted. They are in {st['from']} and {st['to']}. " + "Finish it: strata models move --resume. Leave it (keep the models in the first folder): strata models move --leave.") + + +def _models_move_unfinished(a: argparse.Namespace, old: Path) -> int: + """`strata models move --status | --resume | --leave`: the move the last run left unfinished (A move was interrupted. Finish it or leave it).""" + from strata_control import models, models_move as mm + machine = a.output in ("json", "jsonl") + st = mm.interrupted(old) + if a.status: + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "interrupted": st}, ensure_ascii=False, allow_nan=False)) + else: + print(_interrupted_words(st) if st else "No move was interrupted.") + return 0 + if not st: + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": "nothing", "message": "No move was interrupted.", "details": ""}})) + else: + print("strata: no move was interrupted.", file=sys.stderr) + return 5 + try: + installs = [models.resolve_install(a.install_dir)[0]] if a.install_dir else [p for p, _s in models.all_installs()] + except Exception: + installs = [] + configs = [c for i in installs for c in mm.config_files(i)] + if a.leave: + try: + result = mm.leave(Path(st["from"]), Path(st["to"]), configs=configs) + except mm.MoveError as e: + if machine: + print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": e.code, "message": str(e), "details": e.details}}, ensure_ascii=False)) + else: + print(f"strata: {e} {e.details}".rstrip(), file=sys.stderr) + return 5 + if machine: + print(json.dumps({"schema_version": 1, "ok": True, "event": "result", "left": True, **result}, ensure_ascii=False)) + else: + print(f"Done. Your models stay in {st['from']}; the partial copies in {st['to']} were removed.") + return 0 + a.to, a.source, a.resume, a.status, a.leave = st["to"], st["from"], False, False, False + return _models_move(a) + + def _import_words(plan: dict) -> str: """The plain-words result of `strata models import --plan`: what the files are, what is already set up, what changes (nothing).""" cand = plan.get("candidate_selection") or {} diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 62807cf7..bd401cd3 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -317,6 +317,17 @@ def _say(line: str = "") -> None: sys.stdout.flush() +def _interrupted_move_notice() -> None: + """One line when a move of the models folder was left unfinished (never blocks the launch).""" + try: + from strata_control import discovery, models_move + st = models_move.interrupted(discovery.data_dir(Path.home() / "Strata")[0]) + except Exception: + return + if st: + _say("A move of your models was interrupted. Finish it with `strata models move --resume`, or keep them where they are with `strata models move --leave`.") + + def _printer(quiet: bool = False): """An emit callback that prints readable lines: new text once, progress in steps of 10% when not on a terminal.""" state = {"last": None, "pct": -10, "stage": None} @@ -547,6 +558,8 @@ def run_launch(a: argparse.Namespace) -> int: if a.model or a.model_path: return fail(str(e), 5) s, notices = settings_from_args(a, catalog) + if not machine: + _interrupted_move_notice() have_choices = bool(a.preset or a.model or a.model_path or a.context or a.vision or a.parallel or a.access or a.tune) interactive = sys.stdin.isatty() and sys.stdout.isatty() and not a.no_tui and not machine and not a.plan plain_questions = False diff --git a/strata_control/models_move.py b/strata_control/models_move.py index e42a4b8d..8929ab9b 100644 --- a/strata_control/models_move.py +++ b/strata_control/models_move.py @@ -272,12 +272,6 @@ def _read_state(new: Path) -> dict: return {} -def interrupted(data: Path) -> dict | None: - """The unfinished move recorded in a data folder (``models-move.json``), for 'A move was interrupted'.""" - st = _read_state(data) - return st if st.get("state") == "running" else None - - def _write_state(new: Path, **fields) -> None: try: tmp = new / (STATE_FILE + ".tmp") @@ -287,6 +281,50 @@ def _write_state(new: Path, **fields) -> None: pass +def _save_state(old: Path, new: Path, **fields) -> None: + """The state goes in the new folder and, as a pointer, in the old one: the old folder stays the data folder until the move is done, + so that is where the next start looks.""" + _write_state(new, **fields) + _write_state(old, **fields) + + +def _clear_state(*folders: Path) -> None: + for f in folders: + _quiet_remove(Path(f) / STATE_FILE) + + +def _same_path(a, b) -> bool: + try: + return _same(Path(a), Path(b)) + except (OSError, ValueError, TypeError): + return False + + +def interrupted(data: Path) -> dict | None: + """The unfinished move recorded in the data folder (``models-move.json``), for 'A move was interrupted. Finish it or leave it'. + + A move that is running right now (its process is alive) is not interrupted. A stopped or failed move that left files in both folders is. + Returns ``{state, from, to, bytes}`` or None. + """ + data = Path(data) + st = _read_state(data) + if st.get("state") not in ("running", "stopped", "failed") or not st.get("from") or not st.get("to"): + return None + if not _same_path(st["from"], data): # a pointer left in some other folder is not ours + return None + if not Path(st["from"]).is_dir(): + return None + pid, token = st.get("pid"), st.get("token") + if st["state"] == "running" and isinstance(pid, int) and token and pid != os.getpid(): + try: + from strata_control import procs + if procs.start_token(pid) == token: + return None + except Exception: + pass + return st + + def repoint_config(cfg_file: Path, old: Path, new: Path) -> bool: """A run config whose model files moved from ``old`` to ``new`` names them there (each path only when its file is now there and no longer at the old place). Same rule as setup.py repoint_config. Returns whether the file changed.""" @@ -366,8 +404,17 @@ def move(old: Path, new: Path, *, on_progress: Callable[[dict], None] | None = N todo[e.group].append(e) left = {g: len(v) for g, v in todo.items()} moved_groups: list[str] = [] - state = {"state": "running", "from": str(old), "to": str(new), "started": now(), "bytes": total} - _write_state(new, **state) + before = _read_state(old) + if not (_same_path(before.get("from", ""), old) and _same_path(before.get("to", ""), new)): + before = {} + try: + from strata_control import procs + token = procs.start_token(os.getpid()) + except Exception: + token = None + state = {"state": "running", "from": str(old), "to": str(new), "started": now(), "bytes": total, "pid": os.getpid(), "token": token, + "files": sorted({e.rel for e in entries} | set(before.get("files") or []))} + _save_state(old, new, **state) done_bytes = 0 files_moved = 0 last_emit = [0.0] @@ -459,22 +506,68 @@ def move(old: Path, new: Path, *, on_progress: Callable[[dict], None] | None = N repoint() repoint() state.update(state="done", finished=now()) - _write_state(new, **state) - _quiet_remove(new / STATE_FILE) + _clear_state(old, new) return {"done": True, "stopped": False, "moved": moved_groups, "remaining": [], "bytes_moved": done_bytes, "total_bytes": total, "files_moved": files_moved, "same_drive": same} except Stopped: repoint() state.update(state="stopped") - _write_state(new, **state) - _quiet_remove(new / STATE_FILE) if not moved_groups and not files_moved else None + if files_moved: + _save_state(old, new, **state) + else: + _clear_state(old, new) remaining = [g for g, n in left.items() if n > 0] return {"done": False, "stopped": True, "moved": moved_groups, "remaining": remaining, "bytes_moved": done_bytes, "total_bytes": total, "files_moved": files_moved, "same_drive": same} except MoveError as err: repoint() state.update(state="failed", error=err.code) - _write_state(new, **state) + if files_moved: + _save_state(old, new, **state) + else: + _clear_state(old, new) err.summary = {"moved": moved_groups, "remaining": [g for g, n in left.items() if n > 0], "bytes_moved": done_bytes, "total_bytes": total, "files_moved": files_moved} raise + + +def leave(old: Path, new: Path, *, configs: list[Path] | None = None) -> dict: + """'Leave it': give up an unfinished move and keep the old folder as the complete one. + + Only the files the move itself listed are touched. A copy in the new folder whose original is still in the old one is removed; a file + that exists only in the new folder (its original went after a checked copy) is put back in the old folder, so nothing is lost. + ``.part`` files are removed and the run configs point at the old folder again. Returns ``{removed, restored, bytes_removed}``. + """ + old, new = Path(old), Path(new) + st = _read_state(old) or _read_state(new) + rels = [r for r in (st.get("files") or []) if isinstance(r, str) and r and ".." not in Path(r).parts and not Path(r).is_absolute()] + removed = restored = bytes_removed = 0 + for rel in rels: + src, dst = old / rel, new / rel + _quiet_remove(Path(str(dst) + ".part")) + if not dst.exists(): + continue + try: + size = dst.stat().st_size + if src.exists(): + os.remove(dst) + removed += 1 + bytes_removed += size + else: + src.parent.mkdir(parents=True, exist_ok=True) + if same_drive(old, new): + os.replace(dst, src) + else: + _copy_verified(dst, src, size, lambda: False, lambda n: None) + os.remove(dst) + restored += 1 + except OSError as e: + raise MoveError("io", f"Strata could not clean up {dst.name}.", f"{type(e).__name__}: {e}") from e + _prune(dst.parent, new) + for cfg in (configs or []): + try: + repoint_config(cfg, new, old) + except OSError: + pass + _clear_state(old, new) + return {"removed": removed, "restored": restored, "bytes_removed": bytes_removed} diff --git a/tests/terminal/test_models_move.py b/tests/terminal/test_models_move.py index 80a1408b..b11fec0b 100644 --- a/tests/terminal/test_models_move.py +++ b/tests/terminal/test_models_move.py @@ -52,6 +52,22 @@ class MoveCase(unittest.TestCase): """Another drive: the files are copied, whatever this machine's volumes are.""" return mock.patch.object(mm, "same_drive", return_value=False) + def break_after(self, n): + """A copy that works n times, then fails: a move cut off part way.""" + real, calls = mm._copy_verified, [0] + + def flaky(*args, **kw): + calls[0] += 1 + if calls[0] > n: + raise mm.MoveError("io", "cut off") + return real(*args, **kw) + return mock.patch.object(mm, "_copy_verified", side_effect=flaky) + + def cut_off(self, n=1): + with self.copy_mode(), self.break_after(n): + with self.assertRaises(mm.MoveError): + self.run_move() + def run_move(self, **kw): events = [] summary = mm.move(self.old, self.new, on_progress=events.append, configs=[self.config], **kw) @@ -222,13 +238,68 @@ class MoveTests(MoveCase): self.check_whole() def test_an_interrupted_move_is_remembered(self): + self.cut_off(1) + st = mm.interrupted(self.old) # the old folder is still the data folder: it holds the pointer + self.assertEqual(st["to"], str(self.new)) + self.assertEqual(st["state"], "failed") + self.assertEqual(mm.interrupted(self.base / "elsewhere"), None) + mm._write_state(self.old, state="running", pid=os.getpid() + 7, token=None, **{"from": str(self.old), "to": str(self.new)}) + self.assertEqual(mm.interrupted(self.old)["state"], "running") + + def test_a_move_that_is_running_now_is_not_interrupted(self): + from strata_control import procs + mm._write_state(self.old, state="running", pid=os.getpid() + 7, token="t", **{"from": str(self.old), "to": str(self.new)}) + with mock.patch.object(procs, "start_token", return_value="t"): + self.assertIsNone(mm.interrupted(self.old)) + with mock.patch.object(procs, "start_token", return_value=None): + self.assertIsNotNone(mm.interrupted(self.old)) + + def test_nothing_moved_leaves_nothing_to_ask_about(self): + self.cut_off(0) + self.assertIsNone(mm.interrupted(self.old)) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + + def test_finish_resumes_the_move(self): + self.cut_off(1) + st = mm.interrupted(self.old) with self.copy_mode(): - with self.assertRaises(mm.MoveError): - with mock.patch.object(mm, "_copy_verified", side_effect=mm.MoveError("io", "x")): - self.run_move() - self.assertEqual(mm.interrupted(self.new), None) # failed is not "running" - mm._write_state(self.new, state="running", **{"from": str(self.old), "to": str(self.new)}) - self.assertEqual(mm.interrupted(self.new)["from"], str(self.old)) + summary = mm.move(Path(st["from"]), Path(st["to"]), configs=[self.config]) + self.assertTrue(summary["done"]) + self.check_whole() + self.assertIsNone(mm.interrupted(self.old)) + self.assertFalse((self.old / mm.STATE_FILE).exists() or (self.new / mm.STATE_FILE).exists()) + + def test_leave_keeps_the_old_folder_complete(self): + self.cut_off(1) + (self.new / "models/stray.gguf.part").write_bytes(b"x") # not listed by the move, but a .part of ours is + (self.new / "models/gyro-s").mkdir(parents=True, exist_ok=True) + (self.new / "models/gyro-s/a.gguf.part").write_bytes(b"cut") + theirs = self.new / "models/own/mine.gguf" # a file of the person's, not part of the move + theirs.parent.mkdir(parents=True) + theirs.write_bytes(b"mine") + st = mm.interrupted(self.old) + with self.copy_mode(): + result = mm.leave(Path(st["from"]), Path(st["to"]), configs=[self.config]) + self.assertGreaterEqual(result["restored"] + result["removed"], 1) + for rel, data in self.files.items(): + self.assertEqual((self.old / rel).read_bytes(), data, rel) + self.assertFalse((self.new / rel).exists(), rel) + self.assertEqual(list(self.new.rglob("*.part")), [(self.new / "models/stray.gguf.part")]) + self.assertTrue(theirs.exists()) + self.assertIsNone(mm.interrupted(self.old)) + self.assertFalse((self.new / mm.STATE_FILE).exists()) + cfg = json.loads(self.config.read_text()) + self.assertTrue(all(str(self.new) not in str(v) for v in cfg.values())) + self.assertIn(str(self.old / "models/gyro-s/a.gguf"), cfg["args"]) + + def test_leave_after_a_crash_removes_the_duplicate(self): + self.cut_off(1) + dup = self.new / "models/coder/c.gguf" # copied and renamed, original not yet removed + dup.parent.mkdir(parents=True, exist_ok=True) + dup.write_bytes(self.files["models/coder/c.gguf"]) + mm.leave(self.old, self.new) + self.assertFalse(dup.exists()) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) def test_configs_are_rewritten_only_for_files_that_are_there(self): self.config.write_text(json.dumps({"args": ["--native", str(self.old / "models/gone.gguf")]})) @@ -265,6 +336,52 @@ class CommandLineTests(MoveCase): self.assertTrue(lines[-1]["done"]) self.assertTrue((self.new / "models/coder/c.gguf").exists()) + def run_cli(self, *argv): + from strata_cli import cli + from strata_control import discovery + import contextlib + import io + out = io.StringIO() + with contextlib.redirect_stdout(out), self.copy_mode(), mock.patch.object(discovery, "data_dir", return_value=(self.old, "settings")): + code = cli.main(["models", "move", *argv]) + return code, out.getvalue() + + def test_status_resume_and_leave(self): + code, text = self.run_cli("--status", "--output", "json") + self.assertEqual((code, json.loads(text)["interrupted"]), (0, None)) + self.assertEqual(self.run_cli("--resume", "--output", "json")[0], 5) + self.cut_off(1) + code, text = self.run_cli("--status", "--output", "json") + self.assertEqual(json.loads(text)["interrupted"]["to"], str(self.new)) + self.assertIn("--resume", self.run_cli("--status")[1]) + code, text = self.run_cli("--leave", "--install-dir", str(self.install), "--output", "json") + self.assertEqual(code, 0, text) + self.assertTrue((self.old / "models/coder/c.gguf").exists()) + self.cut_off(1) + code, text = self.run_cli("--resume", "--install-dir", str(self.install), "--output", "jsonl") + self.assertEqual(code, 0, text) + self.assertTrue([json.loads(l) for l in text.splitlines() if l.startswith("{")][-1]["done"]) + self.assertTrue((self.new / "models/coder/c.gguf").exists()) + self.assertFalse((self.old / "models/coder/c.gguf").exists()) + + def test_launch_says_it_in_one_line(self): + from strata_cli.launch import cmd + from strata_control import discovery + import contextlib + import io + self.cut_off(1) + with mock.patch.object(discovery, "data_dir", return_value=(self.old, "settings")): + out = io.StringIO() + with contextlib.redirect_stdout(out): + cmd._interrupted_move_notice() + self.assertEqual(len(out.getvalue().strip().splitlines()), 1) + self.assertIn("models move --resume", out.getvalue()) + mm.leave(self.old, self.new) + out = io.StringIO() + with contextlib.redirect_stdout(out): + cmd._interrupted_move_notice() + self.assertEqual(out.getvalue(), "") + def test_the_cancel_file_stops_the_run(self): from strata_cli import cli import contextlib From 6c688faf227734c937f545f71d248c4c67081dc9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:57:27 +0200 Subject: [PATCH 24/27] Models folder: Finish or leave an interrupted move from the Storage card (host routes, card notice, 6 strings in 8 languages) --- apps/host/server/control-runtime.mjs | 20 ++++++++ apps/host/server/index.mjs | 3 ++ apps/host/server/native-control.mjs | 31 +++++++++++- .../src/components/ModelsFolderDialog.tsx | 49 +++++++++++++++++-- apps/host/src/locales/de.json | 8 ++- apps/host/src/locales/en.json | 8 ++- apps/host/src/locales/es.json | 8 ++- apps/host/src/locales/ja.json | 8 ++- apps/host/src/locales/ko.json | 8 ++- apps/host/src/locales/pt.json | 8 ++- apps/host/src/locales/ru.json | 8 ++- apps/host/src/locales/zh.json | 8 ++- apps/host/tests/models-folder.test.mjs | 47 ++++++++++++++++-- 13 files changed, 198 insertions(+), 16 deletions(-) diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index 0447572d..3e02f8b1 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -224,6 +224,26 @@ export function createControl({ control = findControl(), env = process.env, run const error = result.json?.error; throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' }); }, + /** A move of the models folder that the last run left unfinished (`strata models move --status`): null, or {state, from, to, bytes}. */ + async interruptedModelsMove(dataFolder) { + const result = await call(['models', 'move', '--status', ...(dataFolder ? ['--from', dataFolder] : []), '--output', 'json'], { timeoutMs: 30_000 }); + if (result.json?.ok) return result.json.interrupted ?? null; + throw failure(result, 'The models folder could not be checked.'); + }, + /** "Finish it": the same move again, from where it stopped. Same events and result as moveModels. */ + async resumeModelsMove(dataFolder, { installDir = null, cancelFile = null, onEvent = null } = {}) { + const args = ['models', 'move', '--resume', ...(dataFolder ? ['--from', dataFolder] : []), ...(installDir ? ['--install-dir', installDir] : []), ...(cancelFile ? ['--cancel-file', cancelFile] : []), '--output', 'jsonl']; + const result = await call(args, { timeoutMs: 24 * 3600_000, onLine: onEvent ?? (() => {}) }); + if (result.json?.ok && result.json.event === 'result') return result.json; + const error = result.json?.error; + throw Object.assign(new ControlError(error?.message ?? (result.stderr.split(/\r?\n/).filter(Boolean).pop() || 'The models could not be moved.'), { exitCode: result.code, output: result.json }), { code: error?.code ?? 'move_failed', details: error?.details ?? '' }); + }, + /** "Leave it": keep the old folder, remove the partial copies in the new one. */ + async leaveModelsMove(dataFolder, { installDir = null } = {}) { + const result = await call(['models', 'move', '--leave', ...(dataFolder ? ['--from', dataFolder] : []), ...(installDir ? ['--install-dir', installDir] : []), '--output', 'json'], { timeoutMs: 24 * 3600_000 }); + if (result.json?.ok) return result.json; + throw Object.assign(failure(result, 'The partial copies could not be removed.'), { code: result.json?.error?.code ?? 'leave_failed', details: result.json?.error?.details ?? '' }); + }, async saveProfile(name, configPath) { const listed = await call(['profile', 'list', '--output', 'json'], { timeoutMs: 20_000 }); const known = (listed.json?.profiles ?? []).some(p => p.id === name); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index eb454cb4..f8d638ad 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -974,6 +974,9 @@ async function api(req, res, path, method, url) { if(picked.cancelled)return json(res,200,{cancelled:true}); return json(res,200,{plan:await native.planModelsFolder(picked.path)});} if(path==='/api/native/models-folder/start'&&method==='POST'){const body=await readBody(req);const result=await native.startModelsFolder({folder:body.path,choice:body.choice,stopRunning:body.stopRunning===true});return json(res,result.id?202:200,result);} + if(path==='/api/native/models-folder/interrupted'&&method==='GET')return json(res,200,{interrupted:await native.interruptedMove()}); + if(path==='/api/native/models-folder/resume'&&method==='POST'){const body=await readBody(req);return json(res,202,await native.finishInterruptedMove({stopRunning:body.stopRunning===true}));} + if(path==='/api/native/models-folder/leave'&&method==='POST')return json(res,200,await native.leaveInterruptedMove()); if(path==='/api/native/plan'&&method==='POST')return json(res,200,await native.plan(await readBody(req))); if(path==='/api/native/operations'&&method==='POST'){if(storageChanging)return error(res,409,'Wait for the model folder check to finish.');const body=await readBody(req);return json(res,202,native.operation(body.kind,body.args));} if(path==='/api/native/logs'&&method==='GET')return json(res,200,{logs:native.logs()}); diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 75f7c0ce..7ec4a440 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -424,11 +424,15 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} setDownloadDirectory(target);lastRead=0;await refresh(true); return {done:true,choice,folder:target,oldFolder:old,setAside:aside}; } + return runModelsMove(old,target,(from,to,options)=>control.moveModels(from,to,options)); + } + /* The move as a job (the progress dialog reads it). `run` is moveModels for a new move, resumeModelsMove for "Finish it". */ + function runModelsMove(old,target,run){ rmSync(moveFile(),{force:true}); return begin('models-move',async job=>{ job.cancelFile=moveFile();job.summary='Starting…'; try{ - const result=await control.moveModels(old,target,{installDir:repo(),cancelFile:moveFile(),onEvent:event=>{ + const result=await run(old,target,{installDir:repo(),cancelFile:moveFile(),onEvent:event=>{ if(event.event!=='progress')return; job.progress={done:event.done,total:event.total,file:event.file,group:event.group,index:event.index,count:event.count,secondsLeft:event.seconds_left||0,sameDrive:!!event.same_drive}; job.summary=`${Math.round(event.done/1e8)/10} of ${Math.round(event.total/1e8)/10} GB`;emit();}}); @@ -445,10 +449,33 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} }finally{rmSync(moveFile(),{force:true});} },{family:undefined}); } + /* "A move was interrupted. Finish it or leave it": the next start finds the unfinished move (Control keeps a note in the models folder in use). */ + async function interruptedMove(){ + if(!packaged)return null; + const now=currentModelsFolder();if(!now)return null; + if([...jobs.values()].some(j=>j.kind==='models-move'&&j.state==='running'))return null; + try{return await control.interruptedModelsMove(now);}catch{return null;} + } + async function finishInterruptedMove({stopRunning=false}={}){ + const st=await interruptedMove();if(!st)throw new Error('No move was interrupted.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + if(instances.size){ + if(!stopRunning)throw Object.assign(new Error('A model is running. Stop it first, then change the folder.'),{code:'running'}); + for(const id of [...instances.keys()])await unload(id); + } + return runModelsMove(st.from,st.to,(from,to,options)=>control.resumeModelsMove(from,options)); + } + async function leaveInterruptedMove(){ + const st=await interruptedMove();if(!st)throw new Error('No move was interrupted.'); + if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or stop the download to change the folder.'); + const result=await control.leaveModelsMove(st.from,{installDir:repo()}); + lastRead=0;await refresh(true); + return {done:true,folder:st.from,partial:st.to,removed:result.removed??0,restored:result.restored??0}; + } async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.kind==='models-move'){/* a safe stop: the copy in flight is dropped, files already moved stay */try{writeFileSync(job.cancelFile,'stop');}catch{/* the run ends anyway */}job.summary='Stopping…';emit();return state();}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. const publicState=()=>{const value=state();value.jobs=value.jobs.map(({process,engineAbort,rawResult,...job})=>job);return value;}; async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} - return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; + return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,interruptedMove,finishInterruptedMove,leaveInterruptedMove,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),close}; } diff --git a/apps/host/src/components/ModelsFolderDialog.tsx b/apps/host/src/components/ModelsFolderDialog.tsx index 8d9ba884..4111effe 100644 --- a/apps/host/src/components/ModelsFolderDialog.tsx +++ b/apps/host/src/components/ModelsFolderDialog.tsx @@ -54,6 +54,8 @@ export function ModelsFolderCard({ blocked }: { blocked: boolean }) { const [outcome, setOutcome] = useState<{ job: NativeJob } | null>(null); const [notice, setNotice] = useState(''); const [stopping, setStopping] = useState(false); + const [unfinished, setUnfinished] = useState<{ from: string; to: string } | null>(null); + const [resumed, setResumed] = useState<{ from: string; to: string } | null>(null); const folder = native?.downloadDirectory ?? ''; const free = native?.downloadFreeBytes ?? null; const usage = native?.installed?.usage?.total_bytes ?? 0; @@ -64,6 +66,41 @@ export function ModelsFolderCard({ blocked }: { blocked: boolean }) { const used = free !== null && total ? Math.min(100, Math.max(1, ((total - free) / total) * 100)) : 0; useEffect(() => { if (moving && !jobId) setJobId(moving.id); }, [moving, jobId]); + /* A move that a crash or a stop left half done: found again at the next start, with its two choices. */ + useEffect(() => { + if (moving || outcome) return; + let live = true; + api.get<{ interrupted: { from: string; to: string } | null }>('/api/native/models-folder/interrupted') + .then(r => { if (live) setUnfinished(r.interrupted); }).catch(() => { if (live) setUnfinished(null); }); + return () => { live = false; }; + }, [moving, outcome, folder]); + async function finishMove() { + if (!unfinished) return; + setPending(true); + setError(null); + try { + const result = await api.post('/api/native/models-folder/resume', { stopRunning: true }); + setResumed(unfinished); + setUnfinished(null); + if (result.id) { setJobId(result.id); setOutcome(null); await refreshNative(true); } + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + async function leaveMove() { + if (!unfinished) return; + setPending(true); + setError(null); + try { + await api.post('/api/native/models-folder/leave', {}); + setNotice(tr('The partial copies were removed. Your models are in {0}.', [unfinished.from])); + setUnfinished(null); + await refreshNative(true); + } + catch (e) { setError({ message: (e as Error).message, details: ((e as ApiError).body as { details?: string } | undefined)?.details }); } + finally { setPending(false); } + } + function leave() { setPlan(null); setStage(null); setError(null); setTyping(false); } async function pick(path = '') { setPending(true); @@ -106,7 +143,7 @@ export function ModelsFolderCard({ blocked }: { blocked: boolean }) { try { await nativeAction(`operations/${moving.id}/cancel`); } catch (e) { setError({ message: (e as Error).message }); } } - function closeResult() { setOutcome(null); setJobId(null); leave(); setNotice(''); } + function closeResult() { setOutcome(null); setJobId(null); setResumed(null); leave(); setNotice(''); } const progress = moving?.progress as { done: number; total: number; file: string; group: string; index: number; count: number; secondsLeft: number; sameDrive: boolean } | null | undefined; const percent = progress && progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0; @@ -125,6 +162,12 @@ export function ModelsFolderCard({ blocked }: { blocked: boolean }) { setTyped(e.target.value)} placeholder={tr('Full path to an existing folder')} spellCheck={false} autoFocus/>
{tr('Use this directory')}
: null} + {unfinished && !moving ?
+ {tr('A move was interrupted. Finish it or leave it.')}
+ {tr('Strata was moving your models from {0} to {1} when it stopped. Nothing is lost.', [unfinished.from, unfinished.to])} +

{tr('Finishing puts all your models in {1}. Leaving it keeps them in {0} and removes the partial copies from {1}.', [unfinished.from, unfinished.to])}

+
void finishMove()}>{tr('Finish the move')} void leaveMove()}>{tr('Leave it')}
+
: null} {notice ?

{notice}

: null} {error && !stage ? : null} @@ -155,7 +198,7 @@ export function ModelsFolderCard({ blocked }: { blocked: boolean }) {

{tr('Keep Strata open. You can keep using other apps. Your models cannot be loaded until the move is done.')}

{progress ?
{tr('Details')}
  • {tr('Now copying: {0}, file {1} of {2}', [modelName(progress.group, native) ?? progress.group, progress.index, progress.count])}
  • -
  • {tr('From {0} to {1}', [savedPlan?.current ?? '', savedPlan?.folder ?? ''])}
: null} +
  • {tr('From {0} to {1}', [savedPlan?.current ?? resumed?.from ?? '', savedPlan?.folder ?? resumed?.to ?? ''])}
  • : null}
    { closeResult(); void pick(); }}/> @@ -199,7 +242,7 @@ function ChooseBody({ plan, choice, setChoice, names, error }: { plan: Plan; cho function ResultDialog({ outcome, plan, native, onClose, onAgain }: { outcome: NativeJob | null; plan: Plan | null; native: NativeState | null; onClose: () => void; onAgain: () => void }) { if (!outcome) return null; const result = (outcome.result ?? {}) as Outcome; - const sized = (groups: string[]) => list(groups.map(g => { const m = plan?.models.find(x => x.group === g); const name = modelName(g, native); return name ? `${name} (${gb(m?.bytes ?? 0)})` : null; }).filter((x): x is string => !!x)); + const sized = (groups: string[]) => list(groups.map(g => { const m = plan?.models.find(x => x.group === g); const name = modelName(g, native); return name ? (m ? `${name} (${gb(m.bytes)})` : name) : null; }).filter((x): x is string => !!x)); if (outcome.state === 'error') { const full = result.code === 'disk_full'; const where = driveOf(result.to ?? ''); diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 09f83294..8b0b25ca 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3437,5 +3437,11 @@ "s8413": "Ein Modell läuft. Stoppen Sie es zuerst und ändern Sie dann den Ordner.", "s8414": "Wählen Sie einen Modellordner.", "s8415": "Wählen Sie, was mit Ihren Modellen geschehen soll.", - "s8416": "Diese Möglichkeit gibt es hier nicht." + "s8416": "Diese Möglichkeit gibt es hier nicht.", + "s8417": "Ein Verschieben wurde unterbrochen. Beenden Sie es oder lassen Sie es sein.", + "s8418": "Strata hat Ihre Modelle von {0} nach {1} verschoben, als es angehalten wurde. Es ist nichts verloren.", + "s8419": "Verschieben beenden", + "s8420": "Belassen", + "s8421": "Beenden legt alle Ihre Modelle in {1} ab. Belassen lässt sie in {0} und entfernt die unvollständigen Kopien aus {1}.", + "s8422": "Die unvollständigen Kopien wurden entfernt. Ihre Modelle liegen in {0}." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 59b543fe..2f0c9903 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3437,5 +3437,11 @@ "s8413": "A model is running. Stop it first, then change the folder.", "s8414": "Choose a models folder.", "s8415": "Choose what to do with your models.", - "s8416": "That choice is not possible here." + "s8416": "That choice is not possible here.", + "s8417": "A move was interrupted. Finish it or leave it.", + "s8418": "Strata was moving your models from {0} to {1} when it stopped. Nothing is lost.", + "s8419": "Finish the move", + "s8420": "Leave it", + "s8421": "Finishing puts all your models in {1}. Leaving it keeps them in {0} and removes the partial copies from {1}.", + "s8422": "The partial copies were removed. Your models are in {0}." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index ff46ecd4..af4f2cd7 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3437,5 +3437,11 @@ "s8413": "Hay un modelo en ejecución. Deténlo primero y después cambia la carpeta.", "s8414": "Elige una carpeta de modelos.", "s8415": "Elige qué hacer con tus modelos.", - "s8416": "Esa opción no es posible aquí." + "s8416": "Esa opción no es posible aquí.", + "s8417": "Se interrumpió un traslado. Termínelo o déjelo como estaba.", + "s8418": "Strata estaba trasladando sus modelos de {0} a {1} cuando se detuvo. No se ha perdido nada.", + "s8419": "Terminar el traslado", + "s8420": "Dejarlo", + "s8421": "Terminar pone todos sus modelos en {1}. Dejarlo los mantiene en {0} y elimina las copias parciales de {1}.", + "s8422": "Se eliminaron las copias parciales. Sus modelos están en {0}." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index adc21135..1b29a58b 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3437,5 +3437,11 @@ "s8413": "モデルが実行中です。先に停止してから、フォルダを変更してください。", "s8414": "モデルフォルダを選んでください。", "s8415": "モデルをどうするか選んでください。", - "s8416": "この選択肢はここでは使えません。" + "s8416": "この選択肢はここでは使えません。", + "s8417": "移動が中断されました。完了するか、中止してください。", + "s8418": "Strata がモデルを {0} から {1} へ移動している途中で止まりました。失われたものはありません。", + "s8419": "移動を完了する", + "s8420": "中止する", + "s8421": "完了すると、すべてのモデルが {1} に入ります。中止すると、モデルは {0} に残り、{1} の不完全なコピーが削除されます。", + "s8422": "不完全なコピーを削除しました。モデルは {0} にあります。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index 77bd09ad..4d6f8410 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3437,5 +3437,11 @@ "s8413": "모델이 실행 중입니다. 먼저 중지한 뒤 폴더를 변경하세요.", "s8414": "모델 폴더를 선택하세요.", "s8415": "모델을 어떻게 할지 선택하세요.", - "s8416": "여기서는 해당 선택지를 사용할 수 없습니다." + "s8416": "여기서는 해당 선택지를 사용할 수 없습니다.", + "s8417": "이동이 중단되었습니다. 마무리하거나 그대로 두세요.", + "s8418": "Strata가 모델을 {0}에서 {1}(으)로 옮기던 중 멈췄습니다. 잃어버린 것은 없습니다.", + "s8419": "이동 마무리", + "s8420": "그대로 두기", + "s8421": "마무리하면 모든 모델이 {1}에 들어갑니다. 그대로 두면 모델은 {0}에 남고 {1}의 불완전한 복사본이 삭제됩니다.", + "s8422": "불완전한 복사본을 삭제했습니다. 모델은 {0}에 있습니다." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 91ba5cb1..181b6494 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3437,5 +3437,11 @@ "s8413": "Há um modelo em execução. Pare-o primeiro e depois altere a pasta.", "s8414": "Escolha uma pasta de modelos.", "s8415": "Escolha o que fazer com seus modelos.", - "s8416": "Essa opção não é possível aqui." + "s8416": "Essa opção não é possível aqui.", + "s8417": "Uma mudança foi interrompida. Termine-a ou deixe como estava.", + "s8418": "O Strata estava mudando seus modelos de {0} para {1} quando parou. Nada foi perdido.", + "s8419": "Terminar a mudança", + "s8420": "Deixar como está", + "s8421": "Terminar coloca todos os seus modelos em {1}. Deixar como está mantém os modelos em {0} e remove as cópias parciais de {1}.", + "s8422": "As cópias parciais foram removidas. Seus modelos estão em {0}." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index 02b7e2f6..e8a597f7 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3437,5 +3437,11 @@ "s8413": "Модель запущена. Сначала остановите её, затем смените папку.", "s8414": "Выберите папку моделей.", "s8415": "Выберите, что сделать с моделями.", - "s8416": "Этот вариант здесь невозможен." + "s8416": "Этот вариант здесь невозможен.", + "s8417": "Перенос был прерван. Завершите его или оставьте как есть.", + "s8418": "Strata переносил ваши модели из {0} в {1}, когда остановился. Ничего не потеряно.", + "s8419": "Завершить перенос", + "s8420": "Оставить как есть", + "s8421": "Если завершить, все модели окажутся в {1}. Если оставить, модели останутся в {0}, а неполные копии в {1} будут удалены.", + "s8422": "Неполные копии удалены. Ваши модели находятся в {0}." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index d7a75e9c..8cb47965 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3437,5 +3437,11 @@ "s8413": "有模型正在运行。请先停止它,再更改文件夹。", "s8414": "请选择模型文件夹。", "s8415": "请选择如何处理你的模型。", - "s8416": "此处无法使用该选项。" + "s8416": "此处无法使用该选项。", + "s8417": "移动被中断了。请完成它,或保持原样。", + "s8418": "Strata 正在把你的模型从 {0} 移到 {1} 时停止了。没有任何内容丢失。", + "s8419": "完成移动", + "s8420": "保持原样", + "s8421": "完成后,所有模型都会放到 {1}。保持原样则模型留在 {0},并删除 {1} 中不完整的副本。", + "s8422": "已删除不完整的副本。你的模型在 {0}。" } diff --git a/apps/host/tests/models-folder.test.mjs b/apps/host/tests/models-folder.test.mjs index ef2769bc..e3b4b0e1 100644 --- a/apps/host/tests/models-folder.test.mjs +++ b/apps/host/tests/models-folder.test.mjs @@ -8,7 +8,7 @@ import { createNativeControl } from '../server/native-control.mjs'; import { createControl } from '../server/control-runtime.mjs'; /** The host in the packaged app with a stand-in for Strata Control: the move itself is Control's (tests/terminal/test_models_move.py). */ -function fixture(t, { plan = {}, move = null } = {}) { +function fixture(t, { plan = {}, move = null, unfinished = null } = {}) { const root = realpathSync(mkdtempSync(join(tmpdir(), 'strata-mfolder-'))); const install = join(root, 'install'), data = join(root, 'host'), oldFolder = join(root, 'old'), newFolder = join(root, 'new'); for (const d of [install, data, oldFolder, newFolder]) mkdirSync(d, { recursive: true }); @@ -34,6 +34,13 @@ function fixture(t, { plan = {}, move = null } = {}) { options.onEvent({ event: 'progress', done: 5e9, total: 74e9, file: 'models/gyro-s/a.gguf', group: 'gyro-s', index: 1, count: 3, seconds_left: 300, same_drive: false }); return { ok: true, event: 'result', done: true, stopped: false, moved: ['gyro-s', 'coder'], remaining: [], bytes_moved: 74e9, total_bytes: 74e9, files_moved: 3, same_drive: false }; }, + async interruptedModelsMove(from) { calls.push(['status', from]); return unfinished; }, + async resumeModelsMove(from, options) { + calls.push(['resume', from, options.installDir]); + options.onEvent({ event: 'progress', done: 20e9, total: 74e9, file: 'models/coder/c.gguf', group: 'coder', index: 2, count: 3, seconds_left: 120, same_drive: false }); + return { ok: true, event: 'result', done: true, stopped: false, moved: ['coder'], remaining: [], bytes_moved: 74e9, total_bytes: 74e9, files_moved: 2, same_drive: false }; + }, + async leaveModelsMove(from, options) { calls.push(['leave', from, options.installDir]); return { ok: true, removed: 1, restored: 1, bytes_removed: 5 }; }, async stop() { return { ok: true }; }, }; const spawnProcess = () => { throw new Error('the host starts no process here'); }; @@ -160,11 +167,45 @@ test('a move needs the app: the Control command line is built from the plan and await assert.rejects(failing.moveModels('/o', '/n'), e => e.code === 'disk_full' && e.details === 'ENOSPC' && /ran out of space/.test(e.message)); }); +test('an unfinished move is found at the next start, and Finish resumes it as a job that changes the folder only when done', async t => { + const f = fixture(t); + f.control.interruptedModelsMove = async from => { f.calls.push(['status', from]); return { state: 'failed', from: f.oldFolder, to: f.newFolder, bytes: 74e9 }; }; + assert.equal((await f.native.interruptedMove()).to, f.newFolder); + assert.deepEqual(f.calls[0], ['status', f.oldFolder]); + const job = await f.native.finishInterruptedMove({ stopRunning: true }); + const done = await finish(f.native, job.id); + assert.equal(done.state, 'done'); + assert.equal(f.calls.find(c => c[0] === 'resume')[1], f.oldFolder); + assert.equal(f.native.state().downloadDirectory, f.newFolder); +}); + +test('Leave it keeps the old folder and asks Control to remove the partial copies; nothing interrupted means nothing to do', async t => { + const f = fixture(t); + assert.equal(await f.native.interruptedMove(), null); + await assert.rejects(f.native.leaveInterruptedMove(), /No move was interrupted/); + f.control.interruptedModelsMove = async () => ({ state: 'running', from: f.oldFolder, to: f.newFolder, bytes: 1 }); + const result = await f.native.leaveInterruptedMove(); + assert.equal(result.folder, f.oldFolder); + assert.deepEqual(f.calls.find(c => c[0] === 'leave').slice(0, 2), ['leave', f.oldFolder]); + assert.equal(f.native.state().downloadDirectory, f.oldFolder); +}); + +test('the Control command lines for status, resume and leave', async () => { + const seen = []; + const control = createControl({ control: { dir: '/c', python: '/c/py', cli: '/c/strata.py' }, run: async args => { seen.push(args); return args.includes('--status') ? { code: 0, json: { ok: true, interrupted: { from: '/o', to: '/n' } }, text: '', stderr: '' } : args.includes('--leave') ? { code: 0, json: { ok: true, removed: 0 }, text: '', stderr: '' } : { code: 0, json: { ok: true, event: 'result', done: true }, text: '', stderr: '' }; } }); + assert.equal((await control.interruptedModelsMove('/o')).to, '/n'); + await control.resumeModelsMove('/o', { installDir: '/i', cancelFile: '/c.cancel' }); + await control.leaveModelsMove('/o', { installDir: '/i' }); + assert.deepEqual(seen[0], ['models', 'move', '--status', '--from', '/o', '--output', 'json']); + assert.deepEqual(seen[1], ['models', 'move', '--resume', '--from', '/o', '--install-dir', '/i', '--cancel-file', '/c.cancel', '--output', 'jsonl']); + assert.deepEqual(seen[2], ['models', 'move', '--leave', '--from', '/o', '--install-dir', '/i', '--output', 'json']); +}); + test('the models folder strings exist in all 8 languages with the same placeholders', () => { const read = lang => JSON.parse(readFileSync(new URL(`../src/locales/${lang}.json`, import.meta.url), 'utf8')); const en = read('en'); - const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8339 && Number(k.slice(1)) <= 8416); - assert.equal(ours.length, 78); + const ours = Object.keys(en).filter(k => Number(k.slice(1)) >= 8339 && Number(k.slice(1)) <= 8422); + assert.equal(ours.length, 84); for (const lang of ['de', 'es', 'ja', 'ko', 'pt', 'ru', 'zh']) { const text = read(lang); for (const key of ours) { From 43127e39824583ff217c99467c57a5aba3a04fef Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:58:14 +0200 Subject: [PATCH 25/27] Test: the unsloth setup tests answer every disk-space question themselves --- tools/test_setup_unsloth.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/test_setup_unsloth.py b/tools/test_setup_unsloth.py index c14b9ed8..1fc97070 100644 --- a/tools/test_setup_unsloth.py +++ b/tools/test_setup_unsloth.py @@ -11,6 +11,7 @@ import contextlib import hashlib import io import json +import shutil import sys import tempfile import types @@ -186,6 +187,8 @@ class Base(unittest.TestCase): mock.patch.object(setup, "cpu_cores", lambda: None), # #642: not a hybrid CPU mock.patch.object(setup, "page_file_gb", lambda: 16.0), mock.patch.object(setup, "free_gb", lambda p: free), + # whatever else asks the disk (shutil.disk_usage) gets the same answer: the tests never depend on this PC's free space + mock.patch.object(shutil, "disk_usage", lambda p: shutil._ntuple_diskusage(int(max(free, 1000) * 1e9), int(max(free, 1000) * 1e9 - free * 1e9), int(free * 1e9))), mock.patch.object(setup, "rotational_disk", lambda p: None), # #605: not the test PC's disk mock.patch.object(setup, "is_wsl", lambda: False), # #974: the tests are not run inside WSL mock.patch.object(setup, "pip_install", lambda *a, **k: None), From b486d6f2b44406a8d64f84770e924c95b273a6c5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 16:58:31 +0200 Subject: [PATCH 26/27] Test: engine minimums are checked against the tree's CMake version, not a fixed 0.1.45 --- tools/test_setup_menu.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tools/test_setup_menu.py b/tools/test_setup_menu.py index 1f176836..284f7703 100644 --- a/tools/test_setup_menu.py +++ b/tools/test_setup_menu.py @@ -6,6 +6,7 @@ install removing a stale strata_kq library. """ from __future__ import annotations +import re import sys import tempfile import unittest @@ -155,7 +156,12 @@ class EnginePlaceholders(unittest.TestCase): self.assertEqual(setup.MIN_ENGINE, (0, 1, 45)) for m in ("UD-Q5_K_XL", "UD-Q6_K_XL", "NVFP4", "NVFP4-NVIDIA"): self.assertEqual(setup.MODELS[m]["engine"], (0, 1, 44), m) - self.assertIn("0.1.45", (ROOT / "CMakeLists.txt").read_text(encoding="utf-8").split("project(strata VERSION", 1)[1][:12]) + # No minimum may name an engine newer than this tree (a placeholder for a release that does not exist yet would make setup + # ask for an engine nobody can download). The tree's version is read from CMakeLists.txt, so this does not go stale each release. + text = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + tree = tuple(int(n) for n in re.search(r"project\(strata VERSION ([0-9.]+)", text).group(1).split(".")) + for what, minimum in [("MIN_ENGINE", setup.MIN_ENGINE), ("NVFP4_ENGINE", setup.NVFP4_ENGINE)] + [(m, setup.MODELS[m]["engine"]) for m in setup.MODELS if "engine" in setup.MODELS[m]]: + self.assertLessEqual(tuple(minimum), tree[:len(minimum)], f"{what} {minimum} is ahead of the tree {tree}") class KqLibrary(unittest.TestCase): From ebe4db78d4645e526414865b7da6f8c1f4bb47ba Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 17:17:45 +0200 Subject: [PATCH 27/27] Test: the calibrate setup test's data_folder stand-in takes the extra arguments --- tools/test_calibrate.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py index defa9432..97e33597 100644 --- a/tools/test_calibrate.py +++ b/tools/test_calibrate.py @@ -442,7 +442,7 @@ class SetupIntegration(unittest.TestCase): self.assertNotIn("an earlier start", out.getvalue()) out = io.StringIO() with mock.patch.object(self.S, "ROOT", Path(self.tmp.name)), \ - mock.patch.object(self.S, "data_folder", lambda d: (Path(self.tmp.name) / "data", [])), \ + mock.patch.object(self.S, "data_folder", lambda d, *a, **k: (Path(self.tmp.name) / "data", [])), \ mock.patch.object(self.S, "update_installed_engine", lambda *a: None), \ mock.patch.object(sys, "argv", ["setup.py", "--calibrate", "--no-start"]), \ contextlib.redirect_stdout(out):