diff --git a/.dockerignore b/.dockerignore index 4f341af3..2550d9bf 100644 --- a/.dockerignore +++ b/.dockerignore @@ -17,6 +17,11 @@ __pycache__/ /mtp/ /models/ /Strata-data/ +# the folders docker/entrypoint.sh creates in a mounted data/ (a link to llama.cpp, the models, the keys): never part of a build (#3644) +/data/install/ +/data/state/ +/data/home/ +/data/Strata-data/ third_party/llama.cpp/ third_party/*.zip *.done diff --git a/.gitattributes b/.gitattributes index e9e15ba7..8a835e52 100644 --- a/.gitattributes +++ b/.gitattributes @@ -25,3 +25,6 @@ docker/compose/* text eol=lf # Apple tools (codesign, plutil) read these: LF only, wherever the repository is cloned *.plist text eol=lf + +# vendored KaTeX (serve/web/vendor): the files are hashed byte for byte (PROVENANCE.json), never convert their line endings. +serve/web/vendor/** -text diff --git a/.github/workflows/metal-build.yml b/.github/workflows/metal-build.yml index 7a69696f..a4f7d997 100644 --- a/.github/workflows/metal-build.yml +++ b/.github/workflows/metal-build.yml @@ -20,7 +20,9 @@ permissions: jobs: metal-link: - runs-on: macos-14 + # the macOS 26 SDK: metal/src/mtl_rt.mm names MTLGPUFamilyMetal4 (and MTLCompileOptions.mathMode, macOS 15) behind @available, + # which is a run-time check; the names must still be in the SDK the engine is compiled against + runs-on: macos-26 timeout-minutes: 45 env: # setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin diff --git a/.gitignore b/.gitignore index c6cfb336..88ad4c7b 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,10 @@ build-vision-cuda12.bat /.ccache/ /.rocm-win/ +# Optional MCP raster cache +*.tool-media/ +/.tool-media/ + # local Windows HIP packaging output dist-hip/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c6f2879..ff7fb591 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -179,7 +179,13 @@ elseif(STRATA_ENABLE_CUDA) # a build with no option was an sm_75 build. -DCMAKE_CUDA_ARCHITECTURES and the CUDAARCHS environment variable win. set(_strata_cuda_arch_defaulted OFF) if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES AND NOT DEFINED ENV{CUDAARCHS}) - set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures") + if(STRATA_BUILD_DSV41) + # #3935: the DeepSeek engine's own release shape (sm_86, sm_89, sm_120 + PTX 120, as packaging/build_dsv41_cuda.sh), so a hand + # build of strata-dsv41 with no architecture runs on an RTX 30, 40 or 50 card; the Qwen engine's default below is unchanged + set(CMAKE_CUDA_ARCHITECTURES "86-real;89-real;120" CACHE STRING "CUDA architectures") + else() + set(CMAKE_CUDA_ARCHITECTURES 120 CACHE STRING "CUDA architectures") + endif() set(_strata_cuda_arch_defaulted ON) endif() enable_language(CUDA) @@ -189,7 +195,7 @@ elseif(STRATA_ENABLE_CUDA) option(STRATA_EXPERIMENTAL_SM60 "community build for GPUs below compute capability 7.5: Pascal sm_60, Volta sm_70 (#236)" OFF) if(_strata_cuda_arch_defaulted) # a recommendation, not a refusal: the release engine is built for 75;86;89;120, a hand build names its card - message(WARNING "Strata: CMAKE_CUDA_ARCHITECTURES was not set, so this build is for sm_120 (RTX 50) only. For another " + message(WARNING "Strata: CMAKE_CUDA_ARCHITECTURES was not set, so this build is for ${CMAKE_CUDA_ARCHITECTURES} only (sm_120 = RTX 50). For another " "card pass it: -DCMAKE_CUDA_ARCHITECTURES=native (the GPUs in this PC), 75 (RTX 20), 86 (RTX 30), " "89 (RTX 40), or a list like \"86;120\".") endif() @@ -213,9 +219,16 @@ elseif(STRATA_ENABLE_CUDA) "CMAKE_CUDA_ARCHITECTURES is '${CMAKE_CUDA_ARCHITECTURES}'. (A Pascal sm_60 or Volta sm_70 build is " "-DSTRATA_EXPERIMENTAL_SM60=ON; upstream does not support it.)") endif() - if(_base LESS 60) + if(_base LESS 52) message(FATAL_ERROR "CMAKE_CUDA_ARCHITECTURES '${CMAKE_CUDA_ARCHITECTURES}': even the experimental build " - "needs compute capability 6.0 (sm_60) or newer") + "needs compute capability 5.2 (sm_52, Maxwell) or newer") + endif() + # Maxwell (sm_52, #3218): one reporter built and ran this on two Quadro M6000 (CUDA 12.x, Qwen3.8-Flash-Next + # IQ1, about 22 t/s). It has no native half-precision arithmetic, so it is slower per byte than Pascal; only + # this opt-in build gets the floor. Warn, do not refuse. + if(_base LESS 60) + message(WARNING "Building for sm_${_base} (Maxwell): community-tested on one reporter's Quadro M6000 only, " + "no native half-precision arithmetic, CUDA 12.x toolkit required (docs/OLDER_GPUS.md).") endif() # #220 / #224: RTX 50 engines built with CUDA 12.8 crashed in the prompt path on Linux (13.0 and newer did not) if(_base GREATER_EQUAL 120 AND CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 13.0) @@ -430,6 +443,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/fused_gdn.cu src/kernels/cuda/dequant_bf16.cu src/kernels/cuda/qsa_select.cu + src/kernels/cuda/qsa_pattn.cu src/kernels/cuda/verify_kernels.cu src/kernels/cuda/dflash2.cu src/kernels/cuda/iq_kernels.cu @@ -459,6 +473,29 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) endif() + # PR #3943: STRATA_PATTN_SM60's score and value kernels against the decode kernels' output (the Daily's chunk kernel and + # the merge), bitwise, on random int8 K/V (GPU, synthetic, no model). Only in the experimental sm_60 build; it skips + # (77) on a build without the kernels. + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_pattn_parity src/kernels/qsa_pattn_parity.cpp) + target_include_directories(qsa_pattn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_pattn_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_pattn_parity COMMAND qsa_pattn_parity) + set_tests_properties(qsa_pattn_parity PROPERTIES SKIP_RETURN_CODE 77) + endif() + # PR #3820: STRATA_SELECT_LONG's multi-CTA top-k and shuffle-free decode scorer against qsa_block_topk and + # qsa_block_scores, bitwise, on random scores (GPU, synthetic, no model). The switches force the new kernels on any + # card; the "n3" case fixes three CTAs a query. Only in the experimental sm_60 build (skips with 77 otherwise). + if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + add_executable(qsa_select_long_parity src/kernels/qsa_select_long_parity.cpp) + target_include_directories(qsa_select_long_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + target_link_libraries(qsa_select_long_parity PRIVATE strata_kernels CUDA::cudart) + add_test(NAME qsa_select_long_parity COMMAND qsa_select_long_parity) + add_test(NAME qsa_select_long_parity_n3 COMMAND qsa_select_long_parity) + set_tests_properties(qsa_select_long_parity qsa_select_long_parity_n3 PROPERTIES SKIP_RETURN_CODE 77) + set_tests_properties(qsa_select_long_parity PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1") + set_tests_properties(qsa_select_long_parity_n3 PROPERTIES ENVIRONMENT "STRATA_SCORES_DX=1;STRATA_TOPK_MULTI=1;STRATA_TOPK_MULTI_N=3") + endif() # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) @@ -697,6 +734,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) set_tests_properties(conversation_snapshot_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the same test with a GDN state over 1 MiB and the opt-in background checkpoint copy (STRATA_CKPT_ASYNC=1), alone and with + # recent states kept in VRAM (STRATA_CKPT_VRAM_SLOTS): every checkpoint, capture and restore must give the same bytes + add_test(NAME conversation_snapshot_test_ckpt_async COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test_ckpt_async PROPERTIES + ENVIRONMENT "STRATA_TEST_BIG_GDN=1;STRATA_CKPT_ASYNC=1" SKIP_RETURN_CODE 77 TIMEOUT 300) + add_test(NAME conversation_snapshot_test_ckpt_vram_slots COMMAND conversation_snapshot_test) + set_tests_properties(conversation_snapshot_test_ckpt_vram_slots PROPERTIES + ENVIRONMENT "STRATA_TEST_BIG_GDN=1;STRATA_CKPT_ASYNC=1;STRATA_CKPT_VRAM_SLOTS=3" SKIP_RETURN_CODE 77 TIMEOUT 300) add_executable(conversation_validation_test src/core/conversation_validation_test.cpp) target_link_libraries(conversation_validation_test PRIVATE strata_engine) add_test(NAME conversation_validation_test COMMAND conversation_validation_test) @@ -833,8 +878,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) endif() set_source_files_properties(src/dsv41/ds4_main.cpp PROPERTIES COMPILE_DEFINITIONS "DS4_BUILD_ID=\"${STRATA_BUILD_ID}\"") target_include_directories(strata-dsv41 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) - target_link_libraries(strata-dsv41 PRIVATE strata_dsv41_kernels ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target}) + ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill) + # strata_prefill: the RDNA3 WMMA dense GEMM (src/prefill/wmma_gemm.cu), which gemm() prefers over hipBLAS on gfx11 (measured + # 4.97 -> 20-40 TFLOPS on this part: the chunked prompt's dense GEMM is 11.1 s of a 4K prompt at the library's rate) + target_link_libraries(strata-dsv41 PRIVATE strata_prefill strata_dsv41_kernels ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target}) find_package(Threads REQUIRED) target_link_libraries(strata-dsv41 PRIVATE Threads::Threads) if(WIN32 AND STRATA_ENABLE_HIP) # cudaMemGetInfo is the DXGI-budgeted hip_compat::mem_get_info (src/core/device.cu): on a Strix Halo the @@ -1111,6 +1158,13 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) + # sm_89's opt-in tables (#3453, STRATA_MMVQ_IL_89=1): the table check only (no case matches MMVQ_IL_ONLY) + add_test(NAME mmvq_il_parity_89table COMMAND mmvq_il_parity) + set_tests_properties(mmvq_il_parity_89table PROPERTIES ENVIRONMENT "STRATA_MMVQ_IL_89=1;MMVQ_IL_ONLY=no-such-case") + # the opt-in STRATA_MMVQ_IL_PF kernels (hoisted group loads, exact integer forms): every variant bit-checked against + # native_mmvq for every type, shape, T and rows choice + add_test(NAME mmvq_il_parity_pf COMMAND mmvq_il_parity --pf 0,2,3,4,5,6) + set_tests_properties(mmvq_il_parity_pf PROPERTIES TIMEOUT 900) # the wide dequant kernels (a thread per 8 values; sm_61's default), bitwise vs the per-group ones (GPU, synthetic, # no model; --bench adds old/new timings) add_executable(dequant_wide_parity src/kernels/dequant_wide_parity.cpp) @@ -1166,11 +1220,22 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target}) add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity) + # STRATA_GDN_TC=1: the tensor-core helpers of the scan, each on one warp against a double-precision reference. Any sm_80+ + # card runs them; the scan itself needs 122 KB of shared memory a block (sm_80, sm_90), where gdn_rec_parity prints + # "not on this card" for the tc variant + add_test(NAME gdn_rec_parity_selftest_frag COMMAND gdn_rec_parity --selftest-frag) + set_tests_properties(gdn_rec_parity_selftest_frag PROPERTIES SKIP_RETURN_CODE 77) # the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the # FP16 tensor cores; GPU, synthetic, no model; --bench adds timings) add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu) target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill ) add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity) + # STRATA_DEQUANT_SIDE: Gemm::native with the dense dequant on a side stream (two scratches) against the serial form, + # bitwise (GPU, synthetic, no model; 77 without a device) + add_executable(gemm_dequant_side_parity src/prefill/gemm_dequant_side_parity.cu) + target_link_libraries(gemm_dequant_side_parity PRIVATE strata_prefill ) + add_test(NAME gemm_dequant_side_parity COMMAND gemm_dequant_side_parity) + set_tests_properties(gemm_dequant_side_parity PROPERTIES SKIP_RETURN_CODE 77) # Pascal, opt-in STRATA_DENSE_F32=1: the dense projections' FP16 GEMMs as cublasSgemm on FP32 copies, bitwise vs # the cuBLAS FP16 call over a sweep of chunk sizes (GPU, synthetic, no model; --full sweeps every size, --bench # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. @@ -1415,6 +1480,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_test(NAME ple_parity COMMAND ple_parity --selftest --in "${STRATA_PLE_FIXTURE_DIR}/ple_in.bin" --out "${STRATA_PLE_FIXTURE_DIR}/ple_out.bin" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + # STRATA_PLE_COMPACT: the raw IQ4_NL rows dequantized on the device against the host decode, bit for bit (synthetic, no model) + add_executable(ple_iq4nl_dequant_test src/kernels/ple_iq4nl_dequant_test.cpp) + target_include_directories(ple_iq4nl_dequant_test PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(ple_iq4nl_dequant_test PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_test(NAME ple_iq4nl_dequant_test COMMAND ple_iq4nl_dequant_test) + set_tests_properties(ple_iq4nl_dequant_test PROPERTIES SKIP_RETURN_CODE 77) # Plan v0.3 P7: INT8 KV storage vs a host reference and vs the FP16 path (GPU, synthetic, no model). add_executable(kv_q8_parity src/kernels/kv_q8_parity.cpp) @@ -1910,6 +1981,12 @@ if(STRATA_NATIVE_EXPERTS) add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu src/prefill/mmq_nvfp4_w4a8.cu src/prefill/ggml_cuda_host.cu ${_strata_quantize_cu}) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # GP100 (sm_60): a resident layer's experts weight-stationary, one launch per product (moe_ws.hpp; opt-in at + # run time, STRATA_MMQ_WS=1, and only where every visible GPU is cc 6.0) + target_sources(strata_mmq PRIVATE src/prefill/moe_ws.cu src/prefill/moe_ws_gu_iq2.cu src/prefill/moe_ws_gu_iq3.cu + src/prefill/moe_ws_down.cu) + endif() # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and # STRATA_MMQ_KQUANTS q4_k q5_k q5_1 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch # follows eddoursul/Strata 7706c1b). MODEL-UPDATE Phase 1: on CUDA they are a library of their own, strata_kq @@ -2048,6 +2125,10 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_prefill PUBLIC strata_mmq) target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) + if(STRATA_EXPERIMENTAL_SM60 AND NOT STRATA_HIP_GFX906) + # the weight-stationary experts (moe_ws.hpp) are in strata_mmq: the prompt path may take them (STRATA_MMQ_WS=1) + target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_WS=1) + endif() if(STRATA_BUILD_TESTS) # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80) add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp) @@ -2059,12 +2140,40 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_Q2N=1 on its own (the test leaves STRATA_PF_FUSED unset): the native Q2_0 pack's Q2_0 / Q2_0 + # layers on sm_80+ (77 below sm_80 and without a card) + add_test(NAME prefill_fused_iq_test_q2n COMMAND prefill_fused_iq_test "--only=Q2_0 / Q2_0" --unset-pf-fused) + set_tests_properties(prefill_fused_iq_test_q2n PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_Q2N=1" SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_NT=256 kernels (256 threads, two blocks a multiprocessor, two-pass weight loads) against the + # same references; the batches of the test reach them through the Batch overload of experts_native (77 below sm_80) + add_test(NAME prefill_fused_iq_test_nt256 COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_nt256 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_NT=256" SKIP_RETURN_CODE 77 TIMEOUT 600) + # the opt-in STRATA_PF_FUSED_F16=1 (f16 mma, rounding level) and STRATA_PF_FUSED_WS=1 (warp-specialized, the same F16 products; + # about 101 KB of shared memory at its defaults, more than an sm_86 / sm_89 / sm_120 card's 99 KB, so it is set up on + # sm_80 and sm_90 cards and the test skips (77) elsewhere) + add_test(NAME prefill_fused_iq_test_f16 COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_f16 PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_F16=1" SKIP_RETURN_CODE 77 TIMEOUT 600) + add_test(NAME prefill_fused_iq_test_ws COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test_ws PROPERTIES ENVIRONMENT "STRATA_PF_FUSED_WS=1" SKIP_RETURN_CODE 77 TIMEOUT 600) # the MoE input quantized per token and scattered to its rows (mmq::quantize_scatter) against the per-row # gather: the same q8_1 bytes for every MMQ layout (--bench: both at 2K, 8K and 32K tokens) add_executable(prefill_mmq_scatter_test tests/cuda/prefill_mmq_scatter_test.cpp) target_link_libraries(prefill_mmq_scatter_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_mmq_scatter_test COMMAND prefill_mmq_scatter_test) set_tests_properties(prefill_mmq_scatter_test PROPERTIES TIMEOUT 120) + if(STRATA_EXPERIMENTAL_SM60) + # mmq::swiglu_quant: swiglu + the down product's q8_1 rows in one kernel against the two, byte for byte + add_executable(prefill_swiglu_quant_test tests/cuda/prefill_swiglu_quant_test.cpp) + target_link_libraries(prefill_swiglu_quant_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_swiglu_quant_test COMMAND prefill_swiglu_quant_test) + set_tests_properties(prefill_swiglu_quant_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + # the weight-stationary experts (STRATA_MMQ_WS) against the per-group MMQ, byte for byte, on random experts; the + # verdict is given on a compute capability 6.0 card only (77 elsewhere) + add_executable(prefill_ws_parity_test tests/cuda/prefill_ws_parity_test.cpp) + target_link_libraries(prefill_ws_parity_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_ws_parity_test COMMAND prefill_ws_parity_test) + set_tests_properties(prefill_ws_parity_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) + endif() endif() if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) @@ -2201,6 +2310,20 @@ if(STRATA_NATIVE_EXPERTS) add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) + # STRATA_EXPERT_NIBBLE (include/strata/core/expert_nibble.hpp): the 4-bit gate/up expert slots against the + # production kernels and the GGUF blobs, bit for bit, on a real model's layers (needs a GP100); --header: the + # contract's host half, no GPU + add_executable(iq_nibble_parity src/kernels/iq_nibble_parity.cpp) + target_include_directories(iq_nibble_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(iq_nibble_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ggml-base ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS) + add_test(NAME iq_nibble_parity_header COMMAND iq_nibble_parity --header) + # the synthetic experts of every gate/up x down format pair, no model (skips with 77 on a card that is not a GP100) + add_test(NAME iq_nibble_parity_synthetic COMMAND iq_nibble_parity --synthetic-only) + set_tests_properties(iq_nibble_parity_synthetic PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 900) + endif() + endif() # MODEL-UPDATE: the dense Q8_0 GEMVs at the engine's shapes against the memory bandwidth (a benchmark, no test) add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp) target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories}) @@ -2342,6 +2465,10 @@ if(STRATA_BUILD_TESTS) add_executable(warm_policy_test src/prefill/warm_policy_test.cpp) target_include_directories(warm_policy_test PRIVATE include) add_test(NAME warm_policy_test COMMAND warm_policy_test) + # #4005: which streamed expert copies get a copied event (header-only, CPU) + add_executable(copy_events_test src/prefill/copy_events_test.cpp) + target_include_directories(copy_events_test PRIVATE include) + add_test(NAME copy_events_test COMMAND copy_events_test) # issue #29: tiny batches with sleeping workers, as on a big-VRAM card; a hang fails it add_executable(pool_stress src/kernels/cpu/pool_stress.cpp) target_link_libraries(pool_stress PRIVATE strata_kernels_cpu) diff --git a/Dockerfile b/Dockerfile index 82f096cf..eba34a01 100644 --- a/Dockerfile +++ b/Dockerfile @@ -68,6 +68,8 @@ RUN set -e; \ # ---- 2. the Terminal (the release archive, built here) FROM ${RUNTIME_BASE} AS terminal +ARG STRATA_COMMIT= +ENV STRATA_BUILD_COMMIT=${STRATA_COMMIT} ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/* COPY . /src/ diff --git a/README.de.md b/README.de.md index e9dd81b4..cf1f8186 100644 --- a/README.de.md +++ b/README.de.md @@ -20,7 +20,7 @@ Strata auf Buy Me a Coffee unterstützen

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**Kostenlos, Open Source und ganz in deiner Hand.** Nutze Strata auf dem Desktop oder mit deinen liebsten Coding-Tools. Kein Konto nötig. diff --git a/README.es.md b/README.es.md index 52b9f30d..63e96151 100644 --- a/README.es.md +++ b/README.es.md @@ -20,7 +20,7 @@ Apoya Strata en Buy Me a Coffee

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**Gratis, de código abierto y tuyo para ejecutar.** Usa Strata en tu escritorio o con tus herramientas de programación favoritas. No necesitas cuenta. diff --git a/README.fr.md b/README.fr.md index 0d2e04f1..a3f7fd4d 100644 --- a/README.fr.md +++ b/README.fr.md @@ -20,7 +20,7 @@ Soutenir Strata sur Buy Me a Coffee

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**Gratuit, open source, et à vous de l'exécuter.** Utilisez Strata sur votre bureau ou avec vos outils de programmation préférés. Aucun compte nécessaire. diff --git a/README.ja.md b/README.ja.md index 47f8baa4..d57eab8c 100644 --- a/README.ja.md +++ b/README.ja.md @@ -20,7 +20,7 @@ Buy Me a Coffee で Strata を支援する

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**無料でオープンソース。自分の環境で動かせます。** デスクトップで、またはお好みのコーディングツールと一緒に Strata を使えます。アカウントは不要です。 diff --git a/README.md b/README.md index a5baabec..af82584d 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Support Strata on Buy Me a Coffee

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · PortuguĂŞs

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed. diff --git a/README.pl.md b/README.pl.md new file mode 100644 index 00000000..5c779ef2 --- /dev/null +++ b/README.pl.md @@ -0,0 +1,192 @@ +

+ + + Strata + +

+ +

Uruchom potężną sztuczną inteligencję na własnym komputerze.

+

Rozmawiaj, programuj i pracuj z obrazami — lokalnie.

+ +

+ Modele · Instalacja · + Sprzęt · Narzędzia · + Pomoc · Wsparcie +

+ +

+ Pobierz Stratę + Licencja MIT + Wesprzyj Stratę na Buy Me a Coffee +

+ +

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

+ +**Bezpłatna, z otwartym kodem źródłowym i do uruchomienia u siebie.** Używaj Straty na swoim komputerze albo razem z ulubionymi narzędziami do programowania. Konto nie jest potrzebne. + +## Modele + +Najpierw polecamy **ISTA-DASLab**, potem **Unsloth** i innych dostawców — o ile zgodny model mieści się w pamięci. + +
+  Qwen3.8-Flash-Next + +| Dostawca | Do wyboru | +| --- | --- | +| **ISTA-DASLab · polecany** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) do programowania. | +| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | +| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Zużywa mniej pamięci, ale działa wolniej. | +| **Inne opcje** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | + +[Porównaj rozmiary, wymagania pamięciowe i zgodność](docs/MODELS.md). + +
+ +
+  Qwen3.6-35B-A3B + +**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. To obecnie udokumentowane pakiety dla tego modelu. + +[Przewodnik po modelu i zgodność](docs/QWEN36.md). + +
+ +
+  DeepSeekV4.1-Flash-1017 + +W **aplikacji na komputer** i w **Terminalu**. To, co nie mieści się w pamięci, jest czytane z dysku SSD, więc potrzebujesz +dużo wolnego miejsca na dysku. + +| Zestaw (IST-DAS) | Do pobrania | Potrzebne wolne miejsce | +| --- | ---: | ---: | +| 1.75 bpw | 239 GB | około 245 GB | +| 2.00 bpw | 257 GB | około 265 GB | +| 2.25 bpw | 274 GB | około 280 GB | + +Działa na kartach NVIDIA RTX serii 30, 40 i 50 (Windows i Linux), AMD Radeon AI PRO R9700 (Linux) oraz AMD Ryzen AI Max — Strix Halo +(Windows). Instalacja pobiera pliki i silnik DeepSeek, a potem uruchamia model. + +```sh +strata launch --family deepseek41 --model ist-das-2.00bpw --plan +``` + +Zmierzone na zestawie 2.00 bpw w Strata 0.2.5 (Strix Halo: 0.2.7). „Wyjście” to szybkość odpowiedzi, „prompt” — jak szybko Strata czyta twój tekst. + +| Sprzęt | Wyjście | Prompt | +| --- | ---: | ---: | +| RTX 5070 12 GB, 64 GB RAM | 4–6 tokenów/s | około 110 tokenów/s (4K) | +| RTX 3060 12 GB, 46 GB RAM | 9–11 tokenów/s | około 155 tokenów/s (4K) | +| 1x Radeon AI PRO R9700, 251 GB RAM | 21–25 tokenów/s | 320–360 tokenów/s (8K) | +| 4x Radeon AI PRO R9700 | 74–77 tokenów/s | 400–450 tokenów/s (8K) | +| Ryzen AI Max+ 395 (Strix Halo), 128 GB pamięci współdzielonej | 19–21 tokenów/s (kod), 11 (czat) | 87 tokenów/s (4K), 125 tokenów/s (8K) | + +[Pamięć, dysk i szczegóły](docs/DEEPSEEK41.md) · [Informacje o wydaniach](https://github.com/Niko1221/Strata/releases) + +
+ + + +Nie wiesz, co się zmieści? [Wybierz model do swojego komputera](docs/MODELS.md#pick-by-memory). + +## Instalacja + + + +### Aplikacja na komputer + +**[Pobierz Stratę dla Windows, Linuxa lub Maca →](https://github.com/Niko1221/Strata/releases/latest)** + +Zainstaluj aplikację, wybierz model i zacznij rozmawiać. Dla każdego systemu jest jeden instalator. Przy pierwszym +uruchomieniu aplikacja pobiera silnik dla twojej karty graficznej. [Pomoc z instalatorem](docs/INSTALL.md#the-app). + +Pliki: `Strata-0.2.6-windows-x64-setup.exe` · `Strata-0.2.6-linux-x86_64.AppImage` · `Strata-0.2.6-macos-arm64.dmg` + +

+ Aplikacja Strata na komputer: czat i podgląd kodu na żywo obok siebie +
Czat, pliki i podgląd na żywo w jednym oknie. +

+ + + +### Aplikacja Terminal + +Wolisz terminal? Zainstaluj Stratę, a potem uruchom **`strata launch`**. + +
+Polecenia instalacji + +**Linux / Mac** + +```sh +curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh +``` + +**Windows PowerShell** + +```powershell +irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex +``` + +W Windows otwórz potem nowe okno terminala. Następnie: + +```sh +strata launch +``` + +Postępuj zgodnie z podpowiedziami, aby pobrać i uruchomić model. [Przewodnik po Terminalu](docs/TERMINAL_LAUNCH.md). + +
+ +

+ Aplikacja Terminal Straty pokazująca aktywność modelu, szybkość, pamięć i ostatnie zapytania +
Obserwuj model i sprzęt w trakcie pracy. +

+ + + +[Budowanie ze źródeł](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Pełny przewodnik instalacji](docs/INSTALL.md) + + + +## Sprzęt + +| Obsługiwany sprzęt | Przewodnik | +| --- | --- | +| **NVIDIA GeForce RTX serii 20 / 30 / 40 / 50** | [Konfiguracja NVIDIA](docs/INSTALL.md#what-you-need) | +| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Konfiguracja AMD](docs/AMD_HIP.md) | +| **AMD Radeon RX 6800 / 6900 · eksperymentalnie** | [Konfiguracja RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | +| **Intel Arc · Linux** | [Konfiguracja Intel](docs/INTEL_ARC.md) | +| **Apple Silicon · M1 lub nowszy** | [Konfiguracja Mac](docs/MAC.md) | +| **AMD Ryzen AI Max · Strix Halo** | [Konfiguracja Strix Halo](docs/STRIX_HALO.md) | + + + +## Narzędzia + +**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw** i inne — przez API zgodne z OpenAI i Anthropic. + +Uruchom **`strata connect`**, aby zobaczyć instrukcję konfiguracji dla swojego narzędzia. [Przewodnik po połączeniach](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). + + + + + + +## Pomoc + +[Wszystkie przewodniki](docs) · [Rozwiązywanie problemów](docs/TROUBLESHOOTING.md) · [Zgłoś błąd](https://github.com/Niko1221/Strata/issues/new/choose) · +[Testy wydajności](docs/COMMUNITY_BENCHMARKS.md) · [Jak to działa](docs/HOW_IT_WORKS.md) · [Współtworzenie](CONTRIBUTING.md) + +## Wesprzyj Stratę + +**Pomóż zachować lokalną sztuczną inteligencję otwartą dla wszystkich.** Kawa pomaga finansować rozwój i testy na większej liczbie sprzętu. + +Buy Me a Coffee: wesprzyj Stratę + +[Licencja MIT](LICENSE) · [Podziękowania i licencje modeli](docs/HOW_IT_WORKS.md#credits) · [Prywatność](docs/SAFETY.md) + + + +Dla narzędzi AI i automatycznych czytników: dokumentacja techniczna · instrukcja instalacji. + +**Sponsoring, partnerstwa sprzętowe i współpraca:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/README.pt-BR.md b/README.pt-BR.md index bcc2796e..68556d00 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -20,7 +20,7 @@ Apoie o Strata no Buy Me a Coffee

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**Gratuito, de código aberto e seu para executar.** Use o Strata no desktop ou com suas ferramentas de programação favoritas. Não precisa de conta. diff --git a/README.zh-CN.md b/README.zh-CN.md index 4c716fe7..b21e8e80 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -20,7 +20,7 @@ 在 Buy Me a Coffee 上支持 Strata

-

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

+

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português · Polski

**免费、开源,由你自己运行。** 在桌面上使用 Strata,或搭配你喜欢的编程工具。无需账号。 diff --git a/SECURITY.md b/SECURITY.md index 8bd61c84..8afbf44c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -23,8 +23,9 @@ this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAIL - **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to your network, and the server then warns when no API key is set. - **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint - that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, - `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the + that shows the model's state, requests or answers (`/status`, `/metrics`, `/metrics/prometheus`, `/settings`, + `/mcp`, `/props`, `/slots`, `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. + Set one before you open the server to your network or put a tunnel in front of it. - **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's diff --git a/apps/desktop/scripts/harness-budget.mjs b/apps/desktop/scripts/harness-budget.mjs new file mode 100644 index 00000000..4f588d75 --- /dev/null +++ b/apps/desktop/scripts/harness-budget.mjs @@ -0,0 +1,52 @@ +/** Strata's output-budget correction for the staged pi-ai copy. */ +import { createHash } from 'node:crypto'; +import { lstatSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +export const HARNESS_BUDGET_PATCH = Object.freeze({ + id: 'strata-pi-ai-context-safety-v2', + package: '@earendil-works/pi-ai', + version: '1.1.0', + file: 'node_modules/@earendil-works/pi-ai/dist/api/simple-options.js', + beforeSha256: '9b3cc0ae6daa86fdc050bc0cb0f3f986401e64ccddbde6757183c9f8ad411be2', +}); + +const sha256 = bytes => createHash('sha256').update(bytes).digest('hex'); +const oldClamp = 'const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;'; +// Small windows also need room after tool results; a fixed margin must not +// consume all remaining estimated space. Keep the old 64K+ calculation. +const newClamp = `const remaining = model.contextWindow - estimateContextTokens(context).tokens; + const safety = model.contextWindow >= 65536 ? CONTEXT_SAFETY_TOKENS + : Math.min(CONTEXT_SAFETY_TOKENS, Math.floor(model.contextWindow / 16), Math.max(0, Math.floor(remaining / 2))); + const available = remaining - safety;`; + +/** + * Patch only a flattened, disposable staged Harness. Returns the BUNDLE.json + * provenance entry; the caller records it when writing the bundle manifest. + * A repeat application or any unknown package/source fails before writing. + */ +export function patchStagedHarnessBudget(stagedRoot) { + const fail = message => { throw new Error(`Harness output-budget patch: ${message}`); }; + const root = realpathSync(resolve(stagedRoot)); + const packageDir = join(root, 'node_modules', '@earendil-works', 'pi-ai'); + const target = join(root, HARNESS_BUDGET_PATCH.file); + let manifest, before; + try { + manifest = JSON.parse(readFileSync(join(packageDir, 'package.json'), 'utf8')); + // Flattening must have removed links; never write through a shared source file. + if (realpathSync(target) !== target || !lstatSync(target).isFile() || lstatSync(target).nlink !== 1) + fail('expected an unlinked staged module'); + before = readFileSync(target); + } catch (error) { + fail(`cannot read a standalone staged pi-ai dependency (${error.message})`); + } + if (manifest?.name !== HARNESS_BUDGET_PATCH.package || manifest?.version !== HARNESS_BUDGET_PATCH.version) + fail('expected @earendil-works/pi-ai 1.1.0; review the patch before staging a different dependency'); + if (sha256(before) !== HARNESS_BUDGET_PATCH.beforeSha256) + fail('unexpected simple-options.js SHA-256; review the dependency source before staging'); + const source = before.toString('utf8'); + if (source.split(oldClamp).length !== 2) fail('expected exactly one known context clamp'); + const after = Buffer.from(source.replace(oldClamp, newClamp)); + writeFileSync(target, after); + return { ...HARNESS_BUDGET_PATCH, afterSha256: sha256(after) }; +} diff --git a/apps/desktop/scripts/stage-harness.mjs b/apps/desktop/scripts/stage-harness.mjs index 7327d88e..0e6738ea 100644 --- a/apps/desktop/scripts/stage-harness.mjs +++ b/apps/desktop/scripts/stage-harness.mjs @@ -19,6 +19,7 @@ import { join, relative, resolve, sep } from 'node:path'; import { createHash } from 'node:crypto'; import { flattenPnpm } from './flatten-pnpm.mjs'; import { isOtherOsBinaryFolder, missingHarnessImports } from './harness-prune.mjs'; +import { patchStagedHarnessBudget } from './harness-budget.mjs'; const args = process.argv.slice(2); const opt = (name, fallback) => { const i = args.indexOf(`--${name}`); return i >= 0 ? args[i + 1] : fallback; }; @@ -144,6 +145,9 @@ function prune(dir) { } prune(out); +// Strata's provenance-recorded output-budget correction applies only to this copy. +const patches = [patchStagedHarnessBudget(out)]; + // --- licence: the MIT text and the third-party notices travel with the files --------------------------------------------- for (const name of ['LICENSE', 'THIRD_PARTY_NOTICES.md']) { if (existsSync(join(src, name))) cpSync(join(src, name), join(out, name)); @@ -156,6 +160,7 @@ const total = size(out); writeFileSync(join(out, 'BUNDLE.json'), JSON.stringify({ component: 'deepseek-harness', version: cli.version, commit, license: 'MIT', platform, node: process.version, bytes: total.bytes, files: total.files, entry: 'apps/cli/lib/bin.js', builtAt: new Date().toISOString(), + patches, note: 'Pruned production install (pnpm deploy --prod). No package manager runs on the user\'s PC.', }, null, 2)); diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 368763dc..09b71357 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -349,6 +349,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -1755,6 +1761,19 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png 0.18.1", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2097,6 +2116,20 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "mac-notification-sys" +version = "0.6.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca" +dependencies = [ + "cc", + "log", + "objc2", + "objc2-foundation", + "time", + "uuid", +] + [[package]] name = "markup5ever" version = "0.39.0" @@ -2166,6 +2199,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "muda" version = "0.20.0" @@ -2229,6 +2272,20 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "notify-rust" +version = "4.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4587364a9a0074333429b3df75a30a205340c56a536ca3eb6ca0e59b87bbf8af" +dependencies = [ + "futures-lite", + "log", + "mac-notification-sys", + "serde", + "tauri-winrt-notification", + "zbus", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -2757,6 +2814,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "precomputed-hash" version = "0.1.1" @@ -2825,6 +2891,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + [[package]] name = "quick-xml" version = "0.42.0" @@ -2855,6 +2927,35 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -3531,6 +3632,7 @@ dependencies = [ "serde_json", "tauri", "tauri-build", + "tauri-plugin-notification", "tauri-plugin-shell", "tauri-plugin-single-instance", "tauri-plugin-updater", @@ -3755,6 +3857,7 @@ dependencies = [ "gtk", "heck 0.5.0", "http", + "image", "jni 0.21.1", "libc", "log", @@ -3869,6 +3972,26 @@ dependencies = [ "walkdir", ] +[[package]] +name = "tauri-plugin-notification" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b939d7b19c8af1381a72ef8474b3aba2b56c1ddac2c23f0c8e96abbcf86b198b" +dependencies = [ + "log", + "notify-rust", + "rand", + "serde", + "serde_json", + "serde_repr", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", + "time", + "url", + "zbus", +] + [[package]] name = "tauri-plugin-shell" version = "2.5.0" @@ -4042,6 +4165,17 @@ dependencies = [ "toml 1.1.8+spec-1.1.0", ] +[[package]] +name = "tauri-winrt-notification" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-version", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -5332,6 +5466,26 @@ dependencies = [ "serde", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 324f8963..90c1cf12 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -15,8 +15,10 @@ webkit2gtk = "2.0" tauri-build = { version = "2", features = [] } [dependencies] -tauri = { version = "2", features = [] } +tauri = { version = "2", features = ["tray-icon", "image-png"] } tauri-plugin-shell = "2" +# Desktop notifications for an approval that waits (#3477); the tray icon above is Tauri's own. +tauri-plugin-notification = "2" tauri-plugin-updater = "2" tauri-plugin-single-instance = "2" serde = { version = "1", features = ["derive"] } diff --git a/apps/desktop/src-tauri/gen/schemas/acl-manifests.json b/apps/desktop/src-tauri/gen/schemas/acl-manifests.json index ee63464d..9bccc08a 100644 --- a/apps/desktop/src-tauri/gen/schemas/acl-manifests.json +++ b/apps/desktop/src-tauri/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"shell":{"default_permission":{"identifier":"default","description":"This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n","permissions":["allow-open"]},"permissions":{"allow-execute":{"identifier":"allow-execute","description":"Enables the execute command without any pre-configured scope.","commands":{"allow":["execute"],"deny":[]}},"allow-kill":{"identifier":"allow-kill","description":"Enables the kill command without any pre-configured scope.","commands":{"allow":["kill"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-spawn":{"identifier":"allow-spawn","description":"Enables the spawn command without any pre-configured scope.","commands":{"allow":["spawn"],"deny":[]}},"allow-stdin-write":{"identifier":"allow-stdin-write","description":"Enables the stdin_write command without any pre-configured scope.","commands":{"allow":["stdin_write"],"deny":[]}},"deny-execute":{"identifier":"deny-execute","description":"Denies the execute command without any pre-configured scope.","commands":{"allow":[],"deny":["execute"]}},"deny-kill":{"identifier":"deny-kill","description":"Denies the kill command without any pre-configured scope.","commands":{"allow":[],"deny":["kill"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-spawn":{"identifier":"deny-spawn","description":"Denies the spawn command without any pre-configured scope.","commands":{"allow":[],"deny":["spawn"]}},"deny-stdin-write":{"identifier":"deny-stdin-write","description":"Denies the stdin_write command without any pre-configured scope.","commands":{"allow":[],"deny":["stdin_write"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"cmd":{"description":"The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"}},"required":["cmd","name"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"},"sidecar":{"description":"If this command is a sidecar command.","type":"boolean"}},"required":["name","sidecar"],"type":"object"}],"definitions":{"ShellScopeEntryAllowedArg":{"anyOf":[{"description":"A non-configurable argument that is passed to the command in the order it was specified.","type":"string"},{"additionalProperties":false,"description":"A variable that is set while calling the command from the webview API.","properties":{"raw":{"default":false,"description":"Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.","type":"boolean"},"validator":{"description":"[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: ","type":"string"}},"required":["validator"],"type":"object"}],"description":"A command argument allowed to be executed by the webview API."},"ShellScopeEntryAllowedArgs":{"anyOf":[{"description":"Use a simple boolean to allow all or disable all arguments to this command configuration.","type":"boolean"},{"description":"A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.","items":{"$ref":"#/definitions/ShellScopeEntryAllowedArg"},"type":"array"}],"description":"A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration."}},"description":"Shell scope entry.","title":"ShellScopeEntry"}},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file +{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"shell":{"default_permission":{"identifier":"default","description":"This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n","permissions":["allow-open"]},"permissions":{"allow-execute":{"identifier":"allow-execute","description":"Enables the execute command without any pre-configured scope.","commands":{"allow":["execute"],"deny":[]}},"allow-kill":{"identifier":"allow-kill","description":"Enables the kill command without any pre-configured scope.","commands":{"allow":["kill"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-spawn":{"identifier":"allow-spawn","description":"Enables the spawn command without any pre-configured scope.","commands":{"allow":["spawn"],"deny":[]}},"allow-stdin-write":{"identifier":"allow-stdin-write","description":"Enables the stdin_write command without any pre-configured scope.","commands":{"allow":["stdin_write"],"deny":[]}},"deny-execute":{"identifier":"deny-execute","description":"Denies the execute command without any pre-configured scope.","commands":{"allow":[],"deny":["execute"]}},"deny-kill":{"identifier":"deny-kill","description":"Denies the kill command without any pre-configured scope.","commands":{"allow":[],"deny":["kill"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-spawn":{"identifier":"deny-spawn","description":"Denies the spawn command without any pre-configured scope.","commands":{"allow":[],"deny":["spawn"]}},"deny-stdin-write":{"identifier":"deny-stdin-write","description":"Denies the stdin_write command without any pre-configured scope.","commands":{"allow":[],"deny":["stdin_write"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"cmd":{"description":"The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"}},"required":["cmd","name"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"},"sidecar":{"description":"If this command is a sidecar command.","type":"boolean"}},"required":["name","sidecar"],"type":"object"}],"definitions":{"ShellScopeEntryAllowedArg":{"anyOf":[{"description":"A non-configurable argument that is passed to the command in the order it was specified.","type":"string"},{"additionalProperties":false,"description":"A variable that is set while calling the command from the webview API.","properties":{"raw":{"default":false,"description":"Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.","type":"boolean"},"validator":{"description":"[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: ","type":"string"}},"required":["validator"],"type":"object"}],"description":"A command argument allowed to be executed by the webview API."},"ShellScopeEntryAllowedArgs":{"anyOf":[{"description":"Use a simple boolean to allow all or disable all arguments to this command configuration.","type":"boolean"},{"description":"A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.","items":{"$ref":"#/definitions/ShellScopeEntryAllowedArg"},"type":"array"}],"description":"A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration."}},"description":"Shell scope entry.","title":"ShellScopeEntry"}},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file diff --git a/apps/desktop/src-tauri/gen/schemas/desktop-schema.json b/apps/desktop/src-tauri/gen/schemas/desktop-schema.json index 5625606d..ba712940 100644 --- a/apps/desktop/src-tauri/gen/schemas/desktop-schema.json +++ b/apps/desktop/src-tauri/gen/schemas/desktop-schema.json @@ -2426,6 +2426,216 @@ "const": "core:window:deny-unminimize", "markdownDescription": "Denies the unminimize command without any pre-configured scope." }, + { + "description": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`", + "type": "string", + "const": "notification:default", + "markdownDescription": "This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n\n#### This default permission set includes:\n\n- `allow-is-permission-granted`\n- `allow-request-permission`\n- `allow-notify`\n- `allow-register-action-types`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-cancel`\n- `allow-get-pending`\n- `allow-remove-active`\n- `allow-get-active`\n- `allow-check-permissions`\n- `allow-show`\n- `allow-batch`\n- `allow-list-channels`\n- `allow-delete-channel`\n- `allow-create-channel`\n- `allow-permission-state`" + }, + { + "description": "Enables the batch command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-batch", + "markdownDescription": "Enables the batch command without any pre-configured scope." + }, + { + "description": "Enables the cancel command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-cancel", + "markdownDescription": "Enables the cancel command without any pre-configured scope." + }, + { + "description": "Enables the check_permissions command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-check-permissions", + "markdownDescription": "Enables the check_permissions command without any pre-configured scope." + }, + { + "description": "Enables the create_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-create-channel", + "markdownDescription": "Enables the create_channel command without any pre-configured scope." + }, + { + "description": "Enables the delete_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-delete-channel", + "markdownDescription": "Enables the delete_channel command without any pre-configured scope." + }, + { + "description": "Enables the get_active command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-get-active", + "markdownDescription": "Enables the get_active command without any pre-configured scope." + }, + { + "description": "Enables the get_pending command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-get-pending", + "markdownDescription": "Enables the get_pending command without any pre-configured scope." + }, + { + "description": "Enables the is_permission_granted command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-is-permission-granted", + "markdownDescription": "Enables the is_permission_granted command without any pre-configured scope." + }, + { + "description": "Enables the list_channels command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-list-channels", + "markdownDescription": "Enables the list_channels command without any pre-configured scope." + }, + { + "description": "Enables the notify command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-notify", + "markdownDescription": "Enables the notify command without any pre-configured scope." + }, + { + "description": "Enables the permission_state command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-permission-state", + "markdownDescription": "Enables the permission_state command without any pre-configured scope." + }, + { + "description": "Enables the register_action_types command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-register-action-types", + "markdownDescription": "Enables the register_action_types command without any pre-configured scope." + }, + { + "description": "Enables the register_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-register-listener", + "markdownDescription": "Enables the register_listener command without any pre-configured scope." + }, + { + "description": "Enables the remove_active command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-remove-active", + "markdownDescription": "Enables the remove_active command without any pre-configured scope." + }, + { + "description": "Enables the remove_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-remove-listener", + "markdownDescription": "Enables the remove_listener command without any pre-configured scope." + }, + { + "description": "Enables the request_permission command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-request-permission", + "markdownDescription": "Enables the request_permission command without any pre-configured scope." + }, + { + "description": "Enables the show command without any pre-configured scope.", + "type": "string", + "const": "notification:allow-show", + "markdownDescription": "Enables the show command without any pre-configured scope." + }, + { + "description": "Denies the batch command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-batch", + "markdownDescription": "Denies the batch command without any pre-configured scope." + }, + { + "description": "Denies the cancel command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-cancel", + "markdownDescription": "Denies the cancel command without any pre-configured scope." + }, + { + "description": "Denies the check_permissions command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-check-permissions", + "markdownDescription": "Denies the check_permissions command without any pre-configured scope." + }, + { + "description": "Denies the create_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-create-channel", + "markdownDescription": "Denies the create_channel command without any pre-configured scope." + }, + { + "description": "Denies the delete_channel command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-delete-channel", + "markdownDescription": "Denies the delete_channel command without any pre-configured scope." + }, + { + "description": "Denies the get_active command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-get-active", + "markdownDescription": "Denies the get_active command without any pre-configured scope." + }, + { + "description": "Denies the get_pending command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-get-pending", + "markdownDescription": "Denies the get_pending command without any pre-configured scope." + }, + { + "description": "Denies the is_permission_granted command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-is-permission-granted", + "markdownDescription": "Denies the is_permission_granted command without any pre-configured scope." + }, + { + "description": "Denies the list_channels command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-list-channels", + "markdownDescription": "Denies the list_channels command without any pre-configured scope." + }, + { + "description": "Denies the notify command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-notify", + "markdownDescription": "Denies the notify command without any pre-configured scope." + }, + { + "description": "Denies the permission_state command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-permission-state", + "markdownDescription": "Denies the permission_state command without any pre-configured scope." + }, + { + "description": "Denies the register_action_types command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-register-action-types", + "markdownDescription": "Denies the register_action_types command without any pre-configured scope." + }, + { + "description": "Denies the register_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-register-listener", + "markdownDescription": "Denies the register_listener command without any pre-configured scope." + }, + { + "description": "Denies the remove_active command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-remove-active", + "markdownDescription": "Denies the remove_active command without any pre-configured scope." + }, + { + "description": "Denies the remove_listener command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-remove-listener", + "markdownDescription": "Denies the remove_listener command without any pre-configured scope." + }, + { + "description": "Denies the request_permission command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-request-permission", + "markdownDescription": "Denies the request_permission command without any pre-configured scope." + }, + { + "description": "Denies the show command without any pre-configured scope.", + "type": "string", + "const": "notification:deny-show", + "markdownDescription": "Denies the show command without any pre-configured scope." + }, { "description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`", "type": "string", @@ -2491,6 +2701,60 @@ "type": "string", "const": "shell:deny-stdin-write", "markdownDescription": "Denies the stdin_write command without any pre-configured scope." + }, + { + "description": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`", + "type": "string", + "const": "updater:default", + "markdownDescription": "This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n\n#### This default permission set includes:\n\n- `allow-check`\n- `allow-download`\n- `allow-install`\n- `allow-download-and-install`" + }, + { + "description": "Enables the check command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-check", + "markdownDescription": "Enables the check command without any pre-configured scope." + }, + { + "description": "Enables the download command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-download", + "markdownDescription": "Enables the download command without any pre-configured scope." + }, + { + "description": "Enables the download_and_install command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-download-and-install", + "markdownDescription": "Enables the download_and_install command without any pre-configured scope." + }, + { + "description": "Enables the install command without any pre-configured scope.", + "type": "string", + "const": "updater:allow-install", + "markdownDescription": "Enables the install command without any pre-configured scope." + }, + { + "description": "Denies the check command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-check", + "markdownDescription": "Denies the check command without any pre-configured scope." + }, + { + "description": "Denies the download command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-download", + "markdownDescription": "Denies the download command without any pre-configured scope." + }, + { + "description": "Denies the download_and_install command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-download-and-install", + "markdownDescription": "Denies the download_and_install command without any pre-configured scope." + }, + { + "description": "Denies the install command without any pre-configured scope.", + "type": "string", + "const": "updater:deny-install", + "markdownDescription": "Denies the install command without any pre-configured scope." } ] }, diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index 8f38a00e..83eff268 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -39,6 +39,7 @@ use tauri::{Manager, WebviewUrl, WebviewWindowBuilder}; mod updater; mod desktoplog; +mod shell; #[cfg(target_os = "linux")] mod supervisor; @@ -252,13 +253,24 @@ fn pick_port() -> Result { /// launch starts with empty storage, as before). const PREFERRED_PORT: u16 = 47831; +/// Set when the port the person (or the app) wanted was busy: "busy::". The host gets it as STRATA_PORT_NOTICE and tells the +/// person (the chats and settings saved on the page belong to the port, so a different port starts empty) (#3402). +static PORT_NOTICE: std::sync::Mutex> = std::sync::Mutex::new(None); + fn pick_stable_port() -> Result { - match TcpListener::bind(("127.0.0.1", PREFERRED_PORT)) { + // The person may have chosen a port in Settings (shell-prefs.json); otherwise the app's usual one. + let wanted = shell::wanted_port(&shell::read_prefs(), PREFERRED_PORT); + *PORT_NOTICE.lock().unwrap() = None; + match TcpListener::bind(("127.0.0.1", wanted)) { Ok(listener) => { drop(listener); - Ok(PREFERRED_PORT) + Ok(wanted) + } + Err(_) => { + let used = pick_port()?; + *PORT_NOTICE.lock().unwrap() = Some(shell::busy_notice(wanted, used)); + Ok(used) } - Err(_) => pick_port(), } } @@ -469,6 +481,9 @@ fn host_command(res: &Path, port: u16, shutdown_token: &str) -> Result/shell-prefs.json` is written by the App Host when the person changes a setting +//! (`apps/host/server/shell-prefs.mjs`) and read here when Strata starts, before any page exists: +//! +//! { "port": 0 | 1024..65535, "tray": false, "language": "en" } +//! +//! * `port`: the port the window's origin uses. 0 is the default, 47831. When the port is busy the shell takes a free one and tells the +//! host (`STRATA_PORT_NOTICE=busy::`), which shows the person a warning: the chats and settings of the page are kept per +//! port, so a different port starts empty. +//! * `tray`: closing the window hides it and keeps Strata running in the tray (Windows, macOS). The tray menu follows `language`. +//! * `/shell/notify` on the loopback bridge shows a desktop notification (an approval is waiting) whether the window is open or hidden. + +use std::path::PathBuf; + +use serde_json::Value; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Prefs { + pub port: u16, + pub tray: bool, + pub language: String, +} + +impl Default for Prefs { + fn default() -> Self { + Prefs { port: 0, tray: false, language: "en".into() } + } +} + +pub const LANGUAGES: [&str; 8] = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko"]; + +pub fn prefs_path() -> PathBuf { + crate::desktoplog::data_dir().join("shell-prefs.json") +} + +/// The file's text as choices; anything missing or out of range is the default. +pub fn parse_prefs(text: &str) -> Prefs { + let value: Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).unwrap_or(Value::Null); + let port = value.get("port").and_then(Value::as_u64).filter(|p| (1024..=65535).contains(p)).unwrap_or(0) as u16; + let tray = value.get("tray").and_then(Value::as_bool).unwrap_or(false); + let language = value + .get("language") + .and_then(Value::as_str) + .filter(|l| LANGUAGES.contains(l)) + .unwrap_or("en") + .to_string(); + Prefs { port, tray, language } +} + +pub fn read_prefs() -> Prefs { + std::fs::read_to_string(prefs_path()).map(|t| parse_prefs(&t)).unwrap_or_default() +} + +/// The port to ask for: the person's choice, else the app's usual one. +pub fn wanted_port(prefs: &Prefs, usual: u16) -> u16 { + if prefs.port != 0 { prefs.port } else { usual } +} + +/// The notice the host shows when the wanted port was taken. +pub fn busy_notice(wanted: u16, used: u16) -> String { + format!("busy:{wanted}:{used}") +} + +/// `%41%20b` -> "A b" (a query value from the host). Bad escapes are kept as typed. +pub fn percent_decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() { + if let Some(v) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) { + out.push(v); + i += 3; + continue; + } + } + out.push(if bytes[i] == b'+' { b' ' } else { bytes[i] }); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// The value of `key` in the query of a request path (`/shell/notify?title=..&body=..`). +pub fn query_value(path: &str, key: &str) -> Option { + let query = path.split_once('?')?.1; + query.split('&').find_map(|pair| { + let (k, v) = pair.split_once('=')?; + (k == key).then(|| percent_decode(v)) + }) +} + +/// A short single-line text for a notification: no control characters, bounded. +pub fn clean_text(text: &str, max: usize) -> String { + text.chars().filter(|c| !c.is_control()).take(max).collect::().trim().to_string() +} + +/// The tray menu: (open, quit, tooltip), in the app's language. +pub fn tray_labels(language: &str) -> (&'static str, &'static str, &'static str) { + match language { + "zh" => ("打开 Strata", "退出 Strata", "Strata"), + "ja" => ("Strata を開く", "Strata を終了", "Strata"), + "de" => ("Strata öffnen", "Strata beenden", "Strata"), + "es" => ("Abrir Strata", "Salir de Strata", "Strata"), + "ru" => ("Открыть Strata", "Выйти из Strata", "Strata"), + "pt" => ("Abrir o Strata", "Sair do Strata", "Strata"), + "ko" => ("Strata 열기", "Strata 종료", "Strata"), + _ => ("Open Strata", "Quit Strata", "Strata"), + } +} + +#[cfg(not(target_os = "linux"))] +mod native { + use tauri::menu::{Menu, MenuItem}; + use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; + use tauri::{AppHandle, Manager}; + use tauri_plugin_notification::NotificationExt; + + const TRAY_ID: &str = "strata-tray"; + + fn show_main(app: &AppHandle) { + if let Some(window) = app.get_webview_window("main") { + let _ = window.unminimize(); + let _ = window.show(); + let _ = window.set_focus(); + } + } + + /// Hide the window and keep Strata running in the tray (made on the first need, with the menu in the app's language). + pub fn hide_to_tray(app: &AppHandle, language: &str) { + if app.tray_by_id(TRAY_ID).is_none() { + let (open, quit, tip) = super::tray_labels(language); + let built = (|| -> tauri::Result<()> { + let open_item = MenuItem::with_id(app, "open", open, true, None::<&str>)?; + let quit_item = MenuItem::with_id(app, "quit", quit, true, None::<&str>)?; + let menu = Menu::with_items(app, &[&open_item, &quit_item])?; + let mut builder = TrayIconBuilder::with_id(TRAY_ID) + .tooltip(tip) + .menu(&menu) + .show_menu_on_left_click(false) + .on_menu_event(|app, event| match event.id().as_ref() { + "open" => show_main(app), + "quit" => app.exit(0), + _ => {} + }) + .on_tray_icon_event(|tray, event| { + if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event { + show_main(tray.app_handle()); + } + }); + if let Some(icon) = app.default_window_icon() { + builder = builder.icon(icon.clone()); + } + builder.build(app)?; + Ok(()) + })(); + if built.is_err() { + // No tray could be made (a desktop without one): do not hide a window nobody could bring back. + return; + } + } + if let Some(window) = app.get_webview_window("main") { + let _ = window.hide(); + } + } + + pub fn tray_exists(app: &AppHandle) -> bool { + app.tray_by_id(TRAY_ID).is_some() + } + + /// Show a desktop notification; a hidden or minimised window also asks for attention (the taskbar button flashes). + pub fn notify(app: &AppHandle, title: &str, body: &str) -> bool { + if title.is_empty() { + return false; + } + if let Some(window) = app.get_webview_window("main") { + let hidden = !window.is_visible().unwrap_or(true) || window.is_minimized().unwrap_or(false); + if hidden { + let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational)); + } + } + app.notification().builder().title(title).body(body).show().is_ok() + } +} + +#[cfg(not(target_os = "linux"))] +pub use native::{hide_to_tray, notify, tray_exists}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_file_gives_choices_and_anything_wrong_is_the_default() { + assert_eq!(parse_prefs(""), Prefs::default()); + assert_eq!(parse_prefs("{ not json"), Prefs::default()); + let p = parse_prefs(r#"{"port":47900,"tray":true,"language":"de"}"#); + assert_eq!((p.port, p.tray, p.language.as_str()), (47900, true, "de")); + assert_eq!(parse_prefs("\u{feff}{\"port\":47900}").port, 47900); + assert_eq!(parse_prefs(r#"{"port":80}"#).port, 0, "a port below 1024 is not used"); + assert_eq!(parse_prefs(r#"{"port":70000}"#).port, 0); + assert_eq!(parse_prefs(r#"{"port":"47831"}"#).port, 0, "a text is not a number"); + assert_eq!(parse_prefs(r#"{"tray":"yes","language":"xx"}"#), Prefs::default()); + } + + #[test] + fn the_wanted_port_is_the_choice_or_the_usual_one() { + assert_eq!(wanted_port(&Prefs::default(), 47831), 47831); + assert_eq!(wanted_port(&Prefs { port: 47900, ..Prefs::default() }, 47831), 47900); + assert_eq!(busy_notice(47831, 51234), "busy:47831:51234"); + } + + #[test] + fn query_values_are_decoded_and_bounded() { + let path = "/shell/notify?title=Strata%20needs%20your%20answer&body=a%20%26%20b%3F+ok"; + assert_eq!(query_value(path, "title").as_deref(), Some("Strata needs your answer")); + assert_eq!(query_value(path, "body").as_deref(), Some("a & b? ok")); + assert_eq!(query_value(path, "missing"), None); + assert_eq!(query_value("/shell/notify", "title"), None); + assert_eq!(percent_decode("100%"), "100%"); + assert_eq!(percent_decode("%zz%41"), "%zzA"); + assert_eq!(percent_decode("%C3%A4"), "ä"); + assert_eq!(clean_text("a\nb\u{7}c", 10), "abc"); + assert_eq!(clean_text("abcdef", 3), "abc"); + } + + #[test] + fn every_language_has_tray_labels() { + for language in LANGUAGES { + let (open, quit, tip) = tray_labels(language); + assert!(!open.is_empty() && !quit.is_empty() && !tip.is_empty(), "{language}"); + if language != "en" { + assert_ne!(open, tray_labels("en").0, "{language}"); + } + } + assert_eq!(tray_labels("xx"), tray_labels("en")); + } +} diff --git a/apps/desktop/src-tauri/src/updater.rs b/apps/desktop/src-tauri/src/updater.rs index dd0a1ced..889e7109 100644 --- a/apps/desktop/src-tauri/src/updater.rs +++ b/apps/desktop/src-tauri/src/updater.rs @@ -210,6 +210,16 @@ fn handle(mut stream: TcpStream, app: &AppHandle, token: &str, progress: &Arc respond(&mut stream, "200 OK", &progress.lock().unwrap().json()), + // The host asks for a desktop notification (an approval is waiting): title and body are in the query, bounded and cleaned here. + ("POST", p) if p.starts_with("/shell/notify") => { + let title = crate::shell::clean_text(&crate::shell::query_value(p, "title").unwrap_or_default(), 120); + let body = crate::shell::clean_text(&crate::shell::query_value(p, "body").unwrap_or_default(), 300); + #[cfg(not(target_os = "linux"))] + let shown = crate::shell::notify(app, &title, &body); + #[cfg(target_os = "linux")] + let shown = false; + respond(&mut stream, "200 OK", &serde_json::json!({ "shown": shown })) + } _ => respond(&mut stream, "404 Not Found", &serde_json::json!({ "error": "unknown route" })), } } diff --git a/apps/host/README.md b/apps/host/README.md index 25c8f531..182a525b 100644 --- a/apps/host/README.md +++ b/apps/host/README.md @@ -10,3 +10,15 @@ npm run preview:ui The built UI is included. To rebuild after source edits, run `npm run build`. `preview:ui` uses isolated simulated data; `npm run dev` connects the normal host. The previous project README is retained in [docs/README-historical.md](docs/README-historical.md). It contains older implementation status and is historical reference. + +## Languages + +The app speaks English, Chinese, Japanese, German, French, Spanish, Russian, Portuguese and Korean. The English text is the key: `src/locales/en.json` +(with `fix-en.json`, `tune-en.json` and `tools-en.json`) holds every string, and each language has the same four files (`fr.json`, `fix-fr.json`, ...). + +- **A new string.** Write it with `tr("...")`, then add it to the English catalog (`node scripts/append-localization.mjs`, or the next `fx` number in + `scripts/make-fix-locales.py`). The language tests fail until every language has it. +- **French.** `python scripts/fr_sync.py missing todo.tsv` lists the English strings that have no French yet, one per line (`id`, a tab, the text). + Translate the second column ("vous", short plain words, one next step; a lone `=` keeps the English), then `python scripts/fr_sync.py apply todo.tsv` merges it + (it also sets the French spacing before `: ; ? !` and the typographic apostrophe) and `python scripts/fr_sync.py check` confirms nothing is missing. +- **Screenshots in a language.** `npm run build`, then `node scripts/language-shots.mjs fr models settings setup` (hermetic preview host, scratch profile, headless Chrome). diff --git a/apps/host/public/strata-done-sound.wav b/apps/host/public/strata-done-sound.wav new file mode 100644 index 00000000..ec3173e3 Binary files /dev/null and b/apps/host/public/strata-done-sound.wav differ diff --git a/apps/host/scripts/fr_sync.py b/apps/host/scripts/fr_sync.py new file mode 100644 index 00000000..90bf8970 --- /dev/null +++ b/apps/host/scripts/fr_sync.py @@ -0,0 +1,156 @@ +"""French (fr) catalog tooling for the desktop app (#3970). + +The French texts live in src/locales/fr.json, fix-fr.json, tune-fr.json and tools-fr.json, next to the other languages. +They are edited by hand (they are the translations, not generated), so a string added to an English catalog later has no +French yet. This script lists and merges those. From apps/host: + + python scripts/fr_sync.py missing [out.tsv] write every English string that has no French yet + python scripts/fr_sync.py apply done.tsv merge translations, rewrite the four fr files in English key order + python scripts/fr_sync.py check exit 1 if a French string is missing, empty or breaks a placeholder / tag + +The TSV has one string per line: . In the text, a newline is written \\n and a backslash \\\\. +In the "done" file a lone = means "keep the English text as it is" (class names, product names, file names). +The id prefix picks the file: s0001 -> fr.json, fx01 -> fix-fr.json, tune01 -> tune-fr.json, tl01 -> tools-fr.json. +Use "vous", plain short words, a next step, and a no-break space (U+00A0) before : ; ? ! and inside guillemets. +""" +import json +import re +import sys +from pathlib import Path + +LOCALES = Path(__file__).resolve().parent.parent / "src" / "locales" +PAIRS = [("en.json", "fr.json"), ("fix-en.json", "fix-fr.json"), ("tune-en.json", "tune-fr.json"), ("tools-en.json", "tools-fr.json")] +SLOT = re.compile(r"\{\d+\}") +TAG = re.compile(r"]*>") + + +def load(name): + path = LOCALES / name + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + + +def file_of(identifier): + for en_name, fr_name in PAIRS: + if identifier in load(en_name): + return fr_name + raise SystemExit(f"unknown id {identifier}: it is in no English catalog") + + +def escape(text): + return text.replace("\\", "\\\\").replace("\n", "\\n") + + +def unescape(text): + out, i = [], 0 + while i < len(text): + if text[i] == "\\" and i + 1 < len(text): + out.append({"n": "\n", "\\": "\\"}.get(text[i + 1], text[i + 1])) + i += 2 + else: + out.append(text[i]) + i += 1 + return "".join(out) + + +NBSP = " " + + +def typography(text): + """French spacing and apostrophes, applied to every translated (not kept) string. + l'image -> l'image with a typographic apostrophe (also before a {0} slot); a no-break space before : ; ? ! % and inside the guillemets.""" + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + text = re.sub("« ?", "«" + NBSP, text) + text = re.sub(" ?»", NBSP + "»", text) + return text + + +def problems(identifier, source, text): + found = [] + if not text.strip(): + found.append("empty") + expected = [slot for slot in SLOT.findall(source) if not (identifier == "s2463" and slot == "{1}")] # the tests allow this one to drop {1} (the plural suffix) + if sorted(expected) != sorted(SLOT.findall(text)): + found.append("placeholders differ") + if sorted(TAG.findall(source)) != sorted(TAG.findall(text)): + found.append("markup differs") + return found + + +def missing(): + todo = {} + for en_name, fr_name in PAIRS: + en, fr = load(en_name), load(fr_name) + for identifier, text in en.items(): + if identifier not in fr: + todo[identifier] = text + return todo + + +def main(argv): + command = argv[1] if len(argv) > 1 else "" + if command == "missing": + todo = missing() + lines = [f"{identifier}\t{escape(text)}" for identifier, text in todo.items()] + if len(argv) > 2: + Path(argv[2]).write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8") + print(f"{len(lines)} strings without French written to {argv[2]}") + else: + print("\n".join(lines)) + print(f"{len(lines)} strings without French", file=sys.stderr) + return 0 + if command == "apply" and len(argv) > 2: + incoming = {} + for number, line in enumerate(Path(argv[2]).read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + if "\t" not in line: + raise SystemExit(f"{argv[2]}:{number}: no tab") + identifier, text = line.split("\t", 1) + incoming[identifier.strip()] = text + bad = 0 + for en_name, fr_name in PAIRS: + en, fr = load(en_name), load(fr_name) + changed = False + for identifier, source in en.items(): + if identifier in incoming: + text = source if incoming[identifier] == "=" else typography(unescape(incoming[identifier])) + for why in problems(identifier, source, text): + print(f"{identifier}: {why}: {source!r} -> {text!r}") + bad += 1 + fr[identifier] = text + changed = True + if changed: + ordered = {identifier: fr[identifier] for identifier in en if identifier in fr} + (LOCALES / fr_name).write_text(json.dumps(ordered, ensure_ascii=False, indent=1 if en_name != "en.json" else 2) + "\n", encoding="utf-8") + unknown = [identifier for identifier in incoming if not any(identifier in load(en_name) for en_name, _ in PAIRS)] + for identifier in unknown: + print(f"{identifier}: not in any English catalog") + bad += 1 + print(f"applied {len(incoming)} strings, {bad} problems") + return 1 if bad else 0 + if command == "check": + bad = 0 + for en_name, fr_name in PAIRS: + en, fr = load(en_name), load(fr_name) + for identifier, source in en.items(): + if identifier not in fr: + print(f"{fr_name}: {identifier} has no French yet: {source!r}") + bad += 1 + continue + for why in problems(identifier, source, fr[identifier]): + print(f"{fr_name}: {identifier}: {why}") + bad += 1 + for identifier in fr: + if identifier not in en: + print(f"{fr_name}: {identifier} is not in {en_name}") + bad += 1 + print("French catalogs complete" if not bad else f"{bad} problems") + return 1 if bad else 0 + print(__doc__) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/apps/host/scripts/language-shots.mjs b/apps/host/scripts/language-shots.mjs new file mode 100644 index 00000000..4a371007 --- /dev/null +++ b/apps/host/scripts/language-shots.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +/** + * Screenshots of the app screens in one interface language, from a hermetic preview host (simulated hardware and models, + * scratch profile, no engine, no weights). The browser is a throw-away headless Chrome profile. + * + * node scripts/language-shots.mjs [route ...] (needs `npm run build` first) + * example: node scripts/language-shots.mjs fr C:/Users/me/Desktop/fr-screens models settings setup + * + * Env: CHROME (path to Chrome/Edge), WIDTH (default 1280), HEIGHT (default 800). + */ +import { spawn } from 'node:child_process'; +import { chromium } from 'playwright-core'; +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const [, , language = 'fr', outDir = 'language-shots', ...routes] = process.argv; +const screens = routes.length ? routes : ['models', 'settings', 'setup']; +if (!existsSync(join(root, 'dist/index.html'))) { console.error('Run npm run build first.'); process.exit(1); } +const chrome = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync); +if (!chrome) { console.error('No Chrome or Edge found; set CHROME.'); process.exit(1); } + +const home = mkdtempSync(join(tmpdir(), 'strata-language-shots-')); +const hostPort = 8830 + Math.floor(Math.random() * 40), webPort = hostPort + 100; +const scratch = { STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_WORKSPACE: home, STRATA_REAL_ENGINE: '0', STRATA_NATIVE_REPO: join(home, 'no-native-installation'), + STRATA_SETTINGS_FILE: join(home, 'app-settings.json'), STRATA_COMPONENTS_DIR: join(home, 'components'), LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'), + XDG_DATA_HOME: join(home, 'xdg-data'), XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config'), STRATA_PORT: String(hostPort) }; +const children = []; +const run = (args, extra = {}) => { const child = spawn(process.execPath, args, { cwd: root, env: { ...process.env, ...scratch, ...extra }, stdio: 'ignore' }); children.push(child); return child; }; +const stop = () => { for (const child of children) { try { child.kill(); } catch {} } try { rmSync(home, { recursive: true, force: true }); } catch {} }; +process.on('exit', stop); + +run(['server/index.mjs']); +for (let attempt = 0; ; attempt++) { + try { if ((await fetch(`http://127.0.0.1:${hostPort}/api/health`)).ok) break; } catch {} + if (attempt > 200) { console.error('The preview host did not start.'); process.exit(1); } + await new Promise(done => setTimeout(done, 150)); +} +run(['tests/fixtures/onboarding-ui-host.mjs'], { STRATA_UI_PREVIEW: '1', STRATA_ONBOARDING_UPSTREAM: `http://127.0.0.1:${hostPort}`, STRATA_ONBOARDING_PORT: String(webPort), STRATA_ONBOARDING_START: 'ready', STRATA_ONBOARDING_SCENARIO: 'telemetry', STRATA_ONBOARDING_PREVIEW: '1' }); +for (let attempt = 0; ; attempt++) { + try { if ((await fetch(`http://127.0.0.1:${webPort}/`)).ok) break; } catch {} + if (attempt > 200) { console.error('The preview page did not start.'); process.exit(1); } + await new Promise(done => setTimeout(done, 150)); +} + +mkdirSync(resolve(outDir), { recursive: true }); +const browser = await chromium.launch({ executablePath: chrome, headless: true, args: ['--no-sandbox', '--disable-gpu', '--force-device-scale-factor=1'] }); +const page = await browser.newPage({ viewport: { width: Number(process.env.WIDTH ?? 1280), height: Number(process.env.HEIGHT ?? 800) }, deviceScaleFactor: 1 }); +await page.addInitScript(code => { try { localStorage.setItem('strata.prefs.v2', JSON.stringify({ language: code, onboardingSeen: true })); } catch {} }, language); +const problems = []; +page.on('pageerror', error => problems.push(`pageerror: ${error.message}`)); +for (const screen of screens) { + await page.goto(`http://127.0.0.1:${webPort}/#/${screen}`, { waitUntil: 'load' }); + await page.reload({ waitUntil: 'load' }); + await page.waitForTimeout(2500); + const file = join(resolve(outDir), `${language}-${screen}.png`); + await page.screenshot({ path: file }); + console.log(`${screen}: ${file} (lang=${await page.evaluate(() => document.documentElement.lang)})`); +} +await browser.close(); +if (problems.length) console.log(problems.join('\n')); +stop(); +process.exit(0); diff --git a/apps/host/scripts/make-gh-locales.py b/apps/host/scripts/make-gh-locales.py new file mode 100644 index 00000000..41898d25 --- /dev/null +++ b/apps/host/scripts/make-gh-locales.py @@ -0,0 +1,365 @@ +"""Writes src/locales/gh-.json: the interface strings of the 0.2.7 GitHub items done in f-027-gh-app (the Monitor's Power card #3628, +approval notifications and the tray #3477, the finished-task sound #3586, the pinned port #3402, the interface size #3970). +Run from apps/host: python scripts/make-gh-locales.py +The keys are gh01.. in this order; gh-en.json is the English source. Placeholders ({0}, {1}) must be kept in every language. +A separate file keeps this work from colliding with the other catalogs (the same reason tune-, tools- and fix- exist).""" +import json +import re +from pathlib import Path + +EN = [ + "Energy since start", + "Cost since start", + "GPU fan", + "GPU clock", + "CPU temperature", + "SSD temperature", + "Electricity price", + "Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.", + "Price per kWh", + "Sound when work finishes", + "Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.", + "Play sound", + "Notify me when Strata needs an answer", + "In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.", + "Strata needs your answer", + "The assistant wants to use {0}. Open Strata to approve or deny.", + "a tool", + "Minimise to tray", + "Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.", + "App port", + "The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.", + "Port (empty = automatic)", + "Using port {0} now.", + "Strata could not use its port", + "Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.", + "Choose a port between 1024 and 65535, or leave it empty.", + "Makes all text, buttons and menus in Strata larger or smaller.", + "Energy and temperature readings", + "per kWh, in {0}", + "per kWh", + "Change currency", + "Automatic ({0})", + "Currency", + "less than {0}", +] + +T = { +"zh": [ + "启动以来的能耗", + "启动以来的费用", + "GPU 风扇", + "GPU 频率", + "CPU 温度", + "SSD 温度", + "电价", + "每千瓦时的价格。监控页会据此显示 Strata 启动以来显卡用电的费用。留空则不显示费用。", + "每千瓦时价格", + "工作完成时的提示音", + "回答或耗时较长的任务完成时,或 Strata 在后台时,播放一段简短的提示音。", + "播放提示音", + "Strata 需要您答复时通知我", + "在手动模式下,当助手等待您批准而 Strata 在后台时,显示桌面通知。", + "Strata 需要您的答复", + "助手想使用 {0}。打开 Strata 以批准或拒绝。", + "一个工具", + "最小化到托盘", + "关闭窗口后,Strata 会继续在托盘(时钟旁边)运行。要停止它,请在托盘菜单中选择“退出”。下次启动 Strata 时生效。", + "应用端口", + "Strata 窗口和本地地址使用的端口。留空则由 Strata 自行选择(空闲时为 47831)。下次启动 Strata 时生效。", + "端口(留空 = 自动)", + "当前使用端口 {0}。", + "Strata 无法使用它的端口", + "端口 {0} 已被其他程序占用,因此 Strata 改用端口 {1} 启动。在端口 {0} 上保存的聊天和设置在 Strata 能再次使用该端口之前不会显示。请关闭其他程序并重新启动 Strata。", + "请选择 1024 到 65535 之间的端口,或留空。", + "让 Strata 中的所有文字、按钮和菜单变大或变小。", + "能耗和温度读数", + "每千瓦时,币种 {0}", + "每千瓦时", + "更改货币", + "自动({0})", + "货币", + "不足 {0}", +], +"ja": [ + "起動後の消費電力量", + "起動後の電気代", + "GPU ファン", + "GPU クロック", + "CPU 温度", + "SSD 温度", + "電気料金", + "1キロワット時あたりの料金です。モニターに、Strata の起動後にグラフィックスカードが使った電気代が表示されます。空欄のままなら電気代は表示されません。", + "1 kWh あたりの料金", + "作業完了時の音", + "回答や時間のかかった作業が終わったとき、または Strata がバックグラウンドにあるときに、短い音を鳴らします。", + "音を鳴らす", + "Strata の返答が必要なときに通知する", + "手動モードで、アシスタントが承認を待っていて Strata がバックグラウンドにあるときに、デスクトップ通知を表示します。", + "Strata があなたの返答を待っています", + "アシスタントが {0} を使おうとしています。Strata を開いて承認または拒否してください。", + "ツール", + "トレイに最小化", + "ウィンドウを閉じても、Strata は時計の横のトレイで動き続けます。止めるには、トレイのメニューで「終了」を選びます。次に Strata を起動したときから有効になります。", + "アプリのポート", + "Strata のウィンドウとローカルアドレスが使うポートです。空欄なら Strata が選びます(空いていれば 47831)。次に Strata を起動したときから有効になります。", + "ポート(空欄 = 自動)", + "現在のポートは {0} です。", + "Strata は指定のポートを使えませんでした", + "ポート {0} は別のプログラムが使っているため、Strata はポート {1} で起動しました。ポート {0} に保存されたチャットと設定は、Strata が再びそのポートを使えるようになるまで表示されません。他のプログラムを閉じて Strata を再起動してください。", + "1024 から 65535 の間のポートを選ぶか、空欄にしてください。", + "Strata のすべての文字、ボタン、メニューを大きくしたり小さくしたりします。", + "消費電力量と温度の値", + "1 kWh あたり、通貨は {0}", + "1 kWh あたり", + "通貨を変更", + "自動({0})", + "通貨", + "{0} 未満", +], +"de": [ + "Energie seit dem Start", + "Kosten seit dem Start", + "GPU-Lüfter", + "GPU-Takt", + "CPU-Temperatur", + "SSD-Temperatur", + "Strompreis", + "Preis einer Kilowattstunde. Der Monitor zeigt dann, was Ihre Grafikkarte seit dem Start von Strata gekostet hat. Leer lassen, um die Kosten auszublenden.", + "Preis pro kWh", + "Ton, wenn Arbeit fertig ist", + "Spielt einen kurzen Ton, wenn eine Antwort oder Aufgabe, die länger gedauert hat, fertig ist oder wenn Strata im Hintergrund läuft.", + "Ton abspielen", + "Benachrichtigen, wenn Strata eine Antwort braucht", + "Zeigt im manuellen Modus eine Desktop-Benachrichtigung, wenn der Assistent auf Ihre Freigabe wartet und Strata im Hintergrund läuft.", + "Strata braucht Ihre Antwort", + "Der Assistent möchte {0} verwenden. Öffnen Sie Strata, um zu erlauben oder abzulehnen.", + "ein Werkzeug", + "In den Infobereich minimieren", + "Beim Schließen des Fensters läuft Strata im Infobereich neben der Uhr weiter. Wählen Sie im Menü des Symbols „Beenden“, um es zu stoppen. Gilt ab dem nächsten Start von Strata.", + "App-Port", + "Der Port, den das Fenster und die lokale Adresse von Strata verwenden. Leer lassen, damit Strata ihn wählt (47831, wenn frei). Gilt ab dem nächsten Start von Strata.", + "Port (leer = automatisch)", + "Aktuell wird Port {0} verwendet.", + "Strata konnte seinen Port nicht verwenden", + "Port {0} wird von einem anderen Programm verwendet, daher wurde Strata auf Port {1} gestartet. Unter Port {0} gespeicherte Chats und Einstellungen werden nicht angezeigt, bis Strata ihn wieder verwenden kann. Schließen Sie das andere Programm und starten Sie Strata neu.", + "Wählen Sie einen Port zwischen 1024 und 65535 oder lassen Sie das Feld leer.", + "Macht alle Texte, Schaltflächen und Menüs in Strata größer oder kleiner.", + "Energie- und Temperaturwerte", + "pro kWh, in {0}", + "pro kWh", + "Währung ändern", + "Automatisch ({0})", + "Währung", + "weniger als {0}", +], +"es": [ + "Energía desde el inicio", + "Coste desde el inicio", + "Ventilador de la GPU", + "Reloj de la GPU", + "Temperatura de la CPU", + "Temperatura del SSD", + "Precio de la electricidad", + "Precio de un kilovatio hora. El Monitor mostrará entonces lo que ha costado tu tarjeta gráfica desde que se inició Strata. Déjalo vacío para ocultar el coste.", + "Precio por kWh", + "Sonido al terminar el trabajo", + "Reproduce un sonido breve cuando termina una respuesta o tarea que tardó un rato, o cuando Strata está en segundo plano.", + "Reproducir sonido", + "Avisarme cuando Strata necesite una respuesta", + "En el modo manual, muestra una notificación de escritorio cuando el asistente espera tu aprobación y Strata está en segundo plano.", + "Strata necesita tu respuesta", + "El asistente quiere usar {0}. Abre Strata para aprobar o denegar.", + "una herramienta", + "Minimizar a la bandeja", + "Al cerrar la ventana, Strata sigue funcionando en la bandeja, junto al reloj. Elige Salir en el menú de la bandeja para detenerlo. Se aplica la próxima vez que se inicie Strata.", + "Puerto de la aplicación", + "El puerto que usan la ventana y la dirección local de Strata. Déjalo vacío para que Strata elija (47831 si está libre). Se aplica la próxima vez que se inicie Strata.", + "Puerto (vacío = automático)", + "Ahora se usa el puerto {0}.", + "Strata no pudo usar su puerto", + "El puerto {0} lo usa otro programa, así que Strata se inició en el puerto {1}. Los chats y ajustes guardados en el puerto {0} no se muestran hasta que Strata pueda volver a usarlo. Cierra el otro programa y reinicia Strata.", + "Elige un puerto entre 1024 y 65535, o déjalo vacío.", + "Hace más grandes o más pequeños todos los textos, botones y menús de Strata.", + "Lecturas de energía y temperatura", + "por kWh, en {0}", + "por kWh", + "Cambiar moneda", + "Automática ({0})", + "Moneda", + "menos de {0}", +], +"ru": [ + "Энергия с запуска", + "Стоимость с запуска", + "Вентилятор GPU", + "Частота GPU", + "Температура CPU", + "Температура SSD", + "Цена электричества", + "Цена одного киловатт-часа. Тогда монитор покажет, во сколько видеокарта обошлась с запуска Strata. Оставьте поле пустым, чтобы скрыть стоимость.", + "Цена за кВт·ч", + "Звук по окончании работы", + "Проигрывает короткий звук, когда закончился долгий ответ или задача, а также когда Strata работает в фоне.", + "Проиграть звук", + "Уведомлять, когда Strata нужен ответ", + "В ручном режиме показывает уведомление на рабочем столе, когда помощник ждёт вашего подтверждения, а Strata работает в фоне.", + "Strata нужен ваш ответ", + "Помощник хочет использовать {0}. Откройте Strata, чтобы разрешить или отклонить.", + "инструмент", + "Сворачивать в трей", + "При закрытии окна Strata продолжает работать в трее рядом с часами. Чтобы остановить её, выберите «Выход» в меню значка. Действует со следующего запуска Strata.", + "Порт приложения", + "Порт, который используют окно и локальный адрес Strata. Оставьте поле пустым, чтобы Strata выбрала сама (47831, если свободен). Действует со следующего запуска Strata.", + "Порт (пусто = автоматически)", + "Сейчас используется порт {0}.", + "Strata не смогла использовать свой порт", + "Порт {0} занят другой программой, поэтому Strata запустилась на порту {1}. Чаты и настройки, сохранённые на порту {0}, не показываются, пока Strata не сможет снова его использовать. Закройте другую программу и перезапустите Strata.", + "Выберите порт от 1024 до 65535 или оставьте поле пустым.", + "Увеличивает или уменьшает весь текст, кнопки и меню в Strata.", + "Показания энергии и температуры", + "за кВт·ч, в валюте {0}", + "за кВт·ч", + "Сменить валюту", + "Автоматически ({0})", + "Валюта", + "меньше {0}", +], +"pt": [ + "Energia desde o início", + "Custo desde o início", + "Ventoinha da GPU", + "Clock da GPU", + "Temperatura da CPU", + "Temperatura do SSD", + "Preço da eletricidade", + "Preço de um quilowatt-hora. O Monitor passa a mostrar quanto a sua placa de vídeo custou desde que o Strata iniciou. Deixe vazio para ocultar o custo.", + "Preço por kWh", + "Som ao terminar o trabalho", + "Toca um som curto quando uma resposta ou tarefa que demorou termina, ou quando o Strata está em segundo plano.", + "Tocar som", + "Avisar quando o Strata precisar de uma resposta", + "No modo manual, mostra uma notificação na área de trabalho quando o assistente espera sua aprovação e o Strata está em segundo plano.", + "O Strata precisa da sua resposta", + "O assistente quer usar {0}. Abra o Strata para aprovar ou negar.", + "uma ferramenta", + "Minimizar para a bandeja", + "Ao fechar a janela, o Strata continua em execução na bandeja, ao lado do relógio. Escolha Sair no menu da bandeja para encerrá-lo. Vale a partir da próxima vez que o Strata iniciar.", + "Porta do aplicativo", + "A porta usada pela janela e pelo endereço local do Strata. Deixe vazio para o Strata escolher (47831 quando estiver livre). Vale a partir da próxima vez que o Strata iniciar.", + "Porta (vazio = automático)", + "Usando a porta {0} agora.", + "O Strata não conseguiu usar a sua porta", + "A porta {0} está em uso por outro programa, então o Strata iniciou na porta {1}. Os chats e as configurações salvos na porta {0} não aparecem até o Strata poder usá-la de novo. Feche o outro programa e reinicie o Strata.", + "Escolha uma porta entre 1024 e 65535, ou deixe vazio.", + "Deixa todos os textos, botões e menus do Strata maiores ou menores.", + "Leituras de energia e temperatura", + "por kWh, em {0}", + "por kWh", + "Alterar moeda", + "Automática ({0})", + "Moeda", + "menos de {0}", +], +"ko": [ + "시작 이후 에너지", + "시작 이후 비용", + "GPU 팬", + "GPU 클럭", + "CPU 온도", + "SSD 온도", + "전기 요금", + "1킬로와트시의 요금입니다. 모니터에 Strata를 시작한 뒤 그래픽 카드에 든 전기 요금이 표시됩니다. 비워 두면 비용을 표시하지 않습니다.", + "kWh당 요금", + "작업이 끝났을 때 소리", + "답변이나 오래 걸린 작업이 끝났을 때, 또는 Strata가 백그라운드에 있을 때 짧은 소리를 재생합니다.", + "소리 재생", + "Strata가 답을 필요로 할 때 알림", + "수동 모드에서 어시스턴트가 승인을 기다리고 Strata가 백그라운드에 있을 때 데스크톱 알림을 표시합니다.", + "Strata가 답을 기다리고 있습니다", + "어시스턴트가 {0}을(를) 사용하려고 합니다. Strata를 열어 승인하거나 거부하세요.", + "도구", + "트레이로 최소화", + "창을 닫아도 Strata는 시계 옆 트레이에서 계속 실행됩니다. 끝내려면 트레이 메뉴에서 '종료'를 선택하세요. 다음에 Strata를 시작할 때부터 적용됩니다.", + "앱 포트", + "Strata의 창과 로컬 주소가 사용하는 포트입니다. 비워 두면 Strata가 고릅니다(비어 있으면 47831). 다음에 Strata를 시작할 때부터 적용됩니다.", + "포트(비움 = 자동)", + "지금은 포트 {0}을(를) 사용 중입니다.", + "Strata가 지정한 포트를 사용할 수 없었습니다", + "포트 {0}을(를) 다른 프로그램이 사용 중이어서 Strata는 포트 {1}에서 시작했습니다. 포트 {0}에 저장된 채팅과 설정은 Strata가 다시 그 포트를 쓸 수 있을 때까지 표시되지 않습니다. 다른 프로그램을 닫고 Strata를 다시 시작하세요.", + "1024에서 65535 사이의 포트를 고르거나 비워 두세요.", + "Strata의 모든 글자, 버튼, 메뉴를 더 크게 또는 더 작게 만듭니다.", + "에너지 및 온도 측정값", + "kWh당, 통화 {0}", + "kWh당", + "통화 변경", + "자동({0})", + "통화", + "{0} 미만", +], +"fr": [ + "Énergie depuis le démarrage", + "Coût depuis le démarrage", + "Ventilateur du GPU", + "Fréquence du GPU", + "Température du CPU", + "Température du SSD", + "Prix de l'électricité", + "Prix d'un kilowattheure. Le Moniteur affiche alors ce que votre carte graphique a coûté depuis le démarrage de Strata. Laissez vide pour masquer le coût.", + "Prix par kWh", + "Son à la fin du travail", + "Joue un court son quand une réponse ou une tâche qui a pris du temps est terminée, ou quand Strata est en arrière-plan.", + "Jouer le son", + "Me prévenir quand Strata a besoin d'une réponse", + "En mode manuel, affiche une notification sur le bureau quand l'assistant attend votre accord et que Strata est en arrière-plan.", + "Strata a besoin de votre réponse", + "L'assistant veut utiliser {0}. Ouvrez Strata pour accepter ou refuser.", + "un outil", + "Réduire dans la zone de notification", + "Fermer la fenêtre garde Strata actif dans la zone de notification, près de l'horloge. Choisissez Quitter dans le menu de l'icône pour l'arrêter. S'applique au prochain démarrage de Strata.", + "Port de l'application", + "Le port que la fenêtre et l'adresse locale de Strata utilisent. Laissez vide pour que Strata choisisse (47831 s'il est libre). S'applique au prochain démarrage de Strata.", + "Port (vide = automatique)", + "Port {0} utilisé en ce moment.", + "Strata n'a pas pu utiliser son port", + "Le port {0} est utilisé par un autre programme, donc Strata a démarré sur le port {1}. Les conversations et réglages enregistrés sur le port {0} ne s'affichent pas tant que Strata ne peut pas le réutiliser. Fermez l'autre programme et relancez Strata.", + "Choisissez un port entre 1024 et 65535, ou laissez vide.", + "Agrandit ou réduit tous les textes, boutons et menus de Strata.", + "Relevés d'énergie et de température", + "par kWh, en {0}", + "par kWh", + "Changer de devise", + "Automatique ({0})", + "Devise", + "moins de {0}", +], +} + +here = Path(__file__).resolve().parent.parent / "src" / "locales" + + +NBSP = "\u00a0" + + +def french(text): + """The same French spacing as scripts/fr_sync.py: a typographic apostrophe, a no-break space before : ; ? ! % and inside the guillemets.""" + text = re.sub(r"(?<=[A-Za-z\u00c0-\u017f])'(?=[A-Za-z\u00c0-\u017f{])", "\u2019", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + text = re.sub(r"(?<=[\d}]) %", NBSP + "%", text) + return text + + +def write(lang, values): + assert len(values) == len(EN), (lang, len(values), len(EN)) + for source, text in zip(EN, values): + assert sorted(re.findall(r"\{\d+\}", source)) == sorted(re.findall(r"\{\d+\}", text)), (lang, source, text) + if lang == "fr": + values = [french(v) for v in values] + data = {f"gh{i + 1:02d}": text for i, text in enumerate(values)} + (here / f"gh-{lang}.json").write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + + +write("en", EN) +for lang, values in T.items(): + write(lang, values) +print("written", len(EN), "strings in", len(T) + 1, "languages") diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index b05bebcf..11c3279b 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -61,7 +61,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha | Bypass | `strata-bypass` | `danger-full-access` | `never` | Full access without prompts, as before. | - Manual relies on the gate, so a Manual turn does not start unless the bridge has confirmed the gate is loaded (`/strata-gate` command): without it Manual would be an open sandbox that nobody asks about. -- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked; MCP and unknown tools ask. +- The gate listens to `tools/pre-execute` (the seam the Harness's own Auto-review layer uses) and returns an `ask` decision; the Harness's approval service then asks, runs the tool only after `allowed-once`, and records the answer. Read-only tools and a short allowlist of look-only shell commands (Get-ChildItem, git status, ...) run unasked, each only with the options listed for it in `strata-gate.mjs` (an unknown option, or one that writes, runs a program, sets something or never ends, asks); MCP and unknown tools ask. - Web search and web pages (`web_search`, `web_fetch`) ask once per chat in Manual, not once per call. The gate asks through the approval service itself (`webDecision`: "The assistant wants to search the web for: ... Search words go to ." / "... open the web page ..."), remembers a yes for the chat (a helper agent shares its chat's answer, and two searches started together share one card), and on a no gives the model `WEB_REFUSAL` ("The person did not allow web access ... Go on without it and say so."). Plan and Bypass are unchanged. Settings -> Tools has a switch, "Let the assistant search the web without asking" (off by default, `webWithoutAsking` in `tools-settings.mjs`, passed to the gate as `config.web.skipAsk`), that skips the question in Manual. A scheduled task has nobody at the card, so its web call is answered no unless that switch is on. Tests: `tests/web-ask.test.mjs`. - The mode is read once per turn; an unknown or missing value is Manual. @@ -93,6 +93,13 @@ What the person chose is saved by `tools-settings.mjs` (inside the host's settin ## Thinking and the output budget +The Harness staging script (`apps/desktop/scripts/stage-harness.mjs`) applies Strata's guarded pi-ai 1.1.0 patch to its staged copy +(`harness-budget.mjs`, #3684): below 64K the context safety room is at most `min(4096, floor(contextWindow / 16))` and never more +than half the estimated remaining room, so an 8K window keeps output room after a tool result instead of ending with a one-token +cap. The caller's output cap and the one-token floor remain; windows of 64K or more keep the previous calculation. `BUNDLE.json.patches` +records the patch identity, the dependency version and the before/after SHA-256. Unknown dependency bytes stop staging for review. +Source and already-installed Harness copies are not changed. + - A local route is reasoning-capable (`reasoning: true`) with `compat.thinkingFormat: 'chat-template'`: the request carries `chat_template_kwargs {enable_thinking, reasoning_effort}`, which the Strata server reads (a top-level `enable_thinking` is ignored by it, which is why pi-ai's `qwen` format left the model thinking). The chat's Reasoning menu travels as `thinking` in the stream body; the bridge sends it with `session/selectModel` (`reasoningEffort`) whenever the model or the level changed; a level a route does not have is dropped (never an error). API routes keep the provider default (the menu is disabled for them in the UI). - `localOutputBudget(context)` is 30 percent of the window, at least 4096 and at most 32768 (9,830 tokens at 32K, 19,660 at 64K). The Harness's automatic compaction reads it as the room a reply reserves. pi-ai sends the window minus the prompt. App-loaded models get `fit_max_tokens: true` so the engine clamps instead of answering 400. Sampling is not set here: the Harness sends none, so the server's own defaults apply. diff --git a/apps/host/server/agent/context-fit.mjs b/apps/host/server/agent/context-fit.mjs index 0abcb08a..7bc12e79 100644 --- a/apps/host/server/agent/context-fit.mjs +++ b/apps/host/server/agent/context-fit.mjs @@ -58,7 +58,7 @@ export async function countTokens({ baseUrl, key = '', model = '', text, fetchIm } catch { return null; } } -/** The plain sentences (also in the interface catalog in all eight languages). `{0}` slots are filled by the page. */ +/** The plain sentences (also in the interface catalog in all nine languages). `{0}` slots are filled by the page. */ export const FIT_TEXT = Object.freeze({ tooLarge: 'This message is about {0} tokens long, and this model can read about {1} at a time. It is too large to send as it is.', tooLargeNext: 'Attach it as a file for the assistant to read in parts, or send a shortened preview.', diff --git a/apps/host/server/agent/plugins/strata-gate.mjs b/apps/host/server/agent/plugins/strata-gate.mjs index 96e59221..098ceea8 100644 --- a/apps/host/server/agent/plugins/strata-gate.mjs +++ b/apps/host/server/agent/plugins/strata-gate.mjs @@ -48,25 +48,196 @@ export const READ_ONLY_TOOLS = new Set([ const SHELL_TOOLS = new Set(['pwsh', 'bash']); -/** Commands that only look. Matched against the first word of every pipeline segment. */ -const SAFE_COMMANDS = new Set([ - // PowerShell - 'get-childitem', 'gci', 'ls', 'dir', 'get-content', 'gc', 'cat', 'type', 'get-item', 'gi', 'get-location', 'pwd', 'gl', - 'select-string', 'sls', 'measure-object', 'measure', 'select-object', 'select', 'where-object', 'where', 'sort-object', 'sort', - 'format-table', 'ft', 'format-list', 'fl', 'out-string', 'test-path', 'resolve-path', 'get-filehash', 'get-date', 'get-command', - 'get-process', 'get-itemproperty', 'write-output', 'echo', 'hostname', 'whoami', 'get-host', 'get-psdrive', 'get-help', - 'group-object', 'group', 'convertto-json', 'convertfrom-json', 'select-xml', 'compare-object', 'get-unique', 'tee-object-none', - // POSIX - 'head', 'tail', 'wc', 'grep', 'rg', 'egrep', 'fgrep', 'stat', 'file', 'du', 'df', 'uname', 'which', 'basename', 'dirname', - 'realpath', 'readlink', 'sort', 'uniq', 'cut', 'tr', 'less', 'more', 'date', 'id', 'env-none', 'tree', -]); +/** + * Which shell commands run without a card in Manual mode, and with which options. Safe by construction (#3975): a command is on the list WITH the + * options that are known to only look. Every other option, long or short, abbreviated or attached, makes the command ask. So a write mode + * (`sort -o`, `tree -o`, `uniq in out`), a program-execution mode (`sort --compress-program`, `rg --pre`, `git grep -O`), a setting mode + * (`date -s`) or one that never ends (`tail -f`) cannot slip in, and a word added to the list later starts with no options at all. + * + * A spec says what one command accepts: + * f short options without a value (letters, so `-la` is `-l -a`) v short options that need a value (`-k2`, `-k 2`) + * vn the same, and the value must be a number o short options with an optional value that must be attached (`-Iseconds`) + * n a bare `-5` is allowed l long options (`--name`, `--name=value`), spelled in full + * lv long options that need a value (`--name=value`, `--name value`) ps PowerShell parameter names, lower case, spelled in full + * max how many operands (files, patterns) are allowed op a check for each operand + * post a last check from the options seen and the operand count + */ +const words = (text) => (text ? text.trim().split(/\s+/) : []); +const spec = ({ f = '', v = '', vn = '', o = '', n = false, l = '', lv = '', ps = '', max = Infinity, op = null, post = null }) => + ({ f, v, vn, o, n, l: new Set(words(l)), lv: new Set(words(lv)), ps: ps ? new Set([...words(ps), ...PS_COMMON]) : null, max, op, post }); +/** Parameters every cmdlet has that only change how errors and warnings show. (-Debug asks a question and -OutVariable sets one: not listed.) */ +const PS_COMMON = ['erroraction', 'ea', 'warningaction', 'wa', 'informationaction', 'ia', 'verbose', 'vb']; +const NUMBER = /^[+-]?\d+[A-Za-z]{0,3}$/; + +/** What `ls`, `dir`, `gci` and `Get-ChildItem` take. */ +const LS = { f: 'aAbBcdDFgGhHiklLmnNopqQrRsStuUvxX1CZ', v: 'ITw', ps: 'path literalpath filter include exclude recurse depth name force file directory hidden readonly system attributes', + l: 'all almost-all human-readable recursive directory classify reverse size inode dereference color group-directories-first sort time time-style block-size indicator-style si numeric-uid-gid no-group literal hide ignore quote-name escape author file-type full-time width tabsize' }; +/** What `cat`, `type`, `gc` and `Get-Content` take. (-Wait never ends, so it is not here.) */ +const CAT = { f: 'AbeEnstTuv', ps: 'path literalpath totalcount tail head raw encoding readcount force filter include exclude delimiter stream asbytestream', + l: 'show-all number-nonblank show-ends number squeeze-blank show-tabs show-nonprinting' }; +const MEASURE = { ps: 'property sum average maximum minimum line word character ignorewhitespace inputobject standarddeviation allstats' }; +const SELECT = { ps: 'first last skip skiplast property expandproperty unique index excludeproperty inputobject' }; +const WHERE = { ps: 'property value inputobject eq ne gt lt ge le like notlike match notmatch contains notcontains in notin is isnot ceq cne cgt clt cge cle clike cnotlike cmatch cnotmatch ccontains cnotcontains cin cnotin' }; +const GROUP = { ps: 'property noelement ashashtable asstring casesensitive inputobject culture' }; +const FT = { ps: 'property autosize wrap hidetableheaders groupby view force expand repeatheader displayerror showerror inputobject' }; +const FL = { ps: 'property view groupby expand force displayerror showerror inputobject' }; +const SLS = { ps: 'pattern path literalpath simplematch casesensitive context list notmatch quiet allmatches include exclude encoding raw inputobject culture noemphasis' }; +const GETITEM = { ps: 'path literalpath name filter include exclude force stream' }; +const GETLOC = { ps: 'psprovider psdrive stack stackname' }; +const ECHO = { f: 'neE', ps: 'inputobject noenumerate' }; +/** The GNU/BSD grep family. */ +const GREP = { f: 'aiIlLcnvwHhEFGPqrRsTUyzZbxo', v: 'efdD', vn: 'ABCm', n: true, + l: 'extended-regexp fixed-strings basic-regexp perl-regexp ignore-case no-ignore-case word-regexp line-regexp invert-match count color colour files-with-matches files-without-match max-count only-matching quiet silent no-messages byte-offset with-filename no-filename label line-buffered initial-tab null after-context before-context context text recursive dereference-recursive include exclude exclude-dir binary-files line-number null-data no-group-separator group-separator regexp file directories devices binary' }; + +/** Commands that only look, each with the options that are known to be harmless. Matched against the first word of every pipeline segment. */ +const SPECS = new Map(); +const add = (names, s) => { for (const name of words(names)) SPECS.set(name, spec(s)); }; +// PowerShell +add('get-childitem gci', { ps: LS.ps }); +add('ls dir', LS); +add('get-content gc', { ps: CAT.ps }); +add('cat type', CAT); +add('get-item gi get-itemproperty', GETITEM); +add('get-location gl', GETLOC); +add('pwd', { ...GETLOC, f: 'LP' }); +add('select-string sls', SLS); +add('measure-object measure', MEASURE); +add('select-object select', SELECT); +add('where-object where', WHERE); +add('sort-object', { ps: 'property descending unique top bottom casesensitive culture stable inputobject' }); +add('format-table ft', FT); +add('format-list fl', FL); +add('out-string', { ps: 'stream width inputobject' }); +add('test-path', { ps: 'path literalpath pathtype isvalid filter include exclude olderthan newerthan' }); +add('resolve-path', { ps: 'path literalpath relative relativebasepath force' }); +add('get-filehash', { ps: 'path literalpath algorithm' }); +add('get-date', { ps: 'format uformat date asutc displayhint year month day hour minute second millisecond' }); +add('get-command', { ps: 'name commandtype module all syntax listimported totalcount noun verb fullyqualifiedmodule parametername parametertype' }); +add('get-process', { ps: 'name id includeusername module fileversioninfo inputobject' }); +add('write-output', { ps: ECHO.ps }); +add('echo', ECHO); +add('get-host', { ps: '' }); +add('get-psdrive', { ps: 'name psprovider scope literalname' }); +add('get-help', { ps: 'name full detailed examples parameter category component functionality role' }); +add('group-object group', GROUP); +add('convertto-json', { ps: 'depth compress enumsasstrings inputobject asarray escapehandling' }); +add('convertfrom-json', { ps: 'ashashtable depth inputobject noenumerate' }); +add('select-xml', { ps: 'xml path literalpath xpath content namespace' }); +add('compare-object', { ps: 'referenceobject differenceobject property includeequal excludedifferent passthru syncwindow casesensitive culture' }); +add('get-unique', { ps: 'inputobject asstring caseinsensitive onetype' }); +// POSIX. `sort` and `date` take no PowerShell names here: `sort -o FILE` writes, `date -s` sets the clock, and a PowerShell-looking `-Second` or `-Top` +// must not be read by a real sort or date as one of those. (Sort-Object and Get-Date above are the PowerShell forms.) +add('head', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); +add('tail', { f: 'qvz', vn: 'nc', n: true, l: 'quiet silent verbose zero-terminated lines bytes' }); // no -f, -F, --follow, --retry, --pid, -s: those never end +add('wc', { f: 'lwcmL', l: 'lines words bytes chars max-line-length' }); +add('grep egrep fgrep', GREP); +add('rg', { // no --pre, --pre-glob, --hostname-bin (they run a program) and no -z/--search-zip (it runs decompressors) + f: 'iIsSnNHlcwFxvUoLaquhVpbP', v: 'efgtTr', vn: 'ABCjdMm', + l: 'ignore-case no-ignore-case smart-case case-sensitive fixed-strings word-regexp line-regexp invert-match count count-matches files-with-matches files-without-match files type-list hidden no-ignore no-ignore-vcs no-ignore-parent no-ignore-dot no-ignore-global no-ignore-messages follow line-number no-line-number with-filename no-filename column heading no-heading null only-matching quiet text multiline multiline-dotall pcre2 no-messages json stats trim unrestricted binary no-config vimgrep pretty byte-offset passthru crlf one-file-system no-unicode regexp file glob iglob type type-not max-count max-depth maxdepth context after-context before-context color replace threads sort sortr max-filesize max-columns path-separator encoding engine ignore-file glob-case-insensitive no-glob-case-insensitive' }); +add('stat', { f: 'LtxlnqrsFf', v: 'c', l: 'dereference file-system terse format printf' }); +add('file', { f: 'bhikLnNrvI', l: 'brief dereference no-dereference mime mime-type mime-encoding keep-going no-pad no-buffer raw' }); // no -C, -m, -f, -P (they write or read other files), no -z/-s/-p (they run decompressors, read devices, reset times) +add('du', { f: 'abchHklmsxLPSD0', v: 'tB', vn: 'd', l: 'all apparent-size bytes total dereference-args human-readable si summarize one-file-system dereference no-dereference separate-dirs count-links inodes null max-depth threshold block-size time time-style exclude' }); +add('df', { f: 'ahHiklmPTv', v: 'txB', l: 'all human-readable si inodes local portability print-type total sync no-sync output block-size type exclude-type' }); +add('uname', { f: 'asnrvmpio', max: 0, l: 'all kernel-name nodename kernel-release kernel-version machine processor hardware-platform operating-system' }); +add('which', { f: 'as', l: 'all' }); +add('basename', { f: 'az', v: 's', l: 'multiple zero suffix' }); +add('dirname', { f: 'z', l: 'zero' }); +add('realpath', { f: 'emsqzLP', l: 'canonicalize-existing canonicalize-missing no-symlinks quiet zero strip logical physical relative-to relative-base' }); +add('readlink', { f: 'femnqsvz', l: 'canonicalize canonicalize-existing canonicalize-missing no-newline quiet silent verbose zero' }); +add('sort', { f: 'bdfghiMnRrsuVzmcC', v: 'kt', l: 'ignore-leading-blanks dictionary-order ignore-case general-numeric-sort human-numeric-sort ignore-nonprinting month-sort numeric-sort random-sort reverse stable unique version-sort zero-terminated check merge sort field-separator key' }); +// uniq's second operand is its OUTPUT file, so it takes at most one. +add('uniq', { f: 'cdDuiz', vn: 'fsw', max: 1, l: 'count repeated all-repeated unique ignore-case skip-fields skip-chars check-chars zero-terminated group' }); +add('cut', { f: 'snz', v: 'bcfd', l: 'complement only-delimited zero-terminated bytes characters fields delimiter output-delimiter' }); +add('tr', { f: 'cCdst', max: 2 }); +add('date', { f: 'uR', o: 'I', v: 'dr', lv: 'date reference', l: 'utc universal rfc-email rfc-2822 iso-8601 rfc-3339', + op: (word) => word.startsWith('+') }); // a bare operand like 1026120026 SETS the clock; only +FORMAT is a format +add('id', { f: 'ugGnrazZ', l: 'user group groups name real context zero' }); +add('hostname', { f: 'sfiIdaAyv', max: 0 }); // `hostname NAME` renames the machine +add('whoami', { l: 'help version', op: (word) => /^\/(all|user|groups|priv|upn|fqdn|logonid|nh)$/i.test(word) }); +add('tree', { f: 'adfilpsugDFqNQrtvxCnASUchJX', v: 'LPIHT', vn: '', l: 'help version filelimit charset sort timefmt noreport dirsfirst filesfirst prune du si gitignore matchdirs ignore-case inodes device nolinks' }); // no -o, no -R +// `less` and `more` are not here: they wait for keys, and `less` can run commands. + +/** The names that run without a card (for the tests). */ +export const readOnlyCommandNames = () => [...SPECS.keys()]; + +/** git subcommands that only read, with the options they may take. */ +const GIT_VIEW = 'oneline graph decorate no-decorate all branches tags remotes stat shortstat numstat dirstat name-only name-status patch no-patch raw summary compact-summary abbrev-commit no-abbrev-commit abbrev reverse follow no-merges merges first-parent full-history simplify-by-decoration simplify-merges ancestry-path left-right left-only right-only cherry-pick cherry-mark cherry topo-order date-order author-date-order relative-date all-match invert-grep regexp-ignore-case extended-regexp fixed-strings perl-regexp no-color color color-words word-diff word-diff-regex minimal patience histogram diff-algorithm check exit-code quiet cached staged merge-base no-index no-ext-diff no-textconv find-renames find-copies find-copies-harder no-renames ignore-space-change ignore-all-space ignore-space-at-eol ignore-blank-lines ignore-cr-at-eol function-context show-function unified inter-hunk-context src-prefix dst-prefix no-prefix full-index binary text source use-mailmap mailmap no-mailmap log-size notes no-notes show-signature diff-merges boundary children parents no-walk sparse date format pretty author committer grep since until after before max-count skip min-parents max-parents diff-filter encoding stat-width stat-name-width stat-graph-width stat-count count'; +const LISTING = ['l', 'list', 'contains', 'no-contains', 'merged', 'no-merged', 'points-at']; +const GIT = new Map(Object.entries({ + status: spec({ f: 'sbvz', o: 'u', l: 'short branch porcelain long ignored untracked-files ignore-submodules renames no-renames find-renames show-stash ahead-behind no-ahead-behind column no-column verbose null' }), + log: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + diff: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + show: spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + 'rev-list': spec({ f: 'pswbMCizuacmrtqEFPR', vn: 'nU', v: 'SGL', n: true, l: GIT_VIEW }), + shortlog: spec({ f: 'sneciw', n: false, l: `${GIT_VIEW} summary numbered email committer group` }), + // Listing forms only. A name with no list option would CREATE a branch or a tag, and the options that change things are not here. + branch: spec({ f: 'avri', l: 'list all remotes verbose show-current ignore-case contains no-contains merged no-merged points-at sort format abbrev no-abbrev color no-color column no-column omit-empty', + post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }), + tag: spec({ f: 'li', o: 'n', l: 'list sort contains no-contains merged no-merged points-at format column no-column ignore-case omit-empty color no-color', + post: (seen, count) => count === 0 || LISTING.some(name => seen.has(name)) }), + remote: spec({ f: 'v', l: 'verbose', max: 0 }), + // `git config KEY` reads and `git config KEY VALUE` writes, so a key is only taken with --get; no --edit, --add, --unset, --file. + config: spec({ f: 'lz', l: 'list get get-all get-regexp show-origin show-scope local global system worktree bool int bool-or-int path expiry-date type null name-only includes no-includes', lv: 'default', + post: (seen, count) => (count > 0 ? ['get', 'get-all', 'get-regexp'].some(name => seen.has(name)) : seen.has('list') || seen.has('l')) }), + 'rev-parse': spec({ f: 'q', l: 'show-toplevel git-dir git-common-dir absolute-git-dir abbrev-ref symbolic symbolic-full-name short verify is-inside-work-tree is-inside-git-dir is-bare-repository is-shallow-repository show-prefix show-cdup show-superproject-working-tree all branches tags remotes quiet revs-only no-revs flags no-flags local-env-vars show-object-format path-format', lv: 'default git-path' }), + 'ls-files': spec({ f: 'cdmoiskuzvtfD', l: 'cached deleted modified others ignored stage directory unmerged killed no-empty-directory error-unmatch exclude-standard exclude full-name eol deduplicate recurse-submodules sparse abbrev resolve-undo format' }), + 'ls-tree': spec({ f: 'rtdlz', l: 'name-only name-status long full-name full-tree object-only abbrev format' }), + blame: spec({ f: 'wMCespltbfnc', v: 'L', l: 'porcelain line-porcelain incremental show-email show-name show-number date root abbrev' }), + describe: spec({ l: 'all tags always long dirty broken contains abbrev match exclude first-parent exact-match candidates' }), + 'cat-file': spec({ f: 'tsep', l: 'batch batch-check batch-all-objects allow-unknown-type buffer unordered follow-symlinks mailmap use-mailmap' }), // no --textconv, --filters + // No -O / --open-files-in-pager: they run a program on the matches. + grep: spec({ f: 'aiIlLcnvwHhEFGPqpWrzUo', v: 'e', vn: 'ABCm', n: true, l: 'no-index untracked cached no-exclude-standard exclude-standard recurse-submodules text ignore-case word-regexp invert-match full-name extended-regexp basic-regexp perl-regexp fixed-strings line-number column files-with-matches name-only files-without-match count null only-matching quiet no-color color break heading show-function function-context all-match and or not max-depth max-count threads after-context before-context context recursive no-recursive' }), +})); + +/** + * One command's words against its spec: every option has to be one the spec knows (anything else is not understood, so it asks). + * @param {ReturnType} sp + * @param {{t:string,q:boolean}[]} args the words after the command; q marks a quoted text, which is data and never an option + */ +function argumentsAreSafe(sp, args) { + const seen = new Set(); + let operands = 0, ended = false; + const operand = (arg) => { operands++; return operands <= sp.max && (!sp.op || sp.op(arg.t, arg.q)); }; + const valueOf = (i, numeric) => { // the next word as an option's value; it can be a quoted text, a number, or a word that is not an option + const arg = args[i + 1]; + if (!arg) return false; + return numeric ? NUMBER.test(arg.t) : arg.q || !arg.t.startsWith('-') || NUMBER.test(arg.t); + }; + for (let i = 0; i < args.length; i++) { + const { t, q } = args[i]; + if (q || ended || t === '-' || t[0] !== '-') { if (!operand(args[i])) return false; continue; } + if (t === '--') { ended = true; continue; } + if (t.startsWith('--')) { + const eq = t.indexOf('='); + const name = eq < 0 ? t.slice(2) : t.slice(2, eq); + if (sp.l.has(name)) { seen.add(name); continue; } + if (sp.lv.has(name)) { seen.add(name); if (eq < 0) { if (!valueOf(i, false)) return false; i++; } continue; } + return false; + } + if (sp.ps) { + const named = /^-([A-Za-z][A-Za-z0-9]*)(?::|$)/.exec(t); + if (named && sp.ps.has(named[1].toLowerCase())) { seen.add(named[1].toLowerCase()); continue; } + } + if (sp.n && /^-\d+$/.test(t)) continue; + for (let j = 1; j < t.length; j++) { + const c = t[j]; + if (sp.f.includes(c)) { seen.add(c); continue; } + if (sp.o.includes(c)) { seen.add(c); break; } + const numeric = sp.vn.includes(c); + if (!numeric && !sp.v.includes(c)) return false; + seen.add(c); + const rest = t.slice(j + 1); + if (rest) { if (numeric && !NUMBER.test(rest)) return false; } else { if (!valueOf(i, numeric)) return false; i++; } + break; + } + } + return sp.post ? sp.post(seen, operands) : true; +} -/** git subcommands that only read. */ -const SAFE_GIT = new Set(['status', 'log', 'diff', 'show', 'branch', 'rev-parse', 'ls-files', 'blame', 'describe', 'remote', 'tag', 'shortlog', 'rev-list', 'cat-file', 'grep', 'ls-tree', 'config']); const SAFE_VERSION = /^(node|python|python3|py|npm|pnpm|git|dotnet|cargo|rustc|go|java|pip|pip3)\s+(--version|-v|-version|version)$/i; -/** Anything that can chain, redirect, expand or start something else is not read-only. */ -const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|\bsh\b|\bbash\b|\bpwsh\b|\bpowershell\b|\bcmd\b|-exec\b|-delete\b|-execdir\b/i; +/** Anything that can chain, redirect, expand or start something else is not read-only. (`sh` as a word, not inside an option like `du -sh`.) */ +const UNSAFE_SYNTAX = /[;&<>`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd-content\b|\binvoke-|\biex\b|\bstart-|\bnew-|\bremove-|\bcopy-|\bmove-|\brename-|\bclear-|\bset-|\bpush-|\bexpand-|\bsave-|\binstall-|\bcurl\b|\bwget\b|\bsudo\b|(?`${}()]|\r|\n|--%|\bout-file\b|\bset-content\b|\badd * inside double quotes a $ or a backtick expands (a variable, a sub-command), and an unterminated quote means the text was not understood. * Either one gives null, and the command asks as before. * @param {string} text + * @param {string[]} [quoted] when given, receives the text inside each quote, in order (the checks on operands read it) * @returns {string|null} */ -export function maskQuotes(text) { +export function maskQuotes(text, quoted) { let out = ''; for (let i = 0; i < text.length; i++) { const c = text[i]; @@ -91,13 +263,14 @@ export function maskQuotes(text) { const before = text[i - 1], after = text[end + 1]; if ((before !== undefined && !/[\s|]/.test(before)) || (after !== undefined && !/[\s|]/.test(after)) || text[i + 1] === '-') return null; out += '"_"'; + quoted?.push(text.slice(i + 1, end)); i = end; } return out; } /** - * Whether a shell command only reads. Conservative by design: one unrecognised word and the answer is no. + * Whether a shell command only reads. Conservative by design: one unrecognised word or option and the answer is no. * Quoted text is data and is looked at after it has been set aside (maskQuotes): Get-ChildItem "C:\Users\x\Q&A" only lists. * @param {string} command * @returns {boolean} @@ -106,24 +279,21 @@ export function isReadOnlyShell(command) { const text = String(command ?? '').trim(); if (!text || text.length > 600) return false; if (SAFE_VERSION.test(text)) return true; - const masked = maskQuotes(text); + const quoted = []; + const masked = maskQuotes(text, quoted); if (masked === null || UNSAFE_SYNTAX.test(masked)) return false; - const segments = masked.split('|').map(s => s.trim()); - return segments.every((segment) => { - if (!segment) return false; - const words = segment.split(/\s+/); - const first = words[0].toLowerCase().replace(/^\.\\/, ''); + let next = 0; + const tokens = masked.split('|').map(segment => segment.trim()).map(segment => words(segment).map(w => (w === '"_"' ? { t: quoted[next++] ?? '', q: true } : { t: w, q: false }))); + return tokens.every((segment) => { + if (!segment.length || segment[0].q) return false; + const first = segment[0].t.toLowerCase().replace(/^\.\\/, ''); if (first === 'git') { - // `git config` and `git tag`/`branch`/`remote` can write when given a value; only the bare listing forms are safe. - const sub = (words[1] ?? '').toLowerCase(); - if (!SAFE_GIT.has(sub)) return false; - if (['config', 'tag', 'branch', 'remote'].includes(sub)) { - const rest = words.slice(2).filter(w => !w.startsWith('-') || /^(-l|-a|-v|-vv|--list|--all|--show-current|--get|--get-all)$/i.test(w)); - return rest.length === 0 || (sub === 'config' && words[2] === '--get') || (sub === 'remote' && words[2] === '-v'); - } - return !words.some(w => /^--(output|ext-diff|textconv)\b/i.test(w)); + const sub = segment[1]; + const sp = sub && !sub.q ? GIT.get(sub.t) : null; + return !!sp && argumentsAreSafe(sp, segment.slice(2)); } - return SAFE_COMMANDS.has(first) && !words.some(w => /^-(delete|exec|execdir|fprint|fls|ok)$/i.test(w)); + const sp = SPECS.get(first); + return !!sp && argumentsAreSafe(sp, segment.slice(1)); }); } diff --git a/apps/host/server/agent/turn-guard.mjs b/apps/host/server/agent/turn-guard.mjs index f28ce3f4..14566d5b 100644 --- a/apps/host/server/agent/turn-guard.mjs +++ b/apps/host/server/agent/turn-guard.mjs @@ -10,7 +10,7 @@ * rewrites a plan turn wrote its numbered plan from "1." again this many times * context the context is nearly full: the Harness compaction did not keep up * - * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all eight languages (the page + * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all nine languages (the page * translates a `delta` frame that carries `key`). Each says what happened and gives one next step. */ diff --git a/apps/host/server/bundled-engine.mjs b/apps/host/server/bundled-engine.mjs index 8d4fdc3f..f3ad0534 100644 --- a/apps/host/server/bundled-engine.mjs +++ b/apps/host/server/bundled-engine.mjs @@ -67,40 +67,70 @@ export function nvidiaDriverVersion() { /** Where the builds are published; the wrong-make sentence points here. */ export const RELEASES_URL = 'https://github.com/Niko1221/Strata/releases'; -/** The PCI vendor ids (`10de`, `1002`, `8086`) of the Windows display adapters; empty off Windows or when the registry cannot be read. */ -export function windowsDisplayVendors({ platform = process.platform, run = execFileSync } = {}) { +/** The PCI vendor ids of the display adapters Windows reports as present right now (PowerShell, Win32_VideoController); empty when that cannot be read. */ +export function windowsPresentVendors({ platform = process.platform, run = execFileSync } = {}) { + const found = new Set(); + if (platform !== 'win32') return found; + try { + const out = run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_VideoController | ForEach-Object { $_.PNPDeviceID }'], { encoding: 'utf8', timeout: 15000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); + for (const match of String(out).matchAll(/VEN_([0-9A-F]{4})/gi)) found.add(match[1].toLowerCase()); + } catch { /* no PowerShell or a limited account: the registry answer stands */ } + return found; +} + +/** + * The PCI vendor ids (`10de`, `1002`, `8086`) of the Windows display adapters; empty off Windows or when the registry cannot be read. + * The registry keeps the entry of a card that was taken out (an NVIDIA card swapped for a Radeon, #3892): when NVIDIA and AMD are both + * listed, only the makes Windows reports as present now count, the same rule Strata Control uses (engine_component.windows_display_adapters). + */ +export function windowsDisplayVendors({ platform = process.platform, run = execFileSync, present = windowsPresentVendors } = {}) { const found = new Set(); if (platform !== 'win32') return found; try { const out = run('reg', ['query', 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}', '/s', '/v', 'MatchingDeviceId'], { encoding: 'utf8', timeout: 8000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); for (const match of String(out).matchAll(/VEN_([0-9A-F]{4})/gi)) found.add(match[1].toLowerCase()); } catch { /* no registry access: the tools decide */ } + if (found.has('10de') && found.has('1002')) { + const now = present({ platform, run }); + const kept = new Set([...found].filter(vendor => now.has(vendor))); + if (kept.size) return kept; + } return found; } +const BACKEND_OF_VENDOR = [['10de', 'cuda'], ['1002', 'hip'], ['8086', 'sycl']]; + +/** + * Every engine family this PC's graphics cards can run, in the order NVIDIA, AMD, Intel; STRATA_ENGINE_BACKEND wins. A PC with two + * makes lists both, so a build for either make is accepted (recommend, never force). + */ +export function gpuBackendsHere(env = process.env, { vendors = windowsDisplayVendors() } = {}) { + const forced = String(env.STRATA_ENGINE_BACKEND ?? '').trim().toLowerCase(); + if (forced) return ['cuda', 'hip', 'sycl'].includes(forced) ? [forced] : []; + if (vendors.size) { + const list = BACKEND_OF_VENDOR.filter(([vendor]) => vendors.has(vendor)).map(([, backend]) => backend); + if (list.length) return list; + } + if (nvidiaDriverVersion()) return ['cuda']; + try { + const base = '/sys/class/drm'; + const seen = new Set(); + for (const card of readdirSync(base)) { + if (!/^card\d+$/.test(card)) continue; + try { seen.add(readFileSync(`${base}/${card}/device/vendor`, 'utf8').trim().toLowerCase()); } catch { /* no vendor file */ } + } + const list = [['0x10de', 'cuda'], ['0x1002', 'hip'], ['0x8086', 'sycl']].filter(([vendor]) => seen.has(vendor)).map(([, backend]) => backend); + if (list.length) return list; + } catch { /* not Linux */ } + return []; +} + /** * The engine family this PC's graphics card needs ('cuda', 'hip', 'sycl'), or null when it cannot be told. The same order as Control * (NVIDIA first, then AMD, then Intel); STRATA_ENGINE_BACKEND wins. Reads only the driver and (Linux) the PCI vendor of the display adapters. */ -export function gpuBackendHere(env = process.env, { vendors = windowsDisplayVendors() } = {}) { - const forced = String(env.STRATA_ENGINE_BACKEND ?? '').trim().toLowerCase(); - if (forced) return ['cuda', 'hip', 'sycl'].includes(forced) ? forced : null; - // Windows: the display adapters are the machine's own statement of which cards it has; a leftover nvidia-smi from a card that was - // taken out must not outvote them (#3688). Same order as Control: NVIDIA, then AMD, then Intel. - if (vendors.size) { - for (const [vendor, backend] of [['10de', 'cuda'], ['1002', 'hip'], ['8086', 'sycl']]) if (vendors.has(vendor)) return backend; - } - if (nvidiaDriverVersion()) return 'cuda'; - try { - const base = '/sys/class/drm'; - const vendors = new Set(); - for (const card of readdirSync(base)) { - if (!/^card\d+$/.test(card)) continue; - try { vendors.add(readFileSync(`${base}/${card}/device/vendor`, 'utf8').trim().toLowerCase()); } catch { /* no vendor file */ } - } - for (const [vendor, backend] of [['0x10de', 'cuda'], ['0x1002', 'hip'], ['0x8086', 'sycl']]) if (vendors.has(vendor)) return backend; - } catch { /* not Linux */ } - return null; +export function gpuBackendHere(env = process.env, options = {}) { + return gpuBackendsHere(env, options)[0] ?? null; } const HIP_FAMILIES = [['RX 9000', ['gfx1200', 'gfx1201']], ['RX 7000', ['gfx1100', 'gfx1101', 'gfx1102']], ['RX 6000', ['gfx1030', 'gfx1031']], ['Ryzen AI Max', ['gfx1151']]]; @@ -147,10 +177,12 @@ export async function installBundledEngine({ bundleDir, components, platform = n if (platform) packages = packages.filter(p => p.manifest.platform === platform); if (!packages.length) return { action: 'none' }; // A build for another make of graphics card than this PC has can never run here: it is not unpacked, and the caller says so in plain words. - const wanted = backend === undefined ? gpuBackendHere() : backend; + // A PC with two makes (an AMD card for the model, an NVIDIA card for the desktop) accepts a build for either (#3892). + const wantedList = backend === undefined ? gpuBackendsHere() : (Array.isArray(backend) ? backend : backend ? [backend] : []); + const wanted = wantedList[0] ?? null; if (wanted && ['cuda', 'hip', 'sycl'].includes(wanted)) { const gpu = packages.filter(p => ['cuda', 'hip', 'sycl'].includes(p.manifest.backend)); - const fits = packages.filter(p => !gpu.includes(p) || p.manifest.backend === wanted); + const fits = packages.filter(p => !gpu.includes(p) || wantedList.includes(p.manifest.backend)); if (gpu.length && !fits.length) { const first = gpu.sort((a, b) => compareVersions(b.manifest.version, a.manifest.version))[0].manifest; return { action: 'wrong-make', built: first.backend, here: wanted, notice: wrongMakeNotice(first, wanted) }; diff --git a/apps/host/server/control-runtime.mjs b/apps/host/server/control-runtime.mjs index f0f64dba..2be9e126 100644 --- a/apps/host/server/control-runtime.mjs +++ b/apps/host/server/control-runtime.mjs @@ -74,6 +74,17 @@ export function findControl({ env = process.env, platform = process.platform, ex return control; } +/** + * The environment of the server the host starts from a source checkout (#3851): the key travels in the run configuration, so a + * STRATA_API_KEY the host itself was started with is removed. Setting it to an empty string made serve/server.py stop with + * "an API key was given but it is empty". + */ +export function sourceServerEnvironment(env = process.env) { + const next = { ...env, PYTHONUNBUFFERED: '1', PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' }; + delete next.STRATA_API_KEY; + return next; +} + /** The environment Control runs in: nothing from the user's Python, and acquiring forbidden. */ export function controlEnvironment(control, { env = process.env, components = componentsDirectory({ env }), acquire = false } = {}) { const next = { ...env }; diff --git a/apps/host/server/device-probes.mjs b/apps/host/server/device-probes.mjs index f29bd666..80a68d8c 100644 --- a/apps/host/server/device-probes.mjs +++ b/apps/host/server/device-probes.mjs @@ -40,13 +40,15 @@ export function parseNvidiaDevices(raw) { return [{id:uuid,index:Number(index),sensorIndex:Number(index),busId:bus?.toLowerCase(),vendor:'nvidia',name,vramGb:round((number(memory)??0)/1024,1),unified:false,backend:'cuda',driver}]; }); } +/** A percentage reading; "[N/A]" and out-of-range values are no reading. */ +const percentOf = v => { const n=number(v); return n!==null&&n>=0&&n<=100?n:null; }; export function parseNvidiaReadings(raw) { return raw.split('\n').flatMap(line=>{ - const [id,temp,load,memory,power,limit,gen,maxGen,width]=line.split(',').map(s=>s.trim()); + const [id,temp,load,memory,power,limit,gen,maxGen,width,fan,clock]=line.split(',').map(s=>s.trim()); if (!id?.startsWith('GPU-')) return []; const t=number(temp),u=number(load),m=number(memory); const positive = v => { const n=number(v); return n!==null&&n>=0?n:null; }; - return [{id,temperatureC:t!==null&&t>=0&&t<=150?t:null,utilizationPct:u!==null&&u>=0&&u<=100?u:null,memoryUsedGb:m!==null&&m>=0?round(m/1024,2):null,powerW:positive(power),powerLimitW:positive(limit),pcieGen:positive(gen),pcieGenMax:positive(maxGen),pcieWidth:positive(width),pcieRxMbs:null}]; + return [{id,temperatureC:t!==null&&t>=0&&t<=150?t:null,utilizationPct:u!==null&&u>=0&&u<=100?u:null,memoryUsedGb:m!==null&&m>=0?round(m/1024,2):null,powerW:positive(power),powerLimitW:positive(limit),pcieGen:positive(gen),pcieGenMax:positive(maxGen),pcieWidth:positive(width),pcieRxMbs:null,fanPct:percentOf(fan),clockMhz:positive(clock)}]; }); } export function parsePcieThroughput(raw) { @@ -73,14 +75,15 @@ export async function detectDrmGpus() { } return result; } -export async function readGpuTelemetry(gpus) { +/** `transfer: false` skips the PCIe throughput sample (a second nvidia-smi); it only means something while a model runs. */ +export async function readGpuTelemetry(gpus, { transfer: wantTransfer = true, run = probe } = {}) { const now=new Date().toISOString(); const hasNvidia=gpus.some(g=>g.vendor==='nvidia'); - let raw=hasNvidia?await probe('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current','--format=csv,noheader,nounits'],2000):''; + let raw=hasNvidia?await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used,power.draw,power.limit,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,fan.speed,clocks.current.graphics','--format=csv,noheader,nounits'],2000):''; // Older drivers can reject a field; retain their basic sensors in that case. - if(hasNvidia&&!raw)raw=await probe('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used','--format=csv,noheader,nounits'],2000); + if(hasNvidia&&!raw)raw=await run('nvidia-smi',['--query-gpu=uuid,temperature.gpu,utilization.gpu,memory.used','--format=csv,noheader,nounits'],2000); const nvidia=new Map(parseNvidiaReadings(raw).map(r=>[r.id,r])); - const transfer=hasNvidia?parsePcieThroughput(await probe('nvidia-smi',['dmon','-s','t','-c','1'],1500)):new Map(); + const transfer=hasNvidia&&wantTransfer?parsePcieThroughput(await run('nvidia-smi',['dmon','-s','t','-c','1'],1500)):new Map(); return Promise.all(gpus.map(async gpu=>{ let reading=nvidia.get(gpu.id)??{id:gpu.id??`${gpu.vendor}:${gpu.index}`,temperatureC:null,utilizationPct:null,memoryUsedGb:null,powerW:null,powerLimitW:null,pcieGen:null,pcieGenMax:null,pcieWidth:null,pcieRxMbs:null}; if(gpu.vendor==='nvidia')reading={...reading,pcieRxMbs:transfer.get(gpu.sensorIndex??gpu.index)??null}; @@ -89,11 +92,13 @@ export async function readGpuTelemetry(gpus) { if(counters)reading={...reading,utilizationPct:counters.utilizationPct,memoryUsedGb:round(counters.memoryUsedGb,2)}; } if(gpu.sensorPath&&!nvidia.has(gpu.id)) { - let temperature=null,power=null,powerLimit=null; + let temperature=null,power=null,powerLimit=null,fanPwm=null,clockHz=null; for(const hwmon of await list(`${gpu.sensorPath}/hwmon`)) { const folder=`${gpu.sensorPath}/hwmon/${hwmon}`,inputs=(await list(folder)).filter(n=>/^temp\d+_input$/.test(n)); power ??= number(await read(`${folder}/power1_average`)) ?? number(await read(`${folder}/power1_input`)); powerLimit ??= number(await read(`${folder}/power1_cap`)); + fanPwm ??= number(await read(`${folder}/pwm1`)); // 0-255, the fan's duty as the amdgpu driver reports it + clockHz ??= number(await read(`${folder}/freq1_input`)); // the graphics clock in Hz for(const input of inputs) { const label=await read(`${folder}/${input.replace('_input','_label')}`); if(label&&!/edge|gpu/i.test(label))continue; @@ -105,7 +110,7 @@ export async function readGpuTelemetry(gpus) { const utilization=number(await read(`${gpu.sensorPath}/gpu_busy_percent`)),bytes=number(await read(`${gpu.sensorPath}/mem_info_vram_used`)); const gen=path=>read(path).then(raw=>({2.5:1,5:2,8:3,16:4,32:5,64:6}[Number.parseFloat(raw)]??null)); const [pcieGen,pcieGenMax,width]=await Promise.all([gen(`${gpu.sensorPath}/current_link_speed`),gen(`${gpu.sensorPath}/max_link_speed`),read(`${gpu.sensorPath}/current_link_width`)]); - reading={...reading,temperatureC:temperature,utilizationPct:utilization!==null&&utilization>=0&&utilization<=100?utilization:null,memoryUsedGb:bytes!==null&&bytes>=0?round(bytes/1024**3,2):null,powerW:power!==null&&power>=0?power/1e6:null,powerLimitW:powerLimit!==null&&powerLimit>=0?powerLimit/1e6:null,pcieGen,pcieGenMax,pcieWidth:number(width)}; + reading={...reading,fanPct:fanPwm!==null&&fanPwm>=0&&fanPwm<=255?Math.round(fanPwm/255*100):null,clockMhz:clockHz!==null&&clockHz>0?Math.round(clockHz/1e6):null,temperatureC:temperature,utilizationPct:utilization!==null&&utilization>=0&&utilization<=100?utilization:null,memoryUsedGb:bytes!==null&&bytes>=0?round(bytes/1024**3,2):null,powerW:power!==null&&power>=0?power/1e6:null,powerLimitW:powerLimit!==null&&powerLimit>=0?powerLimit/1e6:null,pcieGen,pcieGenMax,pcieWidth:number(width)}; } return {...reading,sampledAt:now,source:Object.entries(reading).some(([key,value])=>key!=='id'&&typeof value==='number')?'sensor':'none'}; })); diff --git a/apps/host/server/energy-meter.mjs b/apps/host/server/energy-meter.mjs new file mode 100644 index 00000000..9bed3eef --- /dev/null +++ b/apps/host/server/energy-meter.mjs @@ -0,0 +1,14 @@ +/** + * GPU energy since the host started, in Wh (#3628): the power reading held for the time since the last tick, added up. + * A long gap (the PC slept, the host was paused) counts for at most 5 s, so a sleep never adds a made-up hour of use. + */ +const meter = { wh: 0, at: 0 }; + +export function addEnergy(powerW, at) { + const dt = meter.at ? Math.min((at - meter.at) / 1000, 5) : 0; + meter.at = at; + if (typeof powerW === 'number' && Number.isFinite(powerW) && powerW >= 0 && dt > 0) meter.wh += powerW * dt / 3600; + return meter.wh; +} + +export const energyWh = () => meter.wh; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 0025520a..e059a657 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -71,6 +71,8 @@ import { createRuntimeModels } from './runtime-models.mjs'; import { createNativeControl } from './native-control.mjs'; import { nativeUnloadPlan } from './storage-check.mjs'; import { installBundledEngine, cleanupAfterInstall } from './bundled-engine.mjs'; +import { systemLocale } from './region.mjs'; +import { createShellNotifier, DEFAULT_PORT, parsePortNotice, readShellPrefs, writeShellPrefs } from './shell-prefs.mjs'; import { findControl, createControl, componentsDirectory } from './control-runtime.mjs'; import { forbidden as acquisitionForbidden } from './acquisition.mjs'; import { randomBytes, timingSafeEqual } from 'node:crypto'; @@ -115,7 +117,7 @@ const WORKSPACE_NAME = process.env.STRATA_WORKSPACE ? basename(WORKSPACE) : 'Str const insideApp = path => { const rel = relative(ROOT, resolve(path)); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); }; const hub = new EventHub(); -const modelProviders = createModelProviders({ directory: store.DATA_DIR, changed: value => hub.send('providers', withPictureAnswers(value)) }); +const modelProviders = createModelProviders({ directory: store.DATA_DIR, knownThinks: (connection, modelId) => visionProbe.knownThinks(connection, modelId), changed: value => hub.send('providers', withPictureAnswers(value)) }); const imageModels = createImageModels({ dataDir: store.DATA_DIR, modelsDir: () => store.MODELS_DIR, real: models.REAL, changed: value => hub.send('image-models', value) }); /* The installed app ships Strata Control (python + strata_control) next to the host; a source checkout has none and keeps its older paths. */ const CONTROL = findControl(); @@ -127,6 +129,19 @@ const appUi = createAppUi({ shutdown: () => shutdown() }); /* The app's version has one source: the desktop shell passes it (STRATA_APP_VERSION, from apps/desktop/src-tauri/Cargo.toml). Outside the app it is read from the same file in a checkout, else 'dev'. */ function appVersion() { return appVersionFrom({ env: process.env, here: HERE }); } const appUpdater = appUi.updater; +const shellNotifier = createShellNotifier(); +/** What the page needs for the desktop settings: whether this is the desktop app, the port in use, the saved choices and a busy-port notice. */ +function shellState() { + const saved = readShellPrefs(); + const desktop = !!shellNotifier; + return { + desktop, + tray: desktop && process.platform !== 'linux', + port: PORT, defaultPort: DEFAULT_PORT, + pinnedPort: saved.port || null, minimizeToTray: saved.tray, + portNotice: parsePortNotice(process.env.STRATA_PORT_NOTICE), + }; +} /* The engine that ships inside the installer is put in the components folder when this PC has none (or an older one); no network, hashes checked. The model list waits for it. */ const bundledEngine = control && !process.env.STRATA_NO_BUNDLED_ENGINE ? installBundledEngine({ bundleDir: process.env.STRATA_ENGINE_BUNDLE_DIR || resolve(HERE, '..', '..', 'engine-bundle'), components: componentsDirectory(), log: line => console.log(line) }) @@ -224,6 +239,7 @@ models.init(hub); engine.init(hub); engineInstall.init(hub); monitor.init(hub, boot); +monitor.setLiveProbe(() => native.hasLive()); serving.init(hub, { port: PORT, host: HOST }); runtimeModels=createRuntimeModels({hardware:()=>hardware.cachedHardware()??boot,library:()=>models.library(),requests:()=>serving.state().requests,real:models.REAL,changed:value=>{ if(!models.REAL){const primary=value.instances.find(i=>i.id===value.defaultId);if(store.get().loaded!==(primary?.variantId??null))store.update({loaded:primary?.variantId??null});} @@ -557,17 +573,18 @@ function clientName(req) { return 'Local client'; } -async function runRemoteTurn({ selection, message, history, images = [], onFrame, signal, workspaceId }) { +async function runRemoteTurn({ selection, message, history, images = [], thinking, onFrame, signal, workspaceId }) { const controller = new AbortController(); const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal; let entry; const started = Date.now(); try { const { connection, model } = modelProviders.resolve(selection); + if (connection.protocol === 'openai-chat' && model.reasoning == null) await visionProbe.check(connection, model.id); const appliedSkills = selectSkills(skillState, message, workspaceId); entry = serving.open({ client: 'Strata chat', endpoint: connection.protocol === 'anthropic' ? '/messages' : connection.protocol === 'openai-responses' ? '/responses' : '/chat/completions', model: `${connection.name} · ${model.name}`, cancel: () => controller.abort(new DOMException('Cancelled by the user', 'AbortError')) }); serving.mark(entry.id, { state: 'generating' }); - const result = await modelProviders.stream({ selection, message, history, images, signal: requestSignal, systemPrompt: ['You are Strata, a helpful assistant. Answer clearly. Do not claim to have read files or performed actions unless their results are included in the conversation.', skillInstructions(appliedSkills)].filter(Boolean).join('\n\n'), onFrame: frame => { + const result = await modelProviders.stream({ selection, message, history, images, thinking, signal: requestSignal, systemPrompt: ['You are Strata, a helpful assistant. Answer clearly. Do not claim to have read files or performed actions unless their results are included in the conversation.', skillInstructions(appliedSkills)].filter(Boolean).join('\n\n'), onFrame: frame => { if (frame.type === 'start') noteSkillUse(appliedSkills); if (frame.type === 'done') serving.mark(entry.id, { tokensIn: frame.tokensIn, tokensOut: frame.tokensOut, usageSource: frame.usageSource }); onFrame({ ...frame, requestId: entry.id, model: model.name, contextMax: model.contextMax, remoteModel: true, ...(frame.type === 'start' ? { skills: appliedSkills.map(s => s.name) } : {}) }); @@ -630,7 +647,7 @@ async function runAgentTurn({ res, controller, chatId, body, message, workspaceI } async function runTurn({ message, history = [], onFrame, signal, client, workspaceId = null, sessionId = null, remoteModel = null, runtimeModelId = undefined, nativeModelId, images=[], useTools=false, thinking='medium', thinkingBudget=0 }) { - if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, images, onFrame, signal, workspaceId }); + if (remoteModel) return runRemoteTurn({ selection: remoteModel, message, history, images, thinking, onFrame, signal, workspaceId }); if(native.hasLive()||nativeModelId){ let instance;try{instance=native.resolveInstance(nativeModelId??native.state().defaultId);}catch(e){const message=plainNoModel(e.message);onFrame({type:'error',message});return {error:message};}const started=Date.now(),cancel=new AbortController(); const entry=serving.open({client:client??'Strata chat',endpoint:'/chat/completions',model:instance.apiModelId,instanceId:instance.id,gpuIds:instance.gpus.map(String),cancel:()=>cancel.abort()}); @@ -1586,7 +1603,7 @@ async function api(req, res, path, method, url) { if (cancelMatch && method === 'POST') return json(res, 200, serving.cancel(cancelMatch[1])); // --- monitor ------------------------------------------------------------ - if (path === '/api/monitor') return json(res, 200, monitor.snapshot()); + if (path === '/api/monitor') { monitor.watch(); return json(res, 200, monitor.snapshot()); } // --- skills / workspace ------------------------------------------------- if (path === '/api/skills' && method === 'GET') { @@ -1930,6 +1947,19 @@ async function api(req, res, path, method, url) { try { return json(res, 200, await agent.approve({ chatId: b.sessionId, callId: b.toolId, decision: b.decision })); } catch (e) { return error(res, e.code === 'approval-gone' ? 409 : 400, e.message); } } + /* The desktop shell's own choices (#3402, #3477): the port it asks for, the tray, and a desktop notification through the shell. */ + if (path === '/api/locale' && method === 'GET') return json(res, 200, systemLocale()); + if (path === '/api/shell' && method === 'GET') return json(res, 200, shellState()); + if (path === '/api/shell/prefs' && method === 'POST') { + const b = await readBody(req); + try { writeShellPrefs(b); } catch (e) { return error(res, 400, e.message); } + return json(res, 200, shellState()); + } + if (path === '/api/shell/notify' && method === 'POST') { + const b = await readBody(req); + if (!shellNotifier || typeof b.title !== 'string') return json(res, 200, { shown: false }); + try { return json(res, 200, await shellNotifier.notify({ title: b.title, body: String(b.body ?? '') })); } catch { return json(res, 200, { shown: false }); } + } /* The person changed the chat's mode while a turn runs: it applies to the next tool call, goal and helpers included. */ if (path === '/api/chat/mode' && method === 'POST') { const b = await readBody(req); diff --git a/apps/host/server/local-share.mjs b/apps/host/server/local-share.mjs index bcbfc2c4..e8659c61 100644 --- a/apps/host/server/local-share.mjs +++ b/apps/host/server/local-share.mjs @@ -14,8 +14,22 @@ export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0 if (listener) throw new Error('Sharing is already starting.'); listener = http.createServer(async (req, res) => { const path = apiPath(new URL(req.url ?? '/', 'http://localhost').pathname); + const method = req.method ?? 'GET'; + // #3208: with an API key set, a browser page of any site can call the shared API - the key decides, not the + // origin. The browser's preflight (OPTIONS) never carries the key (the spec says so), so it is answered here, + // before the path check and the key check; the real request that follows still goes through both. Without a + // key no CORS headers go out, as before: the listener stays "a device on this network" (SECURITY.md), and a + // web page of another site on the internet cannot read the model through it. + if (hasKey()) { + res.setHeader('access-control-allow-origin', '*'); + res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS'); + // the headers the preflight asks for (SDKs add their own; Anthropic browser clients send anthropic-version) + res.setHeader('access-control-allow-headers', String(req.headers['access-control-request-headers'] ?? '') || 'authorization, content-type, x-api-key, x-strata-client, anthropic-version, anthropic-beta'); + res.setHeader('access-control-max-age', '600'); + if (method === 'OPTIONS') { res.writeHead(204); res.end(); return; } + } if (!['/v1/models','/v1/chat/completions','/v1/messages'].includes(path)) { res.writeHead(404); res.end('Not found'); return; } - try { await handle(req, res, path, req.method ?? 'GET'); } + try { await handle(req, res, path, method); } catch { if (!res.headersSent) res.writeHead(500); res.end('Request failed'); } }); try { await new Promise((resolve,reject) => { listener.once('error',reject); listener.listen(port,host,resolve); }); } diff --git a/apps/host/server/model-providers.mjs b/apps/host/server/model-providers.mjs index 30fa6fbd..3c6bf33e 100644 --- a/apps/host/server/model-providers.mjs +++ b/apps/host/server/model-providers.mjs @@ -1,5 +1,6 @@ /** Saved API connections. Secrets never leave the host's private credentials file. */ import { modelReadsPictures, modelSupportsReasoning } from './vision-probe.mjs'; +import { isOpenRouter, OPENROUTER_EFFORTS } from './agent/profile.mjs'; import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; @@ -49,7 +50,7 @@ export function normalizeBaseUrl(value) { const publicConnection = ({ apiKey, ...connection }) => ({ ...connection, apiKeySet: !!apiKey }); const numeric = value => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null; -export function createModelProviders({ directory, changed = () => {}, fetchImpl = fetch }) { +export function createModelProviders({ directory, changed = () => {}, fetchImpl = fetch, knownThinks = () => null }) { mkdirSync(directory, { recursive: true }); const file = join(directory, 'model-providers.json'); let connections = []; @@ -142,7 +143,7 @@ export function createModelProviders({ directory, changed = () => {}, fetchImpl const models = [...new Map(rows.filter(m => text(m.id, 256)).map(m => [m.id, { id: text(m.id, 256), name: text(m.display_name ?? m.name) || text(m.id, 256), contextMax: numeric(m.context_length ?? m.max_context_length ?? m.context_window), maxOutput: numeric(m.max_output_tokens ?? m.max_completion_tokens ?? m.top_provider?.max_completion_tokens), vision: modelReadsPictures(m), reasoning: modelSupportsReasoning(m) }])).values()]; return { models: models.sort((a, b) => a.name.localeCompare(b.name)) }; } - async function stream({ selection, message, history = [], systemPrompt = '', images = [], signal, onFrame }) { + async function stream({ selection, message, history = [], systemPrompt = '', images = [], thinking, signal, onFrame }) { const { connection, model } = resolve(selection); const started = Date.now(); const messages = history.filter(m => ['user', 'assistant'].includes(m.role) && typeof m.content === 'string').slice(-40).map(m => ({ role: m.role, content: m.content })); @@ -155,6 +156,12 @@ export function createModelProviders({ directory, changed = () => {}, fetchImpl : protocol === 'openai-responses' ? { model: model.id, input: messages, instructions: systemPrompt, stream: true, store: false } : { model: model.id, messages: [...(systemPrompt ? [{ role: 'system', content: systemPrompt }] : []), ...messages], stream: true, ...(['openai', 'deepseek', 'openrouter', 'google', 'moonshotai'].includes(connection.provider) ? { stream_options: { include_usage: true } } : {}) }; + // Match the native composer's effort names. Unknown support and other protocols keep provider defaults. + const choice = typeof thinking === 'string' ? thinking.toLowerCase() : ''; + if (protocol === 'openai-chat' && (model.reasoning ?? knownThinks(connection, model.id)) === true && ['off', 'low', 'medium', 'high', 'max'].includes(choice)) { + if (isOpenRouter(connection)) payload.reasoning = { effort: OPENROUTER_EFFORTS[choice] }; + else payload.reasoning_effort = ({ off: 'none', max: 'high' })[choice] ?? choice; + } const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(10 * 60 * 1000)]) : AbortSignal.timeout(10 * 60 * 1000); const res = await request(connection, protocol === 'anthropic' ? 'messages' : protocol === 'openai-responses' ? 'responses' : 'chat/completions', { method: 'POST', body: JSON.stringify(payload), signal: requestSignal }); if (!res.body) fail('The model API returned an empty response.'); diff --git a/apps/host/server/monitor.mjs b/apps/host/server/monitor.mjs index 4c673360..c861d9b9 100644 --- a/apps/host/server/monitor.mjs +++ b/apps/host/server/monitor.mjs @@ -3,6 +3,9 @@ import { variant as catalogVariant, footprint } from './catalog.mjs'; import { detect, cachedHardware } from './hardware.mjs'; import { readGpuTelemetry, gpuMemoryTotals } from './device-probes.mjs'; import { createSystemSampler } from './system-telemetry.mjs'; +import { sensorPace, WATCH_MS } from './sensor-pace.mjs'; +import { readTemperatures } from './temperature-telemetry.mjs'; +import { addEnergy, energyWh } from './energy-meter.mjs'; import { state as servingState } from './serving.mjs'; import { originalDashboard } from './monitor-dashboard.mjs'; import { get as getStore } from './store.mjs'; @@ -58,7 +61,17 @@ let hwCache = null; let ticker = null; let memoryWarningShown = false; let sensorsPending = false, sensorsAt = 0; +/* The Monitor screen asks (GET /api/monitor) every few seconds while it is open; a model that is loaded counts as live (#4066). */ +let watchedUntil = 0, liveProbe = () => false; +export function watch() { + const wasIdle = Date.now() >= watchedUntil; + watchedUntil = Date.now() + WATCH_MS; + if (wasIdle) sensorsAt = 0; // opening the Monitor after a quiet spell reads the card at once +} +export function setLiveProbe(probe) { liveProbe = typeof probe === 'function' ? probe : () => false; } let systemReading=null; +/* CPU and SSD temperatures (null where this PC cannot give one) and the GPU energy used since the host started (#3628). */ +let temperatures={cpuTempC:null,ssdTempC:null}; const sampleSystem=createSystemSampler(); const finite = value => typeof value==='number'&&Number.isFinite(value); function aggregate(readings,key,mode='sum') { @@ -71,7 +84,7 @@ function hardwareSnapshot() { const demo=process.env.STRATA_REAL_ENGINE!=='1',hw=state.hardware; const devices=cachedHardware()?.gpus??hwCache?.gpus??[]; const memoryPools=Math.max(1,devices.filter(g=>!g.unified).length+Number(devices.some(g=>g.unified))); - const readings=demo?devices.map((gpu,i)=>({id:gpu.id??`${gpu.vendor}:${gpu.index}`,source:'demo',sampledAt:new Date().toISOString(),utilizationPct:Math.round(clamp(hw.gpuLoad+i*2,0,100)),temperatureC:Math.round(hw.gpuTempC+i),memoryUsedGb:round(Math.min(gpu.vramGb,hw.vramUsedGb/memoryPools),2),powerW:gpu.unified?null:round(35+hw.gpuLoad*2,0),powerLimitW:gpu.unified?null:300,pcieGen:gpu.unified?null:4,pcieGenMax:gpu.unified?null:4,pcieWidth:gpu.unified?null:16,pcieRxMbs:gpu.unified?null:round(hw.gpuLoad*1.2,1)})):hw.gpus.map(g=>({...g})); + const readings=demo?devices.map((gpu,i)=>({id:gpu.id??`${gpu.vendor}:${gpu.index}`,source:'demo',sampledAt:new Date().toISOString(),utilizationPct:Math.round(clamp(hw.gpuLoad+i*2,0,100)),temperatureC:Math.round(hw.gpuTempC+i),memoryUsedGb:round(Math.min(gpu.vramGb,hw.vramUsedGb/memoryPools),2),powerW:gpu.unified?null:round(35+hw.gpuLoad*2,0),powerLimitW:gpu.unified?null:300,pcieGen:gpu.unified?null:4,pcieGenMax:gpu.unified?null:4,pcieWidth:gpu.unified?null:16,pcieRxMbs:gpu.unified?null:round(hw.gpuLoad*1.2,1),fanPct:gpu.unified?null:Math.round(30+hw.gpuLoad*0.5),clockMhz:gpu.unified?null:Math.round(1400+hw.gpuLoad*14)})):hw.gpus.map(g=>({...g})); const memory = gpuMemoryTotals(devices,readings); return { gpus:readings,cpus:systemReading?.cpus??[],cpuLoad:systemReading?.cpuLoad??null, @@ -81,7 +94,9 @@ function hardwareSnapshot() { ramUsedGb:systemReading?.ramUsedGb??null,ramTotalGb:systemReading?.ramTotalGb??hw.ramTotalGb, gpuTempC:aggregate(readings,'temperatureC','max'),tempLimitC:hw.tempLimitC, powerW:aggregate(readings,'powerW'),powerLimitW:aggregate(readings,'powerLimitW'), - pcieRxMbs:aggregate(readings,'pcieRxMbs'),diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null, + pcieRxMbs:aggregate(readings,'pcieRxMbs'), + cpuTempC:demo?54:temperatures.cpuTempC,ssdTempC:demo?41:temperatures.ssdTempC,energyWh:round(energyWh(),3), + diskReadGbs:systemReading?.diskReadGbs??null,diskWriteMbs:systemReading?.diskWriteMbs??null, }; } @@ -108,14 +123,16 @@ function approach(current, target, factor = 0.22) { } function tick() { - if(!sensorsPending&&Date.now()-sensorsAt>=3000){ + const pace=sensorPace({live:supervisor.status().running||!!liveProbe(),watchedUntil}); + if(!sensorsPending&&Date.now()-sensorsAt>=pace.intervalMs){ sensorsPending=true;sensorsAt=Date.now(); const hardware=cachedHardware()??hwCache; - void Promise.all([readGpuTelemetry(hardware?.gpus??[]),sampleSystem(hardware?.processors??[])]) - .then(([readings,system])=>{state.hardware.gpus=readings;systemReading=system;}) + void Promise.all([readGpuTelemetry(hardware?.gpus??[],{transfer:pace.transfer}),sampleSystem(hardware?.processors??[]),(process.env.STRATA_REAL_ENGINE==='1'?readTemperatures():Promise.resolve(temperatures)).catch(()=>({cpuTempC:null,ssdTempC:null}))]) + .then(([readings,system,temps])=>{state.hardware.gpus=readings;systemReading=system;temperatures=temps;}) .catch(()=>{state.hardware.gpus=[];systemReading=null;}) .finally(()=>{sensorsPending=false;}); } + addEnergy(hardwareSnapshot().powerW,Date.now()); const hw = state.hardware; const busy = state.phase === 'generating' || state.phase === 'reading' || state.phase === 'thinking'; diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 50dcac5d..895ec054 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -13,12 +13,12 @@ import { USER_KEY, capture as captureUserArgs, merge as mergeUserArgs, setFlag a import { resolvePython, venvPython } from './python-resolver.mjs'; import os from 'node:os'; import { runtimeVision } from './native-vision.mjs'; -import { componentsDirectory, installerEnvironment, controlEnvironment } from './control-runtime.mjs'; +import { componentsDirectory, installerEnvironment, controlEnvironment, sourceServerEnvironment } from './control-runtime.mjs'; import { createEngineStep } from './engine-step.mjs'; import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder, syncDataFolder, terminalSettingsFile } from './model-folder.mjs'; import { createAutoTune, writeTuneConfig } from './native-autotune.mjs'; import { plainError, PHASE_TEXT } from './update-messages.mjs'; -import { checkRunConfig, describeIssues } from './run-config-check.mjs'; +import { checkAndParseRunConfig, checkRunConfig, describeIssues } from './run-config-check.mjs'; import { openTextFile } from './open-text-file.mjs'; import { markEngine, engineRefusal } from './engine-version.mjs'; import { friendlyModelName } from './model-names.mjs'; @@ -150,7 +150,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp function settingsFile(model){const {path}=recordFile(model);return {model,path,name:basename(path),...checkRunConfig(readFileSync(path,'utf8')),note:'Changes you make in the file apply the next time the model starts.'};} async function openSettingsFile(model,options={}){const info=settingsFile(model);await openTextFile(info.path,options);return info;} /* A mistake in the file holds the start back with the line, instead of an engine that dies on it. Warnings (an unknown key) never do. */ - function assertSettingsFile(path){const check=checkRunConfig(readFileSync(path,'utf8'));if(!check.ok)throw new Error(`The settings file for this model has a mistake, so the model was not started. ${describeIssues(check.issues,'error').join(' ')}`);} + function checkedSettingsConfig(text){const check=checkAndParseRunConfig(text);if(!check.ok)throw new Error(`The settings file for this model has a mistake, so the model was not started. ${describeIssues(check.issues,'error').join(' ')}`);return check.config;} function settings(model){const {entry,config}=record(model);const values=Object.fromEntries(NATIVE_FIELDS.map(f=>[f.id,config[f.id]??null]));if(typeof values.aliases==='string')values.aliases=values.aliases.split(',').map(v=>v.trim()).filter(Boolean);values.sampling=config.sampling??{};values.args=config.args??[];values.env=publicNativeEnv(config.env??{});return {model,values,mcp:publicMcpServers(config.mcp_servers??config.mcpServers??{}),restartNeeded:true,capabilities:{dsExperts:ownEngine(config)&&dsExpertsSupported(config)},speedSwitches:speedSwitchRows(config.env??{},{deepseek:ownEngine(config),arch:config.arch??null,backend:config.backend??entry?.backend??snapshot.installed?.engine?.backend??null,gpus:snapshot.hardware?.gpus??[]})};} function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};if(patch.ds_experts!=null&&!dsExpertsSupported(config))throw new Error('The Speed choice needs the newer DeepSeek engine. Update the engine in Settings, then choose it.');for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if('vram_reserve_mib' in patch){const base=captureUserArgs(next);const mine=setUserFlag(base,'--vram-reserve-mib',patch.vram_reserve_mib);if(mine.length)next[USER_KEY]=mine;else delete next[USER_KEY];next.args=mine.length&&patch.vram_reserve_mib!==null?mergeUserArgs(next.args??[],mine):setUserFlag(next.args??[],'--vram-reserve-mib',null);delete next.ui_reserve_applied;if(Array.isArray(next.args_written))next.args_written=[...next.args];}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);} function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}} @@ -276,7 +276,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} /* Which drafter runs, when it is not the one that was asked for (the engine's own words, "Drafting: MTP (DFlash2 didn't fit)"): under Details of the load. */ async function noteDrafting(job,instance,key){let note='';try{const r=await fetcher(`http://127.0.0.1:${instance.port}/metrics`,{headers:{authorization:`Bearer ${key}`},signal:AbortSignal.timeout(2000)});if(r.ok)note=String((await r.json())?.engine?.drafting_note??'');}catch{/* a convenience */}const lines=[job.drafterNote,note].filter(Boolean);if(lines.length)job.details=[job.details,...lines].filter(Boolean).join('\n');} async function loadEngine(job,args){ - await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));}if(!entry.ready){const error=missingFilesError(args.model,entry.missing);append(args.model,error.details[0]);throw error;} + await refresh(true);if(job.state!=='running')return;const {entry,path:configFile}=recordFile(args.model);const config=checkedSettingsConfig(readFileSync(configFile,'utf8'));if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));}if(!entry.ready){const error=missingFilesError(args.model,entry.missing);append(args.model,error.details[0]);throw error;} if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); const {cfg,resources,visionPreferences,parallelChoice,parallelNote:chosenNote}=buildConfig(args,config); @@ -329,7 +329,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} try{await startWith(retryConfig);append(id,'Strata Control reports the engine is ready (second try).');} catch(second){const said2=humanStartError(second);instance.status='error';instance.error=said2;/* the first stop and the second try stay in job.details; the pop-up shows the last stop once */emit();throw new Error(instance.error);}}} } else { - proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:{...process.env,PYTHONUNBUFFERED:'1',PYTHONUTF8:'1',PYTHONIOENCODING:'utf-8',STRATA_API_KEY:''}}); + proc=spawnProcess(py,[join(repo(),'serve/server.py'),'--engine','strata','--config',configPath,'--port',String(cfg.port),'--host','127.0.0.1'],{cwd:repo(),detached:process.platform!=='win32',stdio:['ignore','pipe','pipe'],env:sourceServerEnvironment()}); instances.set(id,instance);processes.set(id,proc);if(!defaultId||!args.multiple||wasDefault)defaultId=id; for(const stream of [proc.stdout,proc.stderr])stream.on('data',chunk=>{const lines=chunk.toString().split('\n').filter(Boolean);lines.forEach(line=>append(id,line.replaceAll(key,'[redacted]')));job.summary=lines.at(-1)??job.summary;emit();}); proc.on('error',error=>{instance.status='error';instance.error=error.message;emit();});proc.on('exit',code=>{if(instances.has(id)&&instance.status!=='unloading'){instance.status='error';instance.error=`Engine stopped${code===null?'':` (exit ${code})`}. Open diagnostics or reload.`;emit();}});emit(); diff --git a/apps/host/server/native-settings.mjs b/apps/host/server/native-settings.mjs index 82f93ed8..e1ebc954 100644 --- a/apps/host/server/native-settings.mjs +++ b/apps/host/server/native-settings.mjs @@ -39,12 +39,17 @@ export const SPEED_SWITCHES=[ {id:'faster_long_prompts',label:'Faster long prompts',group:'Speed', hint:'Reads very long prompts faster by approximating part of the work. Off by default: answers about long documents can miss or mix up details.', default:'off',env:{STRATA_KVA:'1'}}, + {id:'faster_12gb_nvidia',label:'Faster answers on 12 GB NVIDIA cards',group:'Speed', + hint:'Prefers the parts of the model already on the graphics card, which makes answers much faster on 12 GB cards. Turn off if answers look worse than before.', + default:'on',env:{STRATA_ROUTE_PRIOR:'0'}}, {id:'faster_radeon_9000',label:'Faster answers on Radeon RX 9000 / AI PRO R9700',group:'Speed', hint:'Shares the work between the graphics card and the processor in a way that makes answers faster on these cards. Turn off to go back to the previous setting, which is slower.', default:'on',env:{STRATA_PCIE_FRAC_DEFAULT:'old'}}, {id:'deepseek_speedups',label:'DeepSeek speed-ups',group:'Speed', hint:'Reads long prompts faster and loads the parts of the model it needs faster. Turn off if DeepSeek stops working or its answers look wrong; it then runs as in version 0.2.6.', - default:'on',env:{DS4_FAST_ATTN:'0',DS4_ATTN_SLAB:'0',DS4_COPY_PIN:'0',DS4_COPY_HUGETLB:'0',DS4_STORE_SPARE:'0',DS4_STORE_PUT:'0'}}, + default:'on',env:{DS4_DEFAULTS:'026',DS4_FAST_ATTN:'0',DS4_ATTN_SLAB:'0',DS4_COPY_PIN:'0',DS4_COPY_HUGETLB:'0',DS4_STORE_SPARE:'0',DS4_STORE_PUT:'0'}, + /* an earlier test build wrote only these six for the same state: they read as the switch being set, and go with it */ + legacy:{DS4_FAST_ATTN:'0',DS4_ATTN_SLAB:'0',DS4_COPY_PIN:'0',DS4_COPY_HUGETLB:'0',DS4_STORE_SPARE:'0',DS4_STORE_PUT:'0'}}, ]; const GFX12=/^gfx120[01]$/i, RADEON_9000=/\b(?:RX\s*9\d{3}|AI\s*PRO\s*R97\d{2}|R97\d{2})\b/i; /** @@ -53,21 +58,29 @@ const GFX12=/^gfx120[01]$/i, RADEON_9000=/\b(?:RX\s*9\d{3}|AI\s*PRO\s*R97\d{2}|R * the Qwen3.8-Flash-Next files (the original, Swift, Coder, Unsloth, Gyro, NVFP4) have none. KVA was measured on the Flash-Next shape (48 layers, 512 * experts) and the engine declines it on any other, so "Faster long prompts" is shown for a model without an "arch" only. */ +/** A discrete NVIDIA card of 13 GiB or less: the engine's rule for residency-biased routing (not an integrated chip, not a card that shares system memory). */ +const smallNvidia=gpus=>(gpus??[]).some(g=>{ + if(g.usable===false||g.uma||g.integrated||(g.unified_gb??0)>0)return false; + const vendor=String(g.vendor??'').toLowerCase(); + if(vendor!=='nvidia'&&!(vendor===''&&/nvidia|geforce|\brtx\b|\bgtx\b|quadro|tesla/i.test(String(g.name??''))))return false; + return g.vram_gb>0&&g.vram_gb<=13; +}); export function speedSwitchApplies(id,{deepseek=false,backend=null,gpus=[],arch=null}={}){ if(id==='deepseek_speedups')return !!deepseek; if(deepseek)return false; // the Qwen engine's switches if(id==='faster_long_prompts')return !arch&&(backend==='cuda'||backend==='hip'); + if(id==='faster_12gb_nvidia')return !arch&&backend==='cuda'&&smallNvidia(gpus); // the engine's routing needs the Flash-Next shape (512 experts, top-10) and a CUDA build if(id==='faster_radeon_9000')return backend==='hip'&&(gpus??[]).some(g=>(!g.vendor||g.vendor==='amd')&&(GFX12.test(String(g.arch??''))||(!g.arch&&RADEON_9000.test(String(g.name??''))))); return false; } /** The switch is outside its default when every entry it writes is in the environment with its value; anything less or other (a hand-edited file, STRATA_KVA=0) is the default state and is left alone. */ -export function speedSwitchIsSet(env,id){const sw=SPEED_SWITCHES.find(s=>s.id===id);return !!sw&&Object.entries(sw.env).every(([name,value])=>env?.[name]===value);} +export function speedSwitchIsSet(env,id){const sw=SPEED_SWITCHES.find(s=>s.id===id),has=entries=>!!entries&&Object.keys(entries).length>0&&Object.entries(entries).every(([name,value])=>env?.[name]===value);return !!sw&&(has(sw.env)||has(sw.legacy));} /** Is the feature on for a launch with this environment? */ export function speedSwitchIsOn(env,id){const sw=SPEED_SWITCHES.find(s=>s.id===id);return !!sw&&speedSwitchIsSet(env,id)!==(sw.default==='on');} /** The environment with the feature on or off: its default removes the switch's entries, the other state writes them. Nothing else in it changes. */ export function setSpeedSwitch(env,id,on){ const sw=SPEED_SWITCHES.find(s=>s.id===id);if(!sw)throw new Error(`Unknown speed switch: ${id}`); - const write=on!==(sw.default==='on'),next={...(env??{})};for(const [name,value] of Object.entries(sw.env)){if(write)next[name]=value;else delete next[name];}return next; + const write=on!==(sw.default==='on'),next={...(env??{})};for(const [name,value] of Object.entries(sw.env)){if(write)next[name]=value;else delete next[name];}if(!write)for(const name of Object.keys(sw.legacy??{}))delete next[name];return next; } /** What the settings answer carries: each switch that applies, with its words, its default, the entries it writes outside the default, and whether the feature is on. */ export function speedSwitchRows(env,context){return SPEED_SWITCHES.filter(s=>speedSwitchApplies(s.id,context)).map(s=>({...s,on:speedSwitchIsOn(env,s.id)}));} diff --git a/apps/host/server/region.mjs b/apps/host/server/region.mjs new file mode 100644 index 00000000..312b122c --- /dev/null +++ b/apps/host/server/region.mjs @@ -0,0 +1,66 @@ +/** + * The computer's regional format, for the Monitor's cost line (#3628): which region and, where the system names it, which currency the + * person uses. Read once, without PowerShell: + * Windows the regional format (Settings > Time & language > Region > Regional format) from the registry: LocaleName ("en-US"); when it + * names no region, the country or region setting (Geo\Name). + * macOS `defaults read -g AppleLocale` ("en_US", or "de_DE@currency=CHF" when the person set another currency). + * Linux LC_ALL, LC_MONETARY or LANG ("de_DE.UTF-8"), and the locale's own currency when `locale -k int_curr_symbol` answers. + * Nothing here is a guess: no region means no answer, and the page then falls back to its own language list. + */ +import { execFileSync } from 'node:child_process'; + +const NONE = Object.freeze({ locale: null, region: null, currency: null, source: null }); + +/** "en_US.UTF-8" / "de_DE@euro" / "zh-Hans-CN" -> { locale: "en-US", region: "US" } (null parts when the tag has none). */ +export function parseLocaleTag(text) { + const tag = String(text ?? '').trim().replace(/[.@].*$/, '').replace(/_/g, '-'); + if (!tag || /^(c|posix)$/i.test(tag)) return { locale: null, region: null }; + const parts = tag.split('-'); + const region = parts.slice(1).find(p => /^[A-Za-z]{2}$/.test(p)) ?? null; + const language = /^[A-Za-z]{2,3}$/.test(parts[0]) ? parts[0].toLowerCase() : null; + if (!language) return { locale: null, region: null }; + return { locale: region ? `${language}-${region.toUpperCase()}` : language, region: region ? region.toUpperCase() : null }; +} + +export function parseRegValue(out, name) { + const m = new RegExp(`^\\s*${name}\\s+REG_SZ\\s+(.*?)\\s*$`, 'mi').exec(String(out ?? '')); + return m ? m[1] : null; +} + +const currencyCode = value => (/^[A-Z]{3}$/.test(String(value ?? '').trim().toUpperCase()) ? String(value).trim().toUpperCase() : null); + +export function detectRegion({ platform = process.platform, env = process.env, run = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', timeout: 4000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }) } = {}) { + try { + if (platform === 'win32') { + const intl = 'HKCU\\Control Panel\\International'; + const named = parseLocaleTag(parseRegValue(run('reg', ['query', intl, '/v', 'LocaleName']), 'LocaleName')); + if (named.region) return { ...named, currency: null, source: 'windows' }; + let geo = null; + try { geo = parseRegValue(run('reg', ['query', `${intl}\\Geo`, '/v', 'Name']), 'Name'); } catch { /* no country setting */ } + const region = /^[A-Za-z]{2}$/.test(geo ?? '') ? geo.toUpperCase() : null; + return region ? { locale: named.locale ? `${named.locale}-${region}` : null, region, currency: null, source: 'windows' } : { ...NONE }; + } + if (platform === 'darwin') { + const raw = String(run('defaults', ['read', '-g', 'AppleLocale'])).trim(); + const named = parseLocaleTag(raw); + const currency = currencyCode(/@currency=([A-Za-z]{3})/.exec(raw)?.[1]); + return named.region || currency ? { ...named, currency, source: 'macos' } : { ...NONE }; + } + const named = parseLocaleTag(env.LC_ALL || env.LC_MONETARY || env.LANG); + let currency = null; + try { currency = currencyCode(/int_curr_symbol="?([A-Za-z]{3})/.exec(run('locale', ['-k', 'int_curr_symbol']))?.[1]); } catch { /* no locale command */ } + return named.region || currency ? { ...named, currency, source: 'linux' } : { ...NONE }; + } catch { + return { ...NONE }; + } +} + +let cached = null; +/** The answer is cached: the regional format does not change while the host runs. */ +export function systemLocale(options) { + if (options) return detectRegion(options); + // A test or a demo can name the regional format (the screenshots of the Monitor); a packaged app never reads it. + if (process.env.STRATA_TEST_LOCALE && process.env.STRATA_PACKAGED !== '1') { const named = parseLocaleTag(process.env.STRATA_TEST_LOCALE); return { ...named, currency: null, source: 'test' }; } + cached ??= detectRegion(); + return cached; +} diff --git a/apps/host/server/run-config-check.mjs b/apps/host/server/run-config-check.mjs index fc8956a8..12ca8b84 100644 --- a/apps/host/server/run-config-check.mjs +++ b/apps/host/server/run-config-check.mjs @@ -134,6 +134,14 @@ export function checkRunConfig(text, { known = KNOWN_KEYS } = {}) { return { ok: !issues.some(i => i.level === 'error'), issues }; } +/** Validate and parse one captured text value, so callers use the checked snapshot. */ +export function checkAndParseRunConfig(text, options) { + text = String(text ?? ''); + const checked = checkRunConfig(text, options); + if (!checked.ok) return { ...checked, config: null }; + return { ...checked, config: JSON.parse(text.replace(/^\uFEFF/, '')) }; +} + /** The English lines of the issues, `Line 12: …`, for the Details of a refused start. */ export function describeIssues(issues, level) { return issues.filter(i => !level || i.level === level).map(i => `${i.line ? `Line ${i.line}: ` : ''}${i.message}`); diff --git a/apps/host/server/sensor-pace.mjs b/apps/host/server/sensor-pace.mjs new file mode 100644 index 00000000..b8884bb8 --- /dev/null +++ b/apps/host/server/sensor-pace.mjs @@ -0,0 +1,16 @@ +/** + * How often the host asks the graphics card driver for its readings (#4066). + * It used to start two nvidia-smi processes every 3 s for as long as the app was open, even with nothing loaded and + * the Monitor out of sight; on some PCs that was felt as a stutter while typing. Now the 3 s pace is kept while a model + * runs or the Monitor is being looked at, and an idle app asks once every 30 s. + */ +export const ACTIVE_MS = 3000; +export const IDLE_MS = 30000; +/** The Monitor screen asks again every 10 s while it is open; this is how long one ask keeps the fast pace. */ +export const WATCH_MS = 25000; + +/** `live`: a model is loaded or an engine runs. `watchedUntil`: ms timestamp until which the Monitor was last seen open. */ +export function sensorPace({ live = false, watchedUntil = 0, now = Date.now() } = {}) { + const watched = now < watchedUntil; + return { intervalMs: live || watched ? ACTIVE_MS : IDLE_MS, transfer: !!live }; +} diff --git a/apps/host/server/shell-prefs.mjs b/apps/host/server/shell-prefs.mjs new file mode 100644 index 00000000..a81237f8 --- /dev/null +++ b/apps/host/server/shell-prefs.mjs @@ -0,0 +1,77 @@ +/** + * The desktop shell's own choices, kept in /shell-prefs.json (#3402, #3477): the shell reads the file when it starts + * (the port it asks for, whether closing the window keeps Strata in the tray, the language of the tray menu), before any page exists. + * The page changes them through the host (POST /api/shell/prefs); a change of the port or the tray applies the next time Strata starts. + * + * { "port": 0 | 1024..65535, "tray": false, "language": "en" } + * + * Port 0 is the default: the shell asks for 47831 and takes a free port when that one is busy. + */ +import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { componentsDirectory } from './control-runtime.mjs'; + +export const DEFAULT_PORT = 47831; +export const LANGUAGES = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +export const DEFAULTS = Object.freeze({ port: 0, tray: false, language: 'en' }); + +export const validPort = value => Number.isInteger(value) && value >= 1024 && value <= 65535; + +export function shellPrefsFile({ env = process.env } = {}) { + return join(dirname(componentsDirectory({ env })), 'shell-prefs.json'); +} + +/** The file's content with every field checked; anything missing or wrong is the default. */ +export function cleanPrefs(raw) { + const value = raw && typeof raw === 'object' ? raw : {}; + return { + port: validPort(value.port) ? value.port : 0, + tray: value.tray === true, + language: LANGUAGES.includes(value.language) ? value.language : 'en', + }; +} + +export function readShellPrefs(file = shellPrefsFile()) { + try { return cleanPrefs(JSON.parse(readFileSync(file, 'utf8').replace(/^/, ''))); } catch { return { ...DEFAULTS }; } +} + +/** Merge a change into the file. Throws a plain sentence for a port that cannot be used. */ +export function writeShellPrefs(patch, file = shellPrefsFile()) { + const next = readShellPrefs(file); + if (patch && 'port' in patch) { + const wanted = patch.port === null || patch.port === '' || patch.port === 0 ? 0 : Number(patch.port); + if (wanted !== 0 && !validPort(wanted)) throw new Error('Choose a port between 1024 and 65535, or leave it empty to let Strata choose.'); + next.port = wanted; + } + if (patch && 'tray' in patch) next.tray = patch.tray === true; + if (patch && 'language' in patch && LANGUAGES.includes(patch.language)) next.language = patch.language; + mkdirSync(dirname(file), { recursive: true }); + const temporary = `${file}.${process.pid}.tmp`; + writeFileSync(temporary, JSON.stringify(next, null, 2) + '\n'); + renameSync(temporary, file); + return next; +} + +/** + * What the shell tells the host about this start: STRATA_PORT_NOTICE is "busy::" when the port it wanted was taken + * (set by the shell, never by the person). The page turns it into a sentence in the person's language. + */ +export function parsePortNotice(value) { + const m = /^busy:(\d{1,5}):(\d{1,5})$/.exec(String(value ?? '')); + return m ? { wanted: Number(m[1]), used: Number(m[2]) } : null; +} + +/** The notification route of the shell's bridge (loopback, token). Null outside the desktop app. */ +export function createShellNotifier({ env = process.env, fetcher = fetch } = {}) { + const base = env.STRATA_SHELL_BRIDGE, token = env.STRATA_SHELL_TOKEN; + if (!base || !token || !/^http:\/\/127\.0\.0\.1:\d+$/.test(base)) return null; + return { + async notify({ title, body }) { + const query = `title=${encodeURIComponent(String(title ?? '').slice(0, 120))}&body=${encodeURIComponent(String(body ?? '').slice(0, 300))}`; + const response = await fetcher(`${base}/shell/notify?${query}`, { method: 'POST', headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(5000) }); + let reply = null; + try { reply = await response.json(); } catch { /* no body */ } + return { shown: response.ok && reply?.shown === true }; + }, + }; +} diff --git a/apps/host/server/temperature-telemetry.mjs b/apps/host/server/temperature-telemetry.mjs new file mode 100644 index 00000000..0417dc04 --- /dev/null +++ b/apps/host/server/temperature-telemetry.mjs @@ -0,0 +1,124 @@ +/** + * CPU and SSD temperatures for the Monitor's Power card (#3628). A value that this PC cannot give stays null and its line is left out, + * so the card never shows a made-up number. + * + * Linux: the kernel's hwmon sensors (coretemp, k10temp, zenpower for the processor; nvme and drivetemp for the drives). + * Windows: the drive reports its own temperature to a query that needs no administrator (IOCTL_STORAGE_QUERY_PROPERTY with the device + * temperature property). Get-StorageReliabilityCounter is tried first because it is the documented route; on a normal account it is + * refused, then the query is used. One long-lived PowerShell asks every 30 s (windows-poll.mjs). + * There is no unprivileged, trustworthy processor temperature on Windows, so none is shown there. + * macOS: none. + */ +import { readFile, readdir } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; +import { createPowerShellLoop, endWithHost } from './windows-poll.mjs'; + +const CPU_SENSORS = new Set(['coretemp', 'k10temp', 'zenpower', 'cpu_thermal', 'cpu-thermal']); +const DISK_SENSORS = new Set(['nvme', 'drivetemp']); +const plausible = c => Number.isFinite(c) && c > 0 && c < 150; + +/** hwmon entries [{name, temps: [milli-degrees…]}] -> the hottest processor and drive sensor. */ +export function pickTemperatures(entries) { + let cpu = null, ssd = null; + for (const { name, temps } of entries) { + const hottest = Math.max(...temps.map(t => t / 1000).filter(plausible), -Infinity); + if (!Number.isFinite(hottest)) continue; + if (CPU_SENSORS.has(name)) cpu = Math.max(cpu ?? -Infinity, hottest); + else if (DISK_SENSORS.has(name)) ssd = Math.max(ssd ?? -Infinity, hottest); + } + return { cpuTempC: cpu === null ? null : Math.round(cpu), ssdTempC: ssd === null ? null : Math.round(ssd) }; +} + +export async function readLinuxTemperatures({ base = '/sys/class/hwmon', read = readFile, list = readdir } = {}) { + const entries = []; + let folders = []; + try { folders = await list(base); } catch { return { cpuTempC: null, ssdTempC: null }; } + for (const folder of folders) { + try { + const name = String(await read(`${base}/${folder}/name`, 'utf8')).trim(); + if (!CPU_SENSORS.has(name) && !DISK_SENSORS.has(name)) continue; + const files = (await list(`${base}/${folder}`)).filter(f => /^temp\d+_input$/.test(f)); + const temps = []; + for (const file of files) temps.push(Number(String(await read(`${base}/${folder}/${file}`, 'utf8')).trim())); + entries.push({ name, temps }); + } catch { /* a sensor that disappears is skipped */ } + } + return pickTemperatures(entries); +} + +/** One line of the Windows loop: "ssd 53" or "ssd -". */ +export function parseSsdLine(line) { + const m = /^\s*ssd\s+(-?\d+|-)\s*$/.exec(String(line)); + if (!m) return undefined; + const value = m[1] === '-' ? NaN : Number(m[1]); + return plausible(value) ? value : null; +} + +const WINDOWS_SCRIPT = String.raw` +$ErrorActionPreference='SilentlyContinue' +$cs=@' +using System; +using System.Runtime.InteropServices; +public static class StrataDiskTemp { + [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateFile(string n, uint a, uint s, IntPtr p, uint d, uint f, IntPtr t); + [DllImport("kernel32.dll", SetLastError=true)] static extern bool DeviceIoControl(IntPtr h, uint c, byte[] i, uint il, byte[] o, uint ol, out uint r, IntPtr ov); + [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); + public static int Read(int n) { + IntPtr h = CreateFile("\\\\.\\PhysicalDrive" + n, 0, 3, IntPtr.Zero, 3, 0, IntPtr.Zero); + if (h == (IntPtr)(-1)) return -1; + try { + byte[] q = new byte[12]; q[0] = 0x34; byte[] o = new byte[512]; uint r; + if (!DeviceIoControl(h, 0x002D1400, q, 12, o, 512, out r, IntPtr.Zero)) return -1; + if (BitConverter.ToUInt16(o, 12) < 1) return -1; + return BitConverter.ToInt16(o, 26); + } finally { CloseHandle(h); } + } +} +'@ +$compiled=$false +while($true){ + $max=-1 + $c=@(Get-PhysicalDisk | Get-StorageReliabilityCounter | Where-Object { $_.Temperature -gt 0 }) + if($c.Count -gt 0){ $max=($c | Measure-Object Temperature -Maximum).Maximum } + else { + if(-not $compiled){ Add-Type -TypeDefinition $cs; $compiled=$true } + foreach($n in 0..15){ $v=[StrataDiskTemp]::Read($n); if($v -gt $max){ $max=$v } } + } + if($max -gt 0){ [Console]::Out.WriteLine('ssd '+$max) } else { [Console]::Out.WriteLine('ssd -') } + [Console]::Out.Flush() + Start-Sleep -Seconds 30 +}`; + +export function createWindowsSsdReader({ spawnFn = spawn, maxStarts = 2, now = Date.now, intervalSec = 30 } = {}) { + let latest = null; + const loop = createPowerShellLoop({ + script: WINDOWS_SCRIPT, spawnFn, maxStarts, + onLine: line => { + const parsed = parseSsdLine(line); + if (parsed === undefined) return false; + latest = { value: parsed, at: now() }; + return true; + }, + }); + return { + read() { loop.start(); return latest && now() - latest.at < 4 * intervalSec * 1000 ? latest.value : null; }, + stop() { loop.stop(); }, + get starts() { return loop.starts; }, + }; +} + +let windowsReader = null; +let linuxCache = { at: 0, value: { cpuTempC: null, ssdTempC: null } }; + +/** The temperatures this PC can give now: { cpuTempC, ssdTempC } (null where unreadable). Cheap to call every few seconds. */ +export async function readTemperatures({ platform = process.platform, now = Date.now } = {}) { + if (platform === 'linux') { + if (now() - linuxCache.at > 10_000) linuxCache = { at: now(), value: await readLinuxTemperatures() }; + return linuxCache.value; + } + if (platform === 'win32') { + windowsReader ??= endWithHost(createWindowsSsdReader()); + return { cpuTempC: null, ssdTempC: windowsReader.read() }; + } + return { cpuTempC: null, ssdTempC: null }; +} diff --git a/apps/host/src/components/ElectricityPrice.tsx b/apps/host/src/components/ElectricityPrice.tsx new file mode 100644 index 00000000..16851877 --- /dev/null +++ b/apps/host/src/components/ElectricityPrice.tsx @@ -0,0 +1,29 @@ +import { useEffect, useMemo, useState } from 'react'; +import { currencyChoices, currencyLabel } from '../lib/currency'; +import { tr } from '../lib/i18n'; +import { useMoney } from '../lib/money'; +import { setElectricity, useStore } from '../lib/store'; +import { Btn, Select } from './ui'; + +/** + * The price of one kWh for the Monitor's cost line (#3628). The person types only the number: the currency is the one of the computer's + * region, shown beside it. "Change currency" is a way to pick another one, never a step that has to be taken. + */ +export function ElectricityPrice() { + const price = useStore(s => s.electricityPrice), override = useStore(s => s.electricityCurrency); + const money = useMoney(); + const [text, setText] = useState(price > 0 ? String(price) : ''), [picking, setPicking] = useState(false); + useEffect(() => { setText(price > 0 ? String(price) : ''); }, [price]); + const commit = () => setElectricity(Number(text.replace(',', '.')), override); + const choices = useMemo(() => currencyChoices(money.locale), [money.locale]); + return + + setText(e.target.value)} onBlur={commit} onKeyDown={e => { if (e.key === 'Enter') commit(); }}/> + {money.currency ? tr("per kWh, in {0}", [currencyLabel(money.currency, money.locale)]) : tr("per kWh")} + setPicking(v => !v)}>{tr("Change currency")} + + {picking ? setSplit(e.target.value)}/> : null)}
{tr(installed ? <> :

{tr("More engine parameters become available after preparing this version.")}

)} : null)} - + !pending && setPlan(null)} actions={<> setPlan(null)}>{tr("Cancel")} void download()}>{tr(installed?.ready ? "Apply & load" : "Download & load")}}>

{tr(plan?.plan?.title ?? selectedFamily?.title)}{tr(installed?.ready ? null : <>{tr(" \u00B7 approximately ")}{tr(plan?.plan?.download_gb ?? selectedSize?.download_gb)}{tr(" GB")})}

{tr(plan?.drafting?.needed ?

{tr("Choosing DFlash2 also downloads its drafter: about {0} GB, once. If it does not fit in graphics memory, the model uses the MTP instead.", [plan.drafting.gb])}

: null)}{tr(installed?.ready ?

{tr("The model files are already on this computer. Nothing will be downloaded; only the settings you chose are applied.")}

: null)}{tr(plan?.plan?.disk_short ? : null)}{tr(installed?.ready ?

{tr("Any currently loaded native models will be unloaded first.")}

: <>

{tr("Existing files are checked and reused. Any currently loaded native models will be unloaded before preparing files.")}

{tr("Your computer may feel slower while weights load. You can stop the download and resume later.")}

)}{tr(selectedSize?.images ?

{tr("Vision encoder files are included. Picture reading loads only when enabled.")}

: null)}
diff --git a/apps/host/src/components/NativeSettings.tsx b/apps/host/src/components/NativeSettings.tsx index 062874f1..356652fa 100644 --- a/apps/host/src/components/NativeSettings.tsx +++ b/apps/host/src/components/NativeSettings.tsx @@ -16,8 +16,11 @@ interface SpeedSwitch { hint: string; default: 'on' | 'off'; env: Record; + /** What an earlier test build wrote for the same state: it reads as set, and goes with it. */ + legacy?: Record; } -const switchIsSet = (sw: SpeedSwitch, env: Record | undefined) => Object.entries(sw.env).every(([name, value]) => env?.[name] === value); +const switchHas = (entries: Record | undefined, env: Record | undefined) => !!entries && Object.keys(entries).length > 0 && Object.entries(entries).every(([name, value]) => env?.[name] === value); +const switchIsSet = (sw: SpeedSwitch, env: Record | undefined) => switchHas(sw.env, env) || switchHas(sw.legacy, env); const switchIsOn = (sw: SpeedSwitch, env: Record | undefined) => switchIsSet(sw, env) !== (sw.default === 'on'); export function NativeSettings({ model }: { model: string; @@ -61,7 +64,7 @@ export function NativeSettings({ model }: { }, [model,revision]); const change = (id: string, value: any) => { const next = { ...values, [id]: value }; setValues(next); setText(JSON.stringify(next, null, 2)); setNotice(''); }; /** The default removes the switch's environment entries, the other state writes them: the model's file then carries nothing for a default launch. */ - const changeSwitch = (sw: SpeedSwitch, on: boolean) => { const env = { ...(values.env ?? {}) }; const write = on !== (sw.default === 'on'); for (const [name, value] of Object.entries(sw.env)) { if (write) env[name] = value; else delete env[name]; } change('env', env); }; + const changeSwitch = (sw: SpeedSwitch, on: boolean) => { const env = { ...(values.env ?? {}) }; const write = on !== (sw.default === 'on'); for (const [name, value] of Object.entries(sw.env)) { if (write) env[name] = value; else delete env[name]; } if (!write) for (const name of Object.keys(sw.legacy ?? {})) delete env[name]; change('env', env); }; async function save() { setPending(true); setError(''); diff --git a/apps/host/src/components/PcFitCard.tsx b/apps/host/src/components/PcFitCard.tsx index 17ca134b..62a5e2a1 100644 --- a/apps/host/src/components/PcFitCard.tsx +++ b/apps/host/src/components/PcFitCard.tsx @@ -15,7 +15,7 @@ function Meter({ label, total, use }: { label: string; total: number; use: numbe * "This computer": the graphics memory and RAM, and what the chosen version would take of each. One plain line says whether it fits * or how much would be read from the SSD (the n-gram table, which always sits on the SSD, is not counted). */ -export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null }) { +export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null, diskGb = null }: { gpuName?: string | null; ramGb: number | null; vramGb: number; fit: Fit | null; inUse?: { ramGb: number; vramGb: number } | null; diskGb?: number | null }) { const freeVram = Math.max(0, vramGb - (inUse?.vramGb ?? 0)), freeRam = ramGb ? Math.max(0, ramGb - (inUse?.ramGb ?? 0)) : 0; return

{tr("This computer")}

@@ -23,6 +23,7 @@ export function PcFitCard({ gpuName, ramGb, vramGb, fit, inUse = null }: { gpuNa {tr(fit?.known && vramGb > 0 ? : null)} {tr(fit?.known && ramGb ? : null)} {tr(inUse ?

{tr("Models that stay loaded use about {0} GB of RAM and {1} GB of this card’s memory.", [inUse.ramGb, inUse.vramGb])}

: null)} - {tr(fit?.known ?

{tr(fit.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit.spillGb)])}

: null)} + {tr(diskGb ?

{tr("Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", [Math.round(diskGb)])}

: null)} + {tr(fit?.known && (diskGb ? fit.spillGb >= 1 : true) ?

{tr(fit.spillGb >= 1 ? 'About {0} GB will be read from the SSD, so answers can be a little slower.' : 'Fits fully in memory.', [Math.round(fit.spillGb)])}

: null)}
; } diff --git a/apps/host/src/components/ShellSettings.tsx b/apps/host/src/components/ShellSettings.tsx new file mode 100644 index 00000000..32cf0839 --- /dev/null +++ b/apps/host/src/components/ShellSettings.tsx @@ -0,0 +1,74 @@ +import { useEffect, useState } from 'react'; +import { api } from '../lib/client'; +import { tr } from '../lib/i18n'; +import { askNotificationPermission, playDoneSound } from '../lib/attention'; +import { setApprovalNotify, setDoneSound, useStore } from '../lib/store'; +import { Btn } from './ui'; + +/** What the host says about the desktop shell (GET /api/shell): null in a browser or while it loads. */ +export interface ShellState { + desktop: boolean; + tray: boolean; + port: number; + defaultPort: number; + pinnedPort: number | null; + minimizeToTray: boolean; + portNotice: { wanted: number; used: number } | null; +} + +export function useShellState(): [ShellState | null, (patch: { port?: number | null; tray?: boolean }) => Promise] { + const [shell, setShell] = useState(null); + useEffect(() => { + let alive = true; + api.get('/api/shell').then(s => { if (alive) setShell(s); }).catch(() => undefined); + return () => { alive = false; }; + }, []); + const save = async (patch: { port?: number | null; tray?: boolean }) => { + try { setShell(await api.post('/api/shell/prefs', patch)); return null; } + catch (error) { return error instanceof Error ? error.message : 'The choice was not saved.'; } + }; + return [shell, save]; +} + +/** The sound for finished work (#3586): off until switched on, with a button to hear it. */ +export function DoneSoundSetting() { + const on = useStore(s => s.doneSound); + return + playDoneSound()}>{tr("Play sound")} + {tr(open ? setOpen(false)}> diff --git a/apps/host/src/lib/attention.ts b/apps/host/src/lib/attention.ts new file mode 100644 index 00000000..46d19c5f --- /dev/null +++ b/apps/host/src/lib/attention.ts @@ -0,0 +1,85 @@ +/** + * Telling the person that Strata needs them or has finished (#3586, #3477). Both are opt-in and off by default. + * + * - A short sound when an answer or task that took a while is finished, or when Strata is in the background (public/strata-done-sound.wav, + * made for Strata from sine waves, no sample). + * - A desktop notification when Manual mode waits for an approval and Strata is in the background. The desktop app shows it through its own + * shell (the host passes it on, so it also works while the window is hidden in the tray); a browser uses the page's notifications. + */ +import { api } from './client'; +import { tr } from './i18n'; + +/** An answer that came back faster than this does not chime while the person is looking at the window. */ +export const QUICK_MS = 8000; +const SOUND_URL = '/strata-done-sound.wav'; +const MIN_GAP_MS = 2000; +let lastPlayed = 0; + +export interface DoneContext { enabled: boolean; durationMs: number; focused: boolean; now?: number } + +/** Whether the finished-work sound should play now: only when asked for, only for work that took a while or when the window is not in front. */ +export function shouldPlayDone({ enabled, durationMs, focused, now = Date.now() }: DoneContext): boolean { + if (!enabled) return false; + if (now - lastPlayed < MIN_GAP_MS) return false; + return !focused || durationMs >= QUICK_MS; +} + +export const windowInFront = (): boolean => typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus(); + +export function playDoneSound(make: (url: string) => { volume: number; play(): Promise | void } = url => new Audio(url)): boolean { + try { + const audio = make(SOUND_URL); + audio.volume = 0.6; + lastPlayed = Date.now(); + const started = audio.play(); + if (started && typeof (started as Promise).catch === 'function') (started as Promise).catch(() => { /* the browser asked for a click first: no sound this time */ }); + return true; + } catch { + return false; + } +} + +/** Called when an answer or a task is finished. */ +export function workFinished(enabled: boolean, durationMs: number): void { + if (shouldPlayDone({ enabled, durationMs, focused: windowInFront() })) playDoneSound(); +} + +export interface Notice { title: string; body: string } + +/** The sentence of the approval notification, in the person's language. */ +export function approvalNotice(tool: string): Notice { + return { title: tr('Strata needs your answer'), body: tr('The assistant wants to use {0}. Open Strata to approve or deny.', [tool || tr('a tool')]) }; +} + +/** Shows a notification through the desktop shell when there is one, else through the page. Returns whether something was shown. */ +export async function showNotice(notice: Notice, deps: { post?: (body: Notice) => Promise<{ shown?: boolean }>; page?: (notice: Notice) => boolean } = {}): Promise { + const post = deps.post ?? (body => api.post<{ shown?: boolean }>('/api/shell/notify', body)); + try { + const result = await post(notice); + if (result?.shown) return true; + } catch { /* no shell here: the page's own notification below */ } + return (deps.page ?? pageNotification)(notice); +} + +function pageNotification(notice: Notice): boolean { + try { + if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false; + new Notification(notice.title, { body: notice.body, tag: 'strata-approval' }); + return true; + } catch { + return false; + } +} + +/** Manual mode waits for an approval. Only a window that is not in front needs the notification. */ +export function approvalNeeded(enabled: boolean, tool: string, focused = windowInFront()): Promise { + if (!enabled || focused) return Promise.resolve(false); + return showNotice(approvalNotice(tool)); +} + +/** Turning approval notifications on in a browser asks the page's permission once; the desktop shell needs none. */ +export async function askNotificationPermission(): Promise { + try { + if (typeof Notification !== 'undefined' && Notification.permission === 'default') await Notification.requestPermission(); + } catch { /* some web views have none */ } +} diff --git a/apps/host/src/lib/currency.ts b/apps/host/src/lib/currency.ts new file mode 100644 index 00000000..3a7a7a51 --- /dev/null +++ b/apps/host/src/lib/currency.ts @@ -0,0 +1,114 @@ +/** + * The currency of the Monitor's cost line (#3628): the person's own, found from the computer's region, never typed and never a guess. + * + * Order: the system (the host reads the regional format of Windows, macOS or Linux: its region, or its currency when the system names one), + * then the browser's language list, then the region of the app's language, and then no currency at all: the number is shown without a + * symbol rather than in a currency the person does not use. A currency picked in Settings overrides all of this. + */ + +/** ISO 3166 region -> ISO 4217 currency. */ +const PAIRS = `AD:EUR AE:AED AF:AFN AG:XCD AI:XCD AL:ALL AM:AMD AO:AOA AR:ARS AS:USD AT:EUR AU:AUD AW:AWG AX:EUR AZ:AZN +BA:BAM BB:BBD BD:BDT BE:EUR BF:XOF BG:EUR BH:BHD BI:BIF BJ:XOF BL:EUR BM:BMD BN:BND BO:BOB BQ:USD BR:BRL BS:BSD BT:BTN BV:NOK BW:BWP BY:BYN BZ:BZD +CA:CAD CC:AUD CD:CDF CF:XAF CG:XAF CH:CHF CI:XOF CK:NZD CL:CLP CM:XAF CN:CNY CO:COP CR:CRC CU:CUP CV:CVE CW:XCG CX:AUD CY:EUR CZ:CZK +DE:EUR DJ:DJF DK:DKK DM:XCD DO:DOP DZ:DZD EC:USD EE:EUR EG:EGP EH:MAD ER:ERN ES:EUR ET:ETB FI:EUR FJ:FJD FK:FKP FM:USD FO:DKK FR:EUR +GA:XAF GB:GBP GD:XCD GE:GEL GF:EUR GG:GBP GH:GHS GI:GIP GL:DKK GM:GMD GN:GNF GP:EUR GQ:XAF GR:EUR GS:GBP GT:GTQ GU:USD GW:XOF GY:GYD +HK:HKD HM:AUD HN:HNL HR:EUR HT:HTG HU:HUF ID:IDR IE:EUR IL:ILS IM:GBP IN:INR IO:USD IQ:IQD IR:IRR IS:ISK IT:EUR +JE:GBP JM:JMD JO:JOD JP:JPY KE:KES KG:KGS KH:KHR KI:AUD KM:KMF KN:XCD KP:KPW KR:KRW KW:KWD KY:KYD KZ:KZT +LA:LAK LB:LBP LC:XCD LI:CHF LK:LKR LR:LRD LS:LSL LT:EUR LU:EUR LV:EUR LY:LYD +MA:MAD MC:EUR MD:MDL ME:EUR MF:EUR MG:MGA MH:USD MK:MKD ML:XOF MM:MMK MN:MNT MO:MOP MP:USD MQ:EUR MR:MRU MS:XCD MT:EUR MU:MUR MV:MVR MW:MWK MX:MXN MY:MYR MZ:MZN +NA:NAD NC:XPF NE:XOF NF:AUD NG:NGN NI:NIO NL:EUR NO:NOK NP:NPR NR:AUD NU:NZD NZ:NZD OM:OMR +PA:PAB PE:PEN PF:XPF PG:PGK PH:PHP PK:PKR PL:PLN PM:EUR PR:USD PS:ILS PT:EUR PW:USD PY:PYG QA:QAR RE:EUR RO:RON RS:RSD RU:RUB RW:RWF +SA:SAR SB:SBD SC:SCR SD:SDG SE:SEK SG:SGD SH:SHP SI:EUR SJ:NOK SK:EUR SL:SLE SM:EUR SN:XOF SO:SOS SR:SRD SS:SSP ST:STN SV:USD SX:XCG SY:SYP SZ:SZL +TC:USD TD:XAF TF:EUR TG:XOF TH:THB TJ:TJS TK:NZD TL:USD TM:TMT TN:TND TO:TOP TR:TRY TT:TTD TV:AUD TW:TWD TZ:TZS +UA:UAH UG:UGX UM:USD US:USD UY:UYU UZ:UZS VA:EUR VC:XCD VE:VES VG:USD VI:USD VN:VND VU:VUV WF:XPF WS:WST XK:EUR YE:YER YT:EUR ZA:ZAR ZM:ZMW ZW:ZWG`; + +export const REGION_CURRENCY: Readonly> = Object.freeze(Object.fromEntries(PAIRS.split(/\s+/).map(pair => pair.split(':') as [string, string]))); + +/** The region of each app language that has one region of its own; English and Spanish-speaking countries are many, so only the first is a guess. */ +export const LANGUAGE_REGION: Readonly> = Object.freeze({ zh: 'CN', ja: 'JP', de: 'DE', es: 'ES', ru: 'RU', pt: 'BR', ko: 'KR' }); + +export const currencyForRegion = (region: string | null | undefined): string | null => (region ? REGION_CURRENCY[region.toUpperCase()] ?? null : null); + +/** The region in a language tag ("en-US", "de_DE.UTF-8", "zh-Hans-CN"), or null when the tag names none. */ +export function regionOfLocale(tag: string | null | undefined): string | null { + if (!tag) return null; + const clean = String(tag).replace(/[.@].*$/, '').replace(/_/g, '-'); + try { + const region = new Intl.Locale(clean).region; + return region ?? null; + } catch { + const found = /-([A-Za-z]{2})(?:-|$)/.exec(clean); + return found ? found[1].toUpperCase() : null; + } +} + +/** What the host read from the system (GET /api/locale). */ +export interface SystemLocale { locale: string | null; region: string | null; currency: string | null; source: string | null } + +export interface ResolvedCurrency { currency: string | null; locale: string; source: 'system' | 'browser' | 'language' | 'none' } + +/** + * The currency to show money in, and the locale to write the number in. + * `override` is the currency the person chose in Settings (empty: automatic). + */ +export function resolveCurrency({ system, browserLanguages = [], language, override = '' }: { system?: SystemLocale | null; browserLanguages?: readonly string[]; language: string; override?: string }): ResolvedCurrency { + const appTag = language === 'zh' ? 'zh-CN' : language; + const locale = system?.locale ?? browserLanguages.find(tag => regionOfLocale(tag)) ?? browserLanguages[0] ?? appTag; + if (/^[A-Za-z]{3}$/.test(override)) return { currency: override.toUpperCase(), locale, source: 'system' }; + const fromSystem = system?.currency ?? currencyForRegion(system?.region); + if (fromSystem) return { currency: fromSystem, locale, source: 'system' }; + for (const tag of browserLanguages) { + const found = currencyForRegion(regionOfLocale(tag)); + if (found) return { currency: found, locale, source: 'browser' }; + } + const fromLanguage = currencyForRegion(LANGUAGE_REGION[language]); + if (fromLanguage) return { currency: fromLanguage, locale, source: 'language' }; + return { currency: null, locale, source: 'none' }; +} + +/** How many decimals this currency normally has (2 for dollars and euros, 0 for yen); 2 when there is no currency. */ +export function minorDigits(currency: string | null, locale: string): number { + if (!currency) return 2; + try { return new Intl.NumberFormat(locale, { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2; } catch { return 2; } +} + +/** + * An amount of money, written for the person's locale with the currency's usual digits ("$0.12", "$1.23", "1,23 €", "¥3"). + * An amount below the smallest normal unit (one cent; one yen) is not shown as 0.00 or as a long run of decimals but as + * "less than $0.01" (`lessThan` writes the sentence in the person's language). With no currency the number is shown alone, + * and never in a currency that was only guessed. + */ +export function formatMoney(amount: number, { currency, locale, lessThan = shown => `less than ${shown}` }: { currency: string | null; locale: string; lessThan?: (shown: string) => string }): string { + if (!Number.isFinite(amount) || amount < 0) return '—'; + const digits = minorDigits(currency, locale), unit = 10 ** -digits; + const write = (value: number): string => { + try { + if (currency) return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value); + } catch { /* an unknown currency code or locale: the number alone */ } + try { + return new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value); + } catch { + return value.toFixed(digits); + } + }; + return amount > 0 && amount < unit ? lessThan(write(unit)) : write(amount); +} + +/** "USD ($)": the code and its symbol in the person's locale, for the Settings line. */ +export function currencyLabel(currency: string, locale: string): string { + try { + const symbol = new Intl.NumberFormat(locale, { style: 'currency', currency, currencyDisplay: 'narrowSymbol' }).formatToParts(0).find(part => part.type === 'currency')?.value; + return symbol && symbol !== currency ? `${currency} (${symbol})` : currency; + } catch { + return currency; + } +} + +/** Every currency this web view knows, by name, for the override list. */ +export function currencyChoices(locale: string): { value: string; label: string }[] { + let codes: string[] = []; + try { codes = (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.('currency') ?? []; } catch { /* an older web view */ } + let names: Intl.DisplayNames | null = null; + try { names = new Intl.DisplayNames([locale], { type: 'currency' }); } catch { /* no names */ } + return codes.map(code => ({ value: code, label: `${code} – ${names?.of(code) ?? code}` })); +} diff --git a/apps/host/src/lib/follow-scroll.ts b/apps/host/src/lib/follow-scroll.ts new file mode 100644 index 00000000..25da2519 --- /dev/null +++ b/apps/host/src/lib/follow-scroll.ts @@ -0,0 +1,38 @@ +/** + * When a chat follows the newest token, and when the reader has let go (#4014). + * + * The old rule asked "is the reader within 120 px of the bottom?" on every streamed token and pulled the view + * back if so. One wheel notch is about 100 px, so it always landed inside that band and was undone by the next + * token; only a scrollbar drag, which jumps further, got away. The rule now follows what the reader did: + * a wheel, finger or key moving up lets go at once, and the chat follows again when the reader is back at + * the bottom. + */ +export interface Scroller { scrollHeight: number; scrollTop: number; clientHeight: number } + +/** Pixels of slack that still count as "at the bottom" (the same as `atBottom` in reasoning.ts). */ +export const FOLLOW_SLACK = 24; +/** Past this far from the bottom the "jump to latest" button is offered. */ +export const PILL_DISTANCE = 400; +/** A scroll this soon after the reader's own input was the reader's. */ +export const INPUT_WINDOW_MS = 400; + +export const distanceFromBottom = (el: Scroller): number => el.scrollHeight - el.scrollTop - el.clientHeight; + +/** + * Whether the chat should keep following after a scroll event. + * - back at the bottom: follow again; + * - the reader moved it (a wheel, finger, key or the scrollbar a moment ago) and it is not at the bottom: let go; + * - far away whatever moved it (a jump): let go; + * - otherwise (the page grew under a following reader and no input came): keep the state it had. + */ +export function followAfterScroll(distance: number, wasFollowing: boolean, msSinceInput: number): boolean { + if (distance <= FOLLOW_SLACK) return true; + if (msSinceInput <= INPUT_WINDOW_MS || distance > PILL_DISTANCE) return false; + return wasFollowing; +} + +/** A wheel turned up (negative delta) or a finger dragging the content down: the reader wants to go back. */ +export const wheelLeavesBottom = (deltaY: number): boolean => deltaY < 0; + +/** Keys that move a scroller up. */ +export const KEYS_UP = new Set(['PageUp', 'ArrowUp', 'Home']); diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 952e3ca2..8a429c46 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -7,6 +7,7 @@ import tune_es from '../locales/tune-es.json'; import tune_ru from '../locales/tune-ru.json'; import tune_pt from '../locales/tune-pt.json'; import tune_ko from '../locales/tune-ko.json'; +import tune_fr from '../locales/tune-fr.json'; import tools_en from '../locales/tools-en.json'; import tools_zh from '../locales/tools-zh.json'; import tools_ja from '../locales/tools-ja.json'; @@ -15,6 +16,7 @@ import tools_es from '../locales/tools-es.json'; import tools_ru from '../locales/tools-ru.json'; import tools_pt from '../locales/tools-pt.json'; import tools_ko from '../locales/tools-ko.json'; +import tools_fr from '../locales/tools-fr.json'; import fix_en from '../locales/fix-en.json'; import fix_zh from '../locales/fix-zh.json'; import fix_ja from '../locales/fix-ja.json'; @@ -23,6 +25,17 @@ import fix_es from '../locales/fix-es.json'; import fix_ru from '../locales/fix-ru.json'; import fix_pt from '../locales/fix-pt.json'; import fix_ko from '../locales/fix-ko.json'; +import fix_fr from '../locales/fix-fr.json'; +/* The strings of the 0.2.7 GitHub items (gh-.json, scripts/make-gh-locales.py). */ +import gh_en from '../locales/gh-en.json'; +import gh_zh from '../locales/gh-zh.json'; +import gh_ja from '../locales/gh-ja.json'; +import gh_de from '../locales/gh-de.json'; +import gh_es from '../locales/gh-es.json'; +import gh_ru from '../locales/gh-ru.json'; +import gh_pt from '../locales/gh-pt.json'; +import gh_ko from '../locales/gh-ko.json'; +import gh_fr from '../locales/gh-fr.json'; import base_zh from '../locales/zh.json'; import base_ja from '../locales/ja.json'; import base_de from '../locales/de.json'; @@ -30,15 +43,16 @@ import base_es from '../locales/es.json'; import base_ru from '../locales/ru.json'; import base_pt from '../locales/pt.json'; import base_ko from '../locales/ko.json'; +import base_fr from '../locales/fr.json'; -export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; +export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'fr',label:'Français'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-.json (scripts/make-fix-locales.py). */ -const english:Record={...baseEnglish,...tune_en,...tools_en,...fix_en}; -const [zh,ja,de,es,ru,pt,ko]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja},{...base_de,...tune_de,...tools_de,...fix_de},{...base_es,...tune_es,...tools_es,...fix_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko}] as Record[]; -const catalogs:Record>={en:english,zh,ja,de,es,ru,pt,ko}; +const english:Record={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en}; +const [zh,ja,de,es,ru,pt,ko,fr]=[{...base_zh,...tune_zh,...tools_zh,...fix_zh,...gh_zh},{...base_ja,...tune_ja,...tools_ja,...fix_ja,...gh_ja},{...base_de,...tune_de,...tools_de,...fix_de,...gh_de},{...base_es,...tune_es,...tools_es,...fix_es,...gh_es},{...base_ru,...tune_ru,...tools_ru,...fix_ru,...gh_ru},{...base_pt,...tune_pt,...tools_pt,...fix_pt,...gh_pt},{...base_ko,...tune_ko,...tools_ko,...fix_ko,...gh_ko},{...base_fr,...tune_fr,...tools_fr,...fix_fr,...gh_fr}] as Record[]; +const catalogs:Record>={en:english,zh,ja,de,fr,es,ru,pt,ko}; const entities:Record={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\u00a0'}; const decode=(text:string)=>text.replace(/&(#x[\da-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(whole,key:string)=>key[0]==='#'?String.fromCodePoint(key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):parseInt(key.slice(1),10)):entities[key]??whole); const ids=new Map(Object.entries(english).map(([id,value])=>[decode(value),id])); diff --git a/apps/host/src/lib/money.ts b/apps/host/src/lib/money.ts new file mode 100644 index 00000000..9da6d759 --- /dev/null +++ b/apps/host/src/lib/money.ts @@ -0,0 +1,28 @@ +import { useEffect, useState } from 'react'; +import { tr } from './i18n'; +import { api } from './client'; +import { formatMoney, resolveCurrency, type ResolvedCurrency, type SystemLocale } from './currency'; +import { useStore } from './store'; + +let asked: Promise | null = null; + +/** The computer's regional format, read once from the host (null in a browser build that has none, or while it loads). */ +export function useSystemLocale(): SystemLocale | null { + const [value, setValue] = useState(null); + useEffect(() => { + let alive = true; + asked ??= api.get('/api/locale').catch(() => null); + void asked.then(v => { if (alive) setValue(v); }); + return () => { alive = false; }; + }, []); + return value; +} + +/** The person's currency and locale for money (#3628) and a function that writes an amount in them. */ +export function useMoney(): ResolvedCurrency & { format: (amount: number) => string; detected: string | null } { + const system = useSystemLocale(), language = useStore(s => s.language), override = useStore(s => s.electricityCurrency); + const browserLanguages = typeof navigator === 'undefined' ? [] : [...(navigator.languages ?? [navigator.language])].filter(Boolean); + const resolved = resolveCurrency({ system, browserLanguages, language, override }); + const detected = override ? resolveCurrency({ system, browserLanguages, language }).currency : resolved.currency; + return { ...resolved, detected, format: amount => formatMoney(amount, { ...resolved, lessThan: shown => tr('less than {0}', [shown]) }) }; +} diff --git a/apps/host/src/lib/native-monitor.ts b/apps/host/src/lib/native-monitor.ts index f2c4bf5b..16846852 100644 --- a/apps/host/src/lib/native-monitor.ts +++ b/apps/host/src/lib/native-monitor.ts @@ -54,7 +54,9 @@ export function withHostSensors(live:MonitorState,host:MonitorState|null):Monito const empty=(g:GpuReading)=>![g.utilizationPct,g.temperatureC,g.memoryUsedGb,g.powerW].some(hasReading); const pick=(a:T,b:T)=>hasReading(a as unknown)?a:b; return {...live,hardware:{...h, - gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);return sensor&&empty(g)?{...g,...sensor}:g;}), + // The fan and the clock are the host's own readings; the engine's metrics do not carry them (#3628). + gpus:(h.gpus??[]).map(g=>{const sensor=s.gpus?.find(x=>x.id===g.id);const own=sensor&&empty(g)?{...g,...sensor}:g;return sensor?{...own,fanPct:own.fanPct??sensor.fanPct,clockMhz:own.clockMhz??sensor.clockMhz}:own;}), + cpuTempC:s.cpuTempC,ssdTempC:s.ssdTempC,energyWh:s.energyWh, gpuLoad:pick(h.gpuLoad,s.gpuLoad),vramUsedGb:pick(h.vramUsedGb,s.vramUsedGb),vramTotalGb:pick(h.vramTotalGb,s.vramTotalGb),gpuTempC:pick(h.gpuTempC,s.gpuTempC), powerW:pick(h.powerW,s.powerW),powerLimitW:pick(h.powerLimitW,s.powerLimitW),pcieRxMbs:pick(h.pcieRxMbs,s.pcieRxMbs)}}; } diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index e6e64bbf..adab6e92 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -3,7 +3,7 @@ import { api } from './client'; import type { Hardware, RuntimeModels } from './types'; export interface GpuChoiceOption {key:string;cards:number[];label:string;verdict:'fits'|'tight'|'spills'|'unknown';words:string;notes:string[];recommended:boolean} export interface GpuChoice {options:GpuChoiceOption[];recommended:string|null;ignored:{name?:string;why_ignored:string}[];cards:number} -export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** DeepSeek-V4.1-Flash and the like: several big files and an engine of their own. */multi_file?:boolean} +export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;installed:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** DeepSeek-V4.1-Flash and the like: several big files and an engine of their own. */multi_file?:boolean;/** DeepSeek: the free disk the set needs (its download plus the pack and room to work), from the set itself. */disk_gb?:number} export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[]} export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean;forModel?:string} export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record|null;progress?:Record|null} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 3449089a..76f06e3d 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -5,6 +5,7 @@ import { updateAgent } from './agents'; import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop'; import { LoopScheduler } from './loop-runner'; import { applyStatusFrame, clearStatus } from './live-status'; +import { approvalNeeded, workFinished } from './attention'; import { applyGoalFrame } from './goal'; import { tidyAnswer } from './answer-text'; import { appendText, mergeDeliverable, readDeliverable, readGroup, readSkills, upsertGroup } from './deliverables'; @@ -82,6 +83,13 @@ export interface AppState { transparency: 'translucent' | 'opaque'; /** Chrome scale, independent of the conversation's reading size. */ uiScale: number; + /** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ + electricityPrice: number; + electricityCurrency: string; + /** Opt-in: a short sound when a task finishes (#3586). */ + doneSound: boolean; + /** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ + approvalNotify: boolean; /** Governs anonymous usage reporting. Nothing is sent in this build; the * choice is recorded so a version that does offer it starts from it. */ shareTelemetry: boolean; @@ -143,6 +151,10 @@ export interface Prefs { motion: 'system' | 'full' | 'reduced'; transparency: 'translucent' | 'opaque'; uiScale: number; + electricityPrice: number; + electricityCurrency: string; + doneSound: boolean; + approvalNotify: boolean; /** Governs anonymous usage reporting. Nothing is sent in this build; the * choice is recorded so a version that does offer it starts from it. */ shareTelemetry: boolean; @@ -160,6 +172,10 @@ const PREFS_DEFAULTS: Prefs = { motion: 'system', transparency: 'translucent', uiScale: 1, + electricityPrice: 0, + electricityCurrency: '', + doneSound: false, + approvalNotify: false, shareTelemetry: false, }; @@ -203,6 +219,11 @@ function loadPrefs(): Prefs { language: validLanguage(parsed.language) ? parsed.language : 'en', fontFamily: typeof parsed.fontFamily === 'string' ? parsed.fontFamily.slice(0,128).replace(/[\x00-\x1f]/g,'') : '', contentFontSize: Math.min(CONTENT_FS_MAX, Math.max(CONTENT_FS_MIN, Number(parsed.contentFontSize) || 14)), + uiScale: [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2].includes(Number(parsed.uiScale)) ? Number(parsed.uiScale) : 1, + electricityPrice: Number.isFinite(Number(parsed.electricityPrice)) && Number(parsed.electricityPrice) > 0 && Number(parsed.electricityPrice) < 1000 ? Number(parsed.electricityPrice) : 0, + electricityCurrency: typeof parsed.electricityCurrency === 'string' && /^[A-Za-z]{3}$/.test(parsed.electricityCurrency) ? parsed.electricityCurrency.toUpperCase() : '', + doneSound: parsed.doneSound === true, + approvalNotify: parsed.approvalNotify === true, }; } catch { /* fall through to the next key */ @@ -215,6 +236,9 @@ const prefs = loadPrefs(); // Use the saved language for the very first render, before host bootstrap. setTranslationLanguage(prefs.language); +/** The last approval question a notification was shown for, so one question is announced once. */ +let lastApprovalNotice = ''; + let state: AppState = { language: prefs.language, fontFamily: prefs.fontFamily, @@ -232,6 +256,10 @@ let state: AppState = { motion: prefs.motion, transparency: prefs.transparency, uiScale: prefs.uiScale, + electricityPrice: prefs.electricityPrice, + electricityCurrency: prefs.electricityCurrency, + doneSound: prefs.doneSound, + approvalNotify: prefs.approvalNotify, paletteOpen: false, shortcutsOpen: false, settingsSection: 'Appearance', @@ -422,9 +450,11 @@ function applyPrefs() { root.dataset.contrast = state.contrast; root.dataset.density = state.density; root.style.setProperty('--st-content-fs', `${state.contentFontSize}px`); - // The chrome scale. The reading size is deliberately separate: someone who - // needs larger prose does not necessarily want larger buttons. - root.style.setProperty('--st-ui-scale', String(state.uiScale)); + // The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were + // written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs + // larger prose does not necessarily want larger buttons. + root.style.setProperty('--st-ui-scale', '1'); + root.style.setProperty('zoom', state.uiScale === 1 ? '' : String(state.uiScale)); // "system" means the OS decides, so the attribute is absent rather than set // to a third value the stylesheet would have to special-case. @@ -452,6 +482,10 @@ function savePrefs() { motion: state.motion, transparency: state.transparency, uiScale: state.uiScale, + electricityPrice: state.electricityPrice, + electricityCurrency: state.electricityCurrency, + doneSound: state.doneSound, + approvalNotify: state.approvalNotify, shareTelemetry: state.shareTelemetry, }; try { @@ -471,7 +505,17 @@ export function toggleRail() { set({ rail: !state.rail }); savePrefs(); } -export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();} +export function setLanguage(language:Language){if(!validLanguage(language))return;setTranslationLanguage(language);set({language});savePrefs();rememberShellLanguage(language);} +let shellAnnounced = false; +/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ +function rememberShellLanguage(language:Language){api.post('/api/shell/prefs',{language}).catch(()=>undefined);} +/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ +async function announcePortNotice(){ + try{ + const shell=await api.get<{portNotice:{wanted:number;used:number}|null}>('/api/shell'); + if(shell.portNotice)pushToast('warn',tr('Strata could not use its port'),tr('Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.',[shell.portNotice.wanted,shell.portNotice.used])); + }catch{/* a browser or an older host has no shell */} +} export function setFontFamily(fontFamily:string){set({fontFamily:fontFamily.trim().slice(0,128).replace(/[\x00-\x1f]/g,'')});savePrefs();} export function setFocus(focus: boolean) { @@ -544,7 +588,24 @@ export function setTransparency(transparency: 'translucent' | 'opaque') { savePrefs(); } -export const UI_SCALES = [0.9, 1, 1.1, 1.25] as const; +/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ +export function setElectricity(price: number, currency: string) { + const ok = Number.isFinite(price) && price > 0 && price < 1000; + set({ electricityPrice: ok ? Math.round(price * 10000) / 10000 : 0, electricityCurrency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '' }); + savePrefs(); +} + +export function setDoneSound(doneSound: boolean) { + set({ doneSound }); + savePrefs(); +} + +export function setApprovalNotify(approvalNotify: boolean) { + set({ approvalNotify }); + savePrefs(); +} + +export const UI_SCALES = [0.9, 1, 1.1, 1.25, 1.5, 1.75, 2] as const; export function setUiScale(uiScale: number) { set({ uiScale }); @@ -680,8 +741,8 @@ function applyEvent(e: StreamEvent) { // A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. const t = data as unknown as { title?: string; status?: string; attention?: string | null; error?: string | null }; if (t.status === 'error') pushToast('error', 'Task failed', String(t.title ?? '')); - else if (t.attention) pushToast('warn', 'Task needs your yes', String(t.title ?? '')); - else if (t.status === 'done') pushToast('success', 'Task finished', String(t.title ?? '')); + else if (t.attention) { pushToast('warn', 'Task needs your yes', String(t.title ?? '')); void approvalNeeded(state.approvalNotify, String(t.title ?? '')); } + else if (t.status === 'done') { pushToast('success', 'Task finished', String(t.title ?? '')); workFinished(state.doneSound, Infinity); } break; } case 'agent': @@ -726,6 +787,7 @@ export async function bootstrap() { connection: 'live', }); applyProviders(providers); + if (!shellAnnounced) { shellAnnounced = true; void announcePortNotice(); rememberShellLanguage(state.language); } closeEvents?.(); let reconnect = false; closeEvents = onEvent(applyEvent, (status) => { @@ -1746,6 +1808,12 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g patchAssistant((m) => ({ ...m, demo: frame.demo === true, remoteModel: frame.remoteModel === true, requestId: typeof frame.requestId === 'string' ? frame.requestId : m.requestId, model: String(frame.model), contextMax: Number(frame.contextMax), skillsUsed: Array.isArray(frame.skills) ? frame.skills.map(String) : [] })); } else if (type === 'status') { applyStatusFrame(sessionId, frame as Record); + // Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. + if (frame.code === 'waiting-approval' && lastApprovalNotice !== `${sessionId}:${String(frame.seq)}`) { + lastApprovalNotice = `${sessionId}:${String(frame.seq)}`; + const tool = (frame.args as { tool?: unknown } | undefined)?.tool; + void approvalNeeded(state.approvalNotify, typeof tool === 'string' ? tool : ''); + } } else if (type === 'goal') { applyGoalFrame(sessionId, frame.goal); } else if (type === 'plan') { @@ -1820,6 +1888,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g patchAssistant((m) => ({ ...m, error: said, streaming: false, ...(typeof frame.code === 'string' ? { errorCode: frame.code } : {}), ...(typeof frame.details === 'string' && frame.details ? { errorDetail: frame.details } : {}) })); } else if (type === 'done') { clearStatus(sessionId); + workFinished(state.doneSound, Number(frame.durationMs ?? performance.now() - started)); patchSession(sessionId, (sess) => ({ ...sess, tokensIn: sess.tokensIn + Number(frame.tokensIn ?? 0), diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 28e044bd..1e477540 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -23,7 +23,7 @@ export interface HardwareCheck { export interface ProcessorInfo { id:string; socket:string; model:string; cores:number; threads:number; arch:string; ghz:number; logicalIds?:number[] } export interface CpuReading { id:string; utilizationPct:number|null } -export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null } +export interface GpuReading { id:string; temperatureC:number|null; utilizationPct:number|null; memoryUsedGb:number|null; source:string; sampledAt:string; powerW?:number|null; powerLimitW?:number|null; pcieGen?:number|null; pcieGenMax?:number|null; pcieWidth?:number|null; pcieRxMbs?:number|null; fanPct?:number|null; clockMhz?:number|null } export interface GpuInfo { id?: string; @@ -285,6 +285,10 @@ export interface MonitorState { powerW?: number | null; powerLimitW?: number | null; pcieRxMbs?: number | null; + /** CPU and SSD temperatures (only where this PC can give one) and the GPU energy used since the host started, in Wh (#3628). */ + cpuTempC?: number | null; + ssdTempC?: number | null; + energyWh?: number | null; diskReadGbs?: number | null; diskWriteMbs?: number | null; gpuLoad: number | null; diff --git a/apps/host/src/locales/fix-de.json b/apps/host/src/locales/fix-de.json index f378e020..ae018917 100644 --- a/apps/host/src/locales/fix-de.json +++ b/apps/host/src/locales/fix-de.json @@ -77,5 +77,9 @@ "fx76": "Ein (empfohlen)", "fx77": "Das ist ein sehr großes Modell. Der Download umfasst {0} GB und braucht etwa so viel freien Speicherplatz. Es läuft auf NVIDIA-RTX-Karten der Serien 30, 40 und 50, auf einer Radeon AI PRO R9700 (Linux) oder auf einem Ryzen-AI-Max-/Strix-Halo-PC (Windows); wie schnell es ist, hängt von Speicher und Grafikkarte ab (die Zeile darunter sagt, was auf diesem Computer zu erwarten ist). Was nicht in den Speicher passt, wird von deiner SSD gelesen, deshalb zählt eine NVMe-SSD.", "fx78": "Noch nicht getestet. Ein so langer Kontext nimmt dem Modell Grafikspeicher weg, und lange Prompts werden langsam gelesen.", - "fx79": "Aus (empfohlen)" + "fx79": "Aus (empfohlen)", + "fx80": "Braucht etwa {0} GB freien Speicherplatz. Was nicht in den Speicher passt, wird von Ihrer SSD gelesen.", + "fx81": "{0} RAM + VRAM, dazu etwa {1} GB Speicherplatz", + "fx82": "Schnellere Antworten auf NVIDIA-Karten mit 12 GB", + "fx83": "Bevorzugt die Teile des Modells, die schon auf der Grafikkarte liegen. Das macht Antworten auf Karten mit 12 GB deutlich schneller. Schalten Sie die Option aus, wenn die Antworten schlechter aussehen als vorher." } diff --git a/apps/host/src/locales/fix-en.json b/apps/host/src/locales/fix-en.json index efe52962..67ca12df 100644 --- a/apps/host/src/locales/fix-en.json +++ b/apps/host/src/locales/fix-en.json @@ -77,5 +77,9 @@ "fx76": "On (recommended)", "fx77": "This is a very large model. The download is {0} GB and it needs about as much free disk space. It runs on NVIDIA RTX 30, 40 and 50 cards, on a Radeon AI PRO R9700 (Linux) or on a Ryzen AI Max / Strix Halo PC (Windows); how fast it is depends on the memory and card (the line below says what to expect on this computer). What does not fit in memory is read from your SSD, so an NVMe drive matters.", "fx78": "Not tested yet. A context this long takes graphics memory from the model and reads long prompts slowly.", - "fx79": "Off (recommended)" + "fx79": "Off (recommended)", + "fx80": "Needs about {0} GB of free disk space. What does not fit in memory is read from your SSD.", + "fx81": "{0} RAM + VRAM, plus about {1} GB of disk", + "fx82": "Faster answers on 12 GB NVIDIA cards", + "fx83": "Prefers the parts of the model already on the graphics card, which makes answers much faster on 12 GB cards. Turn off if answers look worse than before." } diff --git a/apps/host/src/locales/fix-es.json b/apps/host/src/locales/fix-es.json index 211c1988..94bfd9d6 100644 --- a/apps/host/src/locales/fix-es.json +++ b/apps/host/src/locales/fix-es.json @@ -77,5 +77,9 @@ "fx76": "Activado (recomendado)", "fx77": "Es un modelo muy grande. La descarga es de {0} GB y necesita casi el mismo espacio libre en disco. Funciona con tarjetas NVIDIA RTX de las series 30, 40 y 50, con una Radeon AI PRO R9700 (Linux) o en un PC con Ryzen AI Max / Strix Halo (Windows); su velocidad depende de la memoria y de la tarjeta (la línea de abajo indica qué esperar en este equipo). Lo que no cabe en memoria se lee de tu SSD, así que importa que sea NVMe.", "fx78": "Aún sin probar. Un contexto tan largo le quita memoria gráfica al modelo y lee los prompts largos con lentitud.", - "fx79": "Desactivado (recomendado)" + "fx79": "Desactivado (recomendado)", + "fx80": "Necesita unos {0} GB de espacio libre en disco. Lo que no cabe en memoria se lee de tu SSD.", + "fx81": "{0} de RAM + VRAM, más unos {1} GB de disco", + "fx82": "Respuestas más rápidas en tarjetas NVIDIA de 12 GB", + "fx83": "Prefiere las partes del modelo que ya están en la tarjeta gráfica, lo que hace las respuestas mucho más rápidas en tarjetas de 12 GB. Desactívalo si las respuestas parecen peores que antes." } diff --git a/apps/host/src/locales/fix-fr.json b/apps/host/src/locales/fix-fr.json new file mode 100644 index 00000000..052851ed --- /dev/null +++ b/apps/host/src/locales/fix-fr.json @@ -0,0 +1,85 @@ +{ + "fx01": "ne s’exécutera plus et sera retirée.", + "fx02": "Téléchargé, mais pas chargé. Ouvrez Modèles pour le charger.", + "fx03": "{0} lignes ajoutées, {1} supprimées", + "fx04": "{0} fichiers modifiés", + "fx05": "Déposez des fichiers pour les ajouter", + "fx06": "Images et fichiers texte", + "fx07": "Garder l’objectif", + "fx08": "Supprimer l’objectif", + "fx09": "L’assistant cesse de travailler à l’atteindre. Votre conversation et vos fichiers restent comme ils sont.", + "fx10": "Ce modèle peut lire les images, mais le moteur installé ici n’inclut pas encore le lecteur d’images : Lire les images est donc désactivé. Mettez à jour le moteur dans Paramètres → À propos pour l’activer.", + "fx11": "Affichage des valeurs de votre optimisation « {0} ».", + "fx12": "Votre optimisation « {0} » règle", + "fx13": "était {0}", + "fx14": "· {0} de RAM", + "fx15": "Le message n’a pas été annulé", + "fx16": "Réglages supplémentaires pour le programme", + "fx17": "Rédiger avec l’IA", + "fx18": "Temps de réflexion", + "fx19": "Temps de rédaction", + "fx20": "tokens/s", + "fx21": "% du contexte", + "fx22": "Cette page demande des fichiers à internet, que l’aperçu ne charge pas : elle peut donc paraître incomplète. Voir le code montre exactement ce qui a été écrit.", + "fx23": "Garder A", + "fx24": "Garder B", + "fx25": "A pris", + "fx26": "Variante", + "fx27": "Modifié", + "fx28": "Rien", + "fx29": "Les deux versions sont prêtes. Comparez A et B, puis gardez-en une.", + "fx30": "L’assistant répond encore", + "fx31": "Envoyez votre message quand il a terminé.", + "fx32": "Le message n’a pas été mis en file d’attente", + "fx33": "Aller au dernier message", + "fx34": "Retirer la tâche", + "fx35": "Ouvrir une nouvelle conversation ; garder celle-ci", + "fx36": "Faire d’abord rédiger un plan à l’assistant ; rien ne s’exécute tant que vous ne l’avez pas approuvé", + "fx37": "Chercher sur le web, lire les pages et répondre avec des sources", + "fx38": "Copié", + "fx39": "Réponse", + "fx40": "Message", + "fx41": "PDF ajouté", + "fx42": "Sélectionnez le texte et copiez-le avec Ctrl+C.", + "fx43": "{0} est dans cette conversation. Posez une question à son sujet dans votre prochain message.", + "fx44": "Le moteur est prêt.", + "fx45": "Étape suivante : choisir un modèle.", + "fx46": "Téléchargement du moteur", + "fx47": "Vous pouvez fermer Strata ; le téléchargement reprendra là où il s’est arrêté.", + "fx48": "Bienvenue dans Strata", + "fx49": "Examen de votre carte graphique…", + "fx50": "Strata a trouvé votre carte graphique :", + "fx51": "{0} cartes trouvées. Strata utilise la première pour le moteur ; vous pourrez changer cela plus tard dans les Paramètres.", + "fx52": "Strata n’a pas reconnu de carte graphique prise en charge.", + "fx53": "Pour y exécuter des modèles, Strata a besoin d’un téléchargement :", + "fx54": "Le moteur pour cette carte", + "fx55": "Le moteur a besoin d’environ {0} Go d’espace libre sur ce disque et il n’y en a que {1} Go. Libérez de l’espace, puis continuez.", + "fx56": "Il vient du serveur de mise à jour de Strata et il est vérifié avant utilisation. Vos modèles et vos conversations ne sont jamais touchés.", + "fx57": "Strata n’a pas pu joindre github.com. Vérifiez votre connexion et réessayez, ou téléchargez le fichier du moteur sur un autre PC et choisissez-le ici.", + "fx58": "Le moteur installé ici est prévu pour une autre marque de carte graphique.", + "fx59": "Strata ne peut pas choisir de moteur pour ce PC dans sa liste de mises à jour.", + "fx60": "Continuer sans moteur", + "fx61": "Le téléchargement s’est arrêté. Continuer le reprend là où il s’est arrêté.", + "fx62": "C’est un très gros modèle. Le téléchargement fait {0} Go et il faut à peu près autant d’espace disque libre. Il tourne sur une carte graphique de 12 Go avec 46 à 64 Go de RAM, lentement : environ 5 à 7 mots par seconde. Ce qui ne tient pas en mémoire est lu depuis votre SSD, un disque NVMe compte donc beaucoup.", + "fx63": "Vous pouvez arrêter le téléchargement et le continuer plus tard ; il reprend là où il s’est arrêté. Strata vous avertit ici mais ne vous bloque jamais.", + "fx64": "Plus rapide", + "fx65": "Qualité maximale", + "fx66": "Par défaut (Plus rapide sur ce PC)", + "fx67": "Par défaut (Qualité maximale sur ce PC)", + "fx68": "Plus rapide (par défaut sur ce PC)", + "fx69": "Qualité maximale (par défaut sur ce PC)", + "fx70": "Longs prompts plus rapides", + "fx71": "Réponses plus rapides sur Radeon RX 9000 / AI PRO R9700", + "fx72": "Accélérations DeepSeek", + "fx73": "Lit les très longs prompts plus vite en approximant une partie du travail. Désactivé par défaut : les réponses sur de longs documents peuvent manquer ou mélanger des détails.", + "fx74": "Répartit le travail entre la carte graphique et le processeur d’une façon qui accélère les réponses sur ces cartes. Désactivez pour revenir au réglage précédent, plus lent.", + "fx75": "Lit les longs prompts plus vite et charge plus vite les parties du modèle dont il a besoin. Désactivez si DeepSeek cesse de fonctionner ou si ses réponses semblent fausses ; il fonctionne alors comme dans la version 0.2.6.", + "fx76": "Activé (recommandé)", + "fx77": "C’est un très gros modèle. Le téléchargement fait {0} Go et il faut à peu près autant d’espace disque libre. Il tourne sur les cartes NVIDIA RTX 30, 40 et 50, sur une Radeon AI PRO R9700 (Linux) ou sur un PC Ryzen AI Max / Strix Halo (Windows) ; sa vitesse dépend de la mémoire et de la carte (la ligne ci-dessous indique à quoi s’attendre sur cet ordinateur). Ce qui ne tient pas en mémoire est lu depuis votre SSD, un disque NVMe compte donc beaucoup.", + "fx78": "Pas encore testé. Un contexte aussi long prend de la mémoire graphique au modèle et lit lentement les longs prompts.", + "fx79": "Désactivé (recommandé)", + "fx80": "Il faut environ {0} Go d’espace disque libre. Ce qui ne tient pas en mémoire est lu depuis votre SSD.", + "fx81": "{0} de RAM + VRAM, plus environ {1} Go de disque", + "fx82": "Réponses plus rapides sur les cartes NVIDIA de 12 Go", + "fx83": "Privilégie les parties du modèle déjà présentes sur la carte graphique, ce qui accélère nettement les réponses sur les cartes de 12 Go. Désactivez-le si les réponses semblent moins bonnes qu’avant." +} diff --git a/apps/host/src/locales/fix-ja.json b/apps/host/src/locales/fix-ja.json index 2b888a77..dfa32359 100644 --- a/apps/host/src/locales/fix-ja.json +++ b/apps/host/src/locales/fix-ja.json @@ -77,5 +77,9 @@ "fx76": "オン(推奨)", "fx77": "とても大きなモデルです。ダウンロードは {0} GB で、ほぼ同じ大きさの空き容量が必要です。NVIDIA RTX 30・40・50 シリーズ、Radeon AI PRO R9700(Linux)、または Ryzen AI Max / Strix Halo の PC(Windows)で動きます。速さはメモリとカードによって変わります(この PC での目安は下の行に表示されます)。メモリに入らない分は SSD から読むため、NVMe ドライブが重要です。", "fx78": "まだテストされていません。これほど長いコンテキストは、モデルが使うグラフィックスメモリを消費し、長いプロンプトの読み込みも遅くなります。", - "fx79": "オフ(推奨)" + "fx79": "オフ(推奨)", + "fx80": "約 {0} GB の空きディスク容量が必要です。メモリに入らない分は SSD から読み込みます。", + "fx81": "RAM + VRAM {0}、ほかにディスク約 {1} GB", + "fx82": "12 GB の NVIDIA カードでの高速な応答", + "fx83": "グラフィックスカード上にすでにあるモデルの部分を優先して使うため、12 GB のカードで応答がとても速くなります。以前より回答が悪くなったと感じたらオフにしてください。" } diff --git a/apps/host/src/locales/fix-ko.json b/apps/host/src/locales/fix-ko.json index befec99d..d66de789 100644 --- a/apps/host/src/locales/fix-ko.json +++ b/apps/host/src/locales/fix-ko.json @@ -77,5 +77,9 @@ "fx76": "켬(권장)", "fx77": "매우 큰 모델입니다. 다운로드는 {0}GB이고, 거의 같은 크기의 여유 디스크 공간이 필요합니다. NVIDIA RTX 30·40·50 시리즈 카드, Radeon AI PRO R9700(Linux), 또는 Ryzen AI Max / Strix Halo PC(Windows)에서 실행됩니다. 속도는 메모리와 카드에 따라 달라집니다(아래 줄에 이 컴퓨터에서 기대할 수 있는 속도가 표시됩니다). 메모리에 들어가지 않는 부분은 SSD에서 읽으므로 NVMe 드라이브가 중요합니다.", "fx78": "아직 테스트하지 않았습니다. 이렇게 긴 컨텍스트는 모델이 쓸 그래픽 메모리를 차지하고, 긴 프롬프트를 느리게 읽습니다.", - "fx79": "끔(권장)" + "fx79": "끔(권장)", + "fx80": "약 {0}GB의 여유 디스크 공간이 필요합니다. 메모리에 들어가지 않는 부분은 SSD에서 읽습니다.", + "fx81": "RAM + VRAM {0}, 디스크 약 {1}GB 추가", + "fx82": "12GB NVIDIA 카드에서 더 빠른 응답", + "fx83": "이미 그래픽 카드에 올라와 있는 모델 부분을 우선 사용해 12GB 카드에서 응답이 훨씬 빨라집니다. 답변이 이전보다 나빠 보이면 끄세요." } diff --git a/apps/host/src/locales/fix-pt.json b/apps/host/src/locales/fix-pt.json index 3accb7ef..104ee4be 100644 --- a/apps/host/src/locales/fix-pt.json +++ b/apps/host/src/locales/fix-pt.json @@ -77,5 +77,9 @@ "fx76": "Ativado (recomendado)", "fx77": "Este é um modelo muito grande. O download tem {0} GB e precisa de quase o mesmo espaço livre em disco. Ele roda em placas NVIDIA RTX das séries 30, 40 e 50, em uma Radeon AI PRO R9700 (Linux) ou em um PC com Ryzen AI Max / Strix Halo (Windows); a velocidade depende da memória e da placa (a linha abaixo diz o que esperar neste computador). O que não cabe na memória é lido do seu SSD, então um NVMe faz diferença.", "fx78": "Ainda não testado. Um contexto tão longo tira memória gráfica do modelo e lê prompts longos devagar.", - "fx79": "Desativado (recomendado)" + "fx79": "Desativado (recomendado)", + "fx80": "Precisa de cerca de {0} GB de espaço livre em disco. O que não cabe na memória é lido do seu SSD.", + "fx81": "{0} de RAM + VRAM, mais cerca de {1} GB de disco", + "fx82": "Respostas mais rápidas em placas NVIDIA de 12 GB", + "fx83": "Prefere as partes do modelo que já estão na placa de vídeo, o que deixa as respostas bem mais rápidas em placas de 12 GB. Desative se as respostas parecerem piores do que antes." } diff --git a/apps/host/src/locales/fix-ru.json b/apps/host/src/locales/fix-ru.json index d2147327..583de12f 100644 --- a/apps/host/src/locales/fix-ru.json +++ b/apps/host/src/locales/fix-ru.json @@ -77,5 +77,9 @@ "fx76": "Вкл. (рекомендуется)", "fx77": "Это очень большая модель. Загрузка — {0} ГБ, и нужно почти столько же свободного места на диске. Она работает на видеокартах NVIDIA RTX серий 30, 40 и 50, на Radeon AI PRO R9700 (Linux) или на ПК с Ryzen AI Max / Strix Halo (Windows); скорость зависит от памяти и видеокарты (строка ниже подскажет, чего ждать на этом компьютере). То, что не помещается в память, читается с вашего SSD, поэтому важен накопитель NVMe.", "fx78": "Ещё не проверено. Такой длинный контекст отнимает у модели видеопамять, а длинные запросы читаются медленно.", - "fx79": "Выкл. (рекомендуется)" + "fx79": "Выкл. (рекомендуется)", + "fx80": "Нужно около {0} ГБ свободного места на диске. То, что не помещается в память, читается с вашего SSD.", + "fx81": "{0} RAM + VRAM, плюс около {1} ГБ на диске", + "fx82": "Более быстрые ответы на видеокартах NVIDIA с 12 ГБ", + "fx83": "Отдаёт предпочтение частям модели, которые уже находятся на видеокарте, поэтому ответы на картах с 12 ГБ становятся намного быстрее. Отключите, если ответы стали выглядеть хуже, чем раньше." } diff --git a/apps/host/src/locales/fix-zh.json b/apps/host/src/locales/fix-zh.json index 48b64cd1..4fa0e9db 100644 --- a/apps/host/src/locales/fix-zh.json +++ b/apps/host/src/locales/fix-zh.json @@ -77,5 +77,9 @@ "fx76": "开启(推荐)", "fx77": "这是一个非常大的模型。下载大小为 {0} GB,需要差不多同样大小的可用磁盘空间。它可在 NVIDIA RTX 30、40 和 50 系列显卡、Radeon AI PRO R9700(Linux)或 Ryzen AI Max / Strix Halo 电脑(Windows)上运行;速度取决于内存和显卡(下面一行会说明在这台电脑上的预期)。内存放不下的部分会从你的 SSD 读取,所以 NVMe 硬盘很重要。", "fx78": "尚未测试。这么长的上下文会占用本该给模型使用的显存,读取长提示词也会很慢。", - "fx79": "关闭(推荐)" + "fx79": "关闭(推荐)", + "fx80": "大约需要 {0} GB 可用磁盘空间。内存放不下的部分会从你的 SSD 读取。", + "fx81": "{0} 内存 + 显存,另需约 {1} GB 磁盘空间", + "fx82": "12 GB NVIDIA 显卡上更快的回答", + "fx83": "优先使用已经在显卡上的模型部分,使 12 GB 显卡上的回答快很多。如果回答看起来比以前差,请关闭。" } diff --git a/apps/host/src/locales/fr.json b/apps/host/src/locales/fr.json new file mode 100644 index 00000000..1f9094c4 --- /dev/null +++ b/apps/host/src/locales/fr.json @@ -0,0 +1,3530 @@ +{ + "s0001": "% PCIe", + "s7331": "Les résultats viennent de DuckDuckGo, ou de Bing quand DuckDuckGo est saturé. Vous n’avez besoin ni de compte ni de clé.", + "s7321": "La recherche web est limitée en ce moment, j’ai donc arrêté de chercher et poursuivi avec ce que j’ai. Réessayez dans une minute, ou ajoutez une clé de recherche dans Paramètres → Outils → Recherche web.", + "s7322": "J’ai beaucoup cherché et je me suis arrêté pour que cette conversation ne se remplisse pas. Voici ce que j’ai jusqu’ici. Dites-moi ce qu’il faut explorer ensuite.", + "s7323": "J’ai réécrit le plan plusieurs fois, je m’arrête donc ici avec la dernière version. Dites-moi quoi changer, ou approuvez-la.", + "s7324": "Je n’ai plus de place dans cette conversation, je me suis donc arrêté. Strata résume les anciens messages pour libérer de la place. Dites « continue » pour poursuivre, ou ouvrez une nouvelle conversation.", + "s7325": "Je me suis arrêté sans écrire de réponse. Renvoyez votre message, ou dites « continue ».", + "s7301": "Tapez /loop, la fréquence, puis ce qu’il faut faire. Par exemple : /loop 10m vérifiez si la compilation réussit. Ajoutez « stop after 3 answers » pour l’arrêter tout seul. Tapez /loop stop pour l’arrêter.", + "s7302": "Dites ce qu’il faut faire à chaque fois, pas seulement quand s’arrêter.", + "s7303": "La boucle est terminée : elle s’est exécutée {0} fois, comme demandé. Tapez /loop pour en lancer une autre.", + "s7304": "La boucle s’est arrêtée parce que la dernière réponse indique que le travail est terminé. Tapez /loop pour en lancer une autre.", + "s7305": "La boucle s’est arrêtée parce que le temps que vous aviez fixé est écoulé. Tapez /loop pour en lancer une autre.", + "s7306": "La boucle s’est arrêtée parce que {0} exécutions de suite ont échoué. Vérifiez le modèle, puis tapez /loop pour la relancer.", + "s7307": "Elle s’arrête toute seule après la première réponse.", + "s7308": "Elle s’arrête toute seule après {0} réponses.", + "s7309": "Elle s’arrête toute seule après {0} minutes.", + "s7310": "Elle s’arrête toute seule quand une réponse indique que le travail est terminé.", + "s7311": "Les applications Anthropic ajoutent /v1/messages elles-mêmes : cette adresse ne se termine donc pas par /v1. Dans Claude Code, indiquez-la dans ANTHROPIC_BASE_URL.", + "s0002": "(facultatif)", + "s0003": ", le cache de contexte ne tient pas", + "s0004": "-y @modelcontextprotocol/server-filesystem /your/folder", + "s0005": "0 utilise la valeur par défaut du moteur.", + "s0006": "20 % de marge pour le reste", + "s0007": "Classe 32 Go de RAM", + "s0008": "Classe 48 Go de RAM", + "s0009": "Classe 60–64 Go de RAM", + "s0010": "Classe 8 Go de RAM", + "s0011": "8 testeurs sur 10 terminent l’installation.", + "s0012": "Un serveur Strata tourne déjà en dehors de cette interface. Arrêtez-le avant de charger ici, ou connectez son API dans Paramètres → Modèles.", + "s0013": "Un prompt fixe, sans réflexion, avec jusqu’à 200 tokens de sortie. Dure en général 10 à 60 secondes. Les résultats sont mesurés par votre moteur.", + "s0014": "Une correction ciblée, à partir du même point de départ.", + "s0015": "Un nouveau point de situation, chaque matin", + "s0016": "Un objectif décrit le résultat voulu. Strata planifie le travail, suit son avancement et continue jusqu’à l’atteindre.", + "s0017": "Un bon point de départ.", + "s0018": "Une clé permet à vos autres applications de se connecter à Strata.", + "s0019": "Un petit coup de pouce.", + "s0020": "Un peu de réglage. Un meilleur résultat.", + "s0021": "Bien plus de possibilités.", + "s0022": "Une opération sur un modèle est en cours.", + "s0023": "Un nouveau candidat part du point de départ de B.", + "s0024": "Une visite rapide de Strata", + "s0025": "Un petit exercice quotidien pour affûter votre écriture.", + "s0026": "Une adresse stable sur un domaine que vous gérez avec Cloudflare.", + "s0027": "Une configuration de moteur validée est requise.", + "s0028": "A → B · détail manquant ajouté, aucune vérification en recul.", + "s0029": "API", + "s0030": "URL de base de l’API", + "s0031": "Clé API", + "s0032": "Clé API prête", + "s0033": "Clé API requise", + "s0034": "Clé API enregistrée", + "s0035": "API à l’écoute", + "s0036": "Alias des modèles API", + "s0037": "Les modèles API utilisent les réglages de réponse de leur fournisseur.", + "s0038": "Protocole de l’API", + "s0039": "Fournisseur d’API", + "s0040": "API arrêtée", + "s0041": "À propos", + "s0042": "Au-dessus de 1, le texte répété est découragé.", + "s0043": "Accès", + "s0044": "Accès configuré dans le serveur MCP", + "s0045": "Actions pour {0}", + "s0046": "Actif", + "s0047": "Actives / en file d’attente", + "s0048": "Jours actifs", + "s0049": "Ajoutez un objet de réglages pour débutant.", + "s0050": "Ajoutez un dossier contenant SKILL.md.", + "s0051": "Ajoutez un prompt après /time-skip", + "s0052": "Ajoutez une route d’application publiée pour ce nom d’hôte avec cette URL de service :", + "s0053": "Ajouter une tâche", + "s0054": "Ajouter un dossier de travail", + "s0055": "Ajoutez un objet de réglages experts.", + "s0056": "Ajouter des fichiers ou des photos", + "s0057": "Ajouter un dossier", + "s0058": "Ajoutez des programmes locaux ou des serveurs MCP HTTP. Les outils connectés peuvent lire ou modifier les ressources auxquelles vous leur donnez accès. Activez les outils dans la conversation quand vous voulez que le modèle les utilise.", + "s0059": "Ajouter un modèle", + "s0060": "Ajouter un fournisseur de modèles", + "s0061": "Ajouter des modèles à votre sélecteur de conversation", + "s0062": "Ajouter ou ouvrir", + "s0063": "Ajouter une compétence", + "s0064": "Ajouter aux paramètres", + "s0065": "Ajouter un serveur d’outils", + "s0066": "Ajoutez deux fois, remettez à 0, puis vérifiez à 320 px.", + "s0067": "Vérification de réussite reproductible ajoutée", + "s0068": "Vérification de réussite ajoutée", + "s0069": "Compétences ajoutées", + "s0070": "Ajout…", + "s0071": "Réglages supplémentaires", + "s0072": "Adresse", + "s0073": "Ajuster", + "s0074": "Avancé", + "s0075": "JSON avancé", + "s0076": "Agentique", + "s0077": "Les agents travaillent en parallèle", + "s0078": "Tout", + "s0079": "Tous les GPU ({0})", + "s0080": "Toutes les conversations", + "s0081": "Tous les groupes", + "s0082": "Toutes les couches", + "s0083": "Tous les modèles", + "s0084": "Tous les modèles ({0})", + "s0085": "Tous les processeurs ({0})", + "s0086": "Tous les espaces de travail", + "s0087": "Les {0} modèles chargés seront tous déchargés.", + "s0088": "Autoriser des origines de navigateur", + "s0089": "Déjà attribué à {0}. Effacez ou modifiez d’abord cette association.", + "s0090": "Vous avez déjà téléchargé le modèle ?", + "s0091": "Vous savez déjà vous en servir ?", + "s0092": "Un argument du moteur désigne un fichier GGUF introuvable. Restaurez les arguments enregistrés ou réparez les fichiers.", + "s0093": "GIF animé", + "s0094": "Réponse", + "s0095": "Réponse de", + "s0096": "Anthropic", + "s0097": "Anthropic Messages", + "s0098": "Réflexion Anthropic", + "s0099": "Hôte de l’application :", + "s0100": "Apparence", + "s0101": "Appliqué sous la forme --vram-reserve-mib au chargement.", + "s0102": "Appliquer", + "s0103": "Appliquer la police", + "s0104": "Appliquer maintenant…", + "s0105": "Appliquer les réglages maintenant ?", + "s0106": "Approuver", + "s0107": "Approuvé", + "s0108": "Les applications de cet ordinateur pourront envoyer des requêtes sans clé. Les clients existants peuvent garder leur champ de clé actuel.", + "s0109": "Architecture", + "s0110": "Archivée", + "s0111": "Arguments · un par ligne", + "s0112": "Redemander", + "s0113": "Demander avant de modifier", + "s0114": "Écrivez « spawn subagents » dans la conversation et décrivez les tâches. Des agents distincts peuvent chercher, rédiger et relire en parallèle, puis vous rapporter leur travail.", + "s0115": "Ressource introuvable", + "s0116": "GPU attribués", + "s0117": "Joignez une image PNG, JPEG ou WebP. Les autres images peuvent s’ouvrir dans l’aperçu.", + "s0118": "Joignez jusqu’à trois images par message.", + "s0119": "Outil connecté autorisé", + "s0120": "Optimiser pour mon PC", + "s0121": "Optimiser pour cet ordinateur", + "s0122": "Automatique", + "s0123": "GPU automatique", + "s0124": "La configuration automatique du connecteur n’est pas disponible pour ce système d’exploitation et ce processeur.", + "s0125": "La configuration automatique doit être retentée.", + "s0126": "Automatique utilise le placement GPU de l’installation. Choisissez un GPU, ou répartissez ce modèle sur plusieurs GPU.", + "s0127": "Automatique · GPU 1", + "s0128": "Automatique · tous les GPU", + "s0129": "Automatique · recommandé : 2 048", + "s0130": "Disponible", + "s0131": "Modèles API disponibles", + "s0132": "Disponible dans", + "s0133": "Modèles disponibles", + "s0134": "Délai moyen avant le premier token", + "s0135": "B comble les lacunes et garde les bons éléments de A.", + "s0136": "B est enregistré. Une dernière révision ciblée est en cours dans l’autre flux.", + "s0137": "B sélectionné · les trois vérifications d’exemple réussissent.", + "s0138": "Retour", + "s0139": "Retour à la conversation", + "s0140": "Revenir au réglage recommandé", + "s0141": "Équilibré", + "s0142": "URL de base", + "s0143": "Taille du lot", + "s0144": "En dessous du minimum de 16 Go", + "s0145": "Test de performance", + "s0146": "Tester le modèle", + "s0147": "Le corps doit être du JSON", + "s0148": "Style botanique", + "s0149": "Style botanique conservé", + "s0150": "Créer une branche à partir d’ici", + "s0151": "Rassembler les résultats", + "s0152": "Le stockage du navigateur est plein. Libérez de la place avant d’enregistrer les réglages.", + "s0153": "Création de B à partir du brouillon enregistré.", + "s0154": "Compétences intégrées", + "s0155": "Ignorer les autorisations", + "s0156": "CPU", + "s0157": "Le CPU et le GPU partagent un même pool de mémoire.", + "s0158": "Le CPU et le GPU utilisent le même pool de mémoire. La VRAM partagée n’est comptée qu’une fois dans le total.", + "s0159": "Charge du CPU", + "s0160": "CPU uniquement", + "s0161": "CPU uniquement · aucun GPU attribué", + "s0162": "Threads CPU", + "s0163": "Threads CPU.", + "s0164": "Utilisation du CPU", + "s0165": "CPU {0} ·", + "s0166": "CPU {0} · {1}", + "s0167": "Les détails du cache apparaissent quand le moteur signale une réutilisation du prompt.", + "s0168": "Calibrer le moteur…", + "s0169": "Calibrer cet ordinateur ?", + "s0170": "La calibration est disponible sur le matériel NVIDIA pris en charge par la version installée. Les tests courts fonctionnent avec toute instance native en cours d’exécution.", + "s0171": "Peut-on aller plus loin ?", + "s0172": "Annuler", + "s0173": "Annuler le téléchargement", + "s0174": "Échec de l’annulation", + "s0175": "Annuler l’aperçu", + "s0176": "Annuler la requête", + "s0177": "Annulé", + "s0178": "Annulation…", + "s0179": "Tokens candidats. Zéro supprime cette limite.", + "s0180": "Estimation de capacité : {0} Go de GPU, {1} Go de {2}, {3} Go de débordement sur SSD{4}", + "s0181": "Plan de capacité d’après les métadonnées du modèle. Le placement réel, la mémoire libre et les lectures SSD doivent être vérifiés par le moteur.", + "s0182": "Mesures capturées par Strata Monitor", + "s0183": "Préférence du catalogue parmi les modèles qui tiennent. {0}.", + "s0184": "Modifier", + "s0185": "Changer la clé API", + "s0186": "Changer de dossier", + "s0187": "Changer de fichier", + "s0188": "Changer la clé", + "s0189": "Changer le raccourci de {0}", + "s0190": "Changez l’adresse d’écoute de l’hôte et redémarrez pour mettre à jour l’accès réseau.", + "s0191": "Modifications seulement", + "s0192": "Modifications seulement (", + "s0193": "Les modifications sont enregistrées dans Strata. Le fichier d’origine de la compétence reste intact.", + "s0194": "Modifications en surbrillance", + "s0195": "Chat", + "s0196": "Chat Completions", + "s0197": "Mémoire de conversation nécessaire", + "s0198": "Modèle de conversation", + "s0199": "Modèle de conversation modifié", + "s0200": "Nom de la conversation", + "s0201": "Options de la conversation", + "s0202": "Démo du chat · code, outils et médias", + "s0203": "Statistiques de la conversation", + "s0204": "Conversation {0}", + "s0205": "Vérifier", + "s0206": "Vérifier à nouveau", + "s0207": "Vérifiez l’ordinateur, choisissez une version et chargez-la", + "s0208": "Vérifier chaque page", + "s0209": "Échec de la vérification", + "s0210": "Vérifier le dossier", + "s0211": "Rechercher des mises à jour", + "s0212": "Vérification conservée", + "s0213": "Vérifier le résultat", + "s0214": "Vérification indisponible", + "s0215": "Analysez votre ordinateur pour savoir quels modèles lui conviennent.", + "s0216": "Vérifié à", + "s0217": "Vérification d’une révision ultérieure", + "s0218": "Vérification des modifications…", + "s0219": "Vérification de l’exhaustivité et de ce qui fonctionnait déjà.", + "s0220": "Vérification du brouillon…", + "s0221": "Vérification des fichiers…", + "s0222": "Recherche de nouvelles versions…", + "s0223": "Analyse du matériel", + "s0224": "Vérification des menus, des commandes et de la navigation au clavier.", + "s0225": "Vérification des espacements et de l’alignement des composants.", + "s0226": "Vérification du stockage…", + "s0227": "Vérification…", + "s0228": "Vérifications et historique", + "s0229": "Chinois", + "s0230": "Choisissez CPU uniquement comme périphérique d’exécution, ou activez les couches GPU.", + "s0231": "Choisir les GPU…", + "s0232": "Choisissez Désactivé, Q4, Q5, Q6 ou Q8.", + "s0233": "Choisissez Ouvrir ou Afficher dans l’explorateur de fichiers.", + "s0234": "Choisissez un fichier GGUF.", + "s0235": "Choisissez un fichier de moins de 20 Mo.", + "s0236": "Choisissez d’abord un dossier.", + "s0237": "Choisissez un dossier à parcourir.", + "s0238": "Choisissez un dossier, pas un fichier.", + "s0239": "Choisissez l’ID d’un modèle chargé.", + "s0240": "Choisissez un modèle local qui lit les images avant d’envoyer des images jointes.", + "s0241": "Choisir un modèle", + "s0242": "Indiquez l’ID du modèle dans votre requête quand plusieurs modèles sont chargés.", + "s0243": "Choisissez un fichier de modèle ou saisissez son chemin complet.", + "s0244": "Choisissez un dossier de modèles.", + "s0245": "Choisissez une image de moins de 2 Mo.", + "s0246": "Choisissez un port entre 1024 et 65535.", + "s0247": "Choisissez un fournisseur, saisissez sa clé API, puis sélectionnez les modèles à ajouter.", + "s0248": "Choisissez une préférence de ressources.", + "s0249": "Choisissez un dossier distinct pour les modèles, en dehors des données de l’application Strata.", + "s0250": "Choisir un modèle plus petit", + "s0251": "Choisissez un contexte de conversation pris en charge.", + "s0252": "Choisissez une opération native prise en charge.", + "s0253": "Choisissez une planification prise en charge.", + "s0254": "Choisir une police système", + "s0255": "Choisissez une URL temporaire ou votre propre domaine.", + "s0256": "Choisissez une heure valide.", + "s0257": "Choisir une version", + "s0258": "Choisissez une version, puis chargez-la depuis Modèles. Les fichiers natifs partagés sont regroupés dans Stockage.", + "s0259": "Choisir une version…", + "s0260": "Choisissez un jour de la semaine.", + "s0261": "Choisissez une version d’image à télécharger.", + "s0262": "Choisir un modèle qui lit les images", + "s0263": "Choisir une installation", + "s0264": "Choisissez une police installée pour l’interface et les conversations.", + "s0265": "Choisissez un modèle installé.", + "s0266": "Choisir un autre fichier", + "s0267": "Choisir un autre dossier", + "s0268": "Choisissez un autre dossier ou un modèle plus petit.", + "s0269": "Choisissez les GPU détectés, ou CPU uniquement.", + "s0270": "Choisissez des GPU détectés différents. L’inférence de texte sur CPU seul n’est pas prise en charge par cet adaptateur natif.", + "s0271": "Choisissez des alias de modèle distincts, de 80 caractères maximum chacun.", + "s0272": "Choisir un fichier", + "s0273": "Choisir un dossier", + "s0274": "Choisir un modèle : {0}", + "s0275": "Choisissez un point de répartition des couches entre chaque paire de GPU.", + "s0276": "Choisissez des images de moins de 2 Mo.", + "s0277": "Choisir la planification", + "s0278": "Choisissez l’exécution d’un seul modèle ou de plusieurs.", + "s0279": "Choisissez le dossier du dépôt Strata qui contient setup.py et tools/strata_mcp.py.", + "s0280": "Choisir le meilleur travail", + "s0281": "Choisissez le dossier et nous démarrerons vos modèles avec Strata.", + "s0282": "Choisissez la langue utilisée dans tout Strata.", + "s0283": "Choisissez le", + "s0284": "Choisissez si la lecture des images doit être activée.", + "s0285": "Choisissez votre adresse", + "s0286": "Choisissez votre dossier de modèles", + "s0287": "Choix des réglages recommandés", + "s0288": "Choisi pendant l’installation. Les modèles déjà préparés continuent d’utiliser leurs fichiers actuels.", + "s0289": "Effacer les filtres", + "s0290": "Résultat clair · progression mesurable", + "s0291": "Effacer la recherche", + "s0292": "Effacer le raccourci de {0}", + "s0293": "Point de départ clair", + "s0294": "Moyen clair de vérifier", + "s0295": "Étapes suivantes plus claires", + "s0296": "Cliquez sur un raccourci, puis appuyez sur les touches de votre choix. Les modifications sont enregistrées dans ce navigateur. Échap annule l’enregistrement.", + "s0297": "Client / point d’accès", + "s0298": "Client, modèle ou ID de requête…", + "s0299": "Fermer", + "s0300": "Fermer la recherche de conversations", + "s0301": "Fermer le contexte de la conversation", + "s0302": "Fermer la dictée", + "s0303": "Fermer le mode expert", + "s0304": "Fermer la navigation", + "s0305": "Fermer {0}", + "s0306": "Type de connexion Cloudflare", + "s0307": "Tableau de bord Cloudflare ↗", + "s0308": "Tunnel Cloudflare", + "s0309": "Cloudflare créera votre adresse quand vous vous connecterez.", + "s0310": "Le service de téléchargement de Cloudflare est indisponible. Réessayez dans un instant.", + "s0311": "Coder", + "s0312": "Coder · IQ1_M", + "s0313": "Programmation", + "s0314": "Réduire le panneau d’aperçu", + "s0315": "Recueillir les retours", + "s0316": "Recueillir les retours d’ici vendredi", + "s0317": "Collecte et journaux", + "s0318": "Confortable", + "s0319": "Tient confortablement · estimation", + "s0320": "Espacement confortable par défaut.", + "s0321": "Bientôt disponible", + "s0322": "Noms séparés par des virgules que les clients peuvent utiliser pour ce modèle.", + "s0323": "Palette de commandes", + "s0324": "Commandes", + "s0325": "Compact", + "s0326": "Comparer", + "s0327": "Comparer et garder", + "s0328": "Comparer les résultats", + "s0329": "Comparaison du candidat avec l’original sur les mêmes vérifications.", + "s0330": "La compatibilité et les tailles dépendent de la version de Strata installée.", + "s0331": "GPU compatible trouvé", + "s0332": "Terminé", + "s0333": "Mémoire de l’ordinateur", + "s0334": "Préférence de ressources de l’ordinateur", + "s0335": "Utilisation de l’ordinateur", + "s0336": "Requêtes simultanées", + "s0337": "Configuration vérifiée. Aucune erreur de validation.", + "s0338": "Brouillon de configuration", + "s0339": "Exemple de configuration", + "s0340": "La configuration doit être un objet JSON.", + "s0341": "Connecter Strata à une application", + "s0342": "Connectez un fournisseur d’API ou un serveur de modèles sur un autre ordinateur.", + "s0343": "Connecter une application", + "s0344": "Connecter un domaine", + "s0345": "Connecter le moteur", + "s0346": "Connecter l’installation", + "s0347": "Connectez le moteur pour configurer un modèle.", + "s0348": "Connectez le moteur pour modifier ses réglages.", + "s0349": "Se connecter avec Cloudflare", + "s0350": "Connectez votre installation de Strata", + "s0351": "Connectez votre installation locale pour choisir un modèle optimisé.", + "s0352": "Connecté", + "s0353": "Connecté. Réinitialiser pour remettre le compteur à zéro", + "s0354": "Les serveurs connectés peuvent agir sur les ressources que vous avez configurées. Les appels s’exécutent automatiquement quand le modèle les choisit, et leurs résultats apparaissent dans la conversation.", + "s0355": "Outil connecté", + "s0356": "Outils connectés", + "s0357": "Connexion à Cloudflare…", + "s0358": "Connexion au moteur local…", + "s0359": "Connexion…", + "s0360": "Détails de la connexion", + "s0361": "Échec de la connexion", + "s0362": "Guide de connexion", + "s0363": "Modèle du guide de connexion", + "s0364": "Progression de la connexion", + "s0365": "Réglages de connexion", + "s0366": "Type de connexion", + "s0367": "Connecteur", + "s0368": "Connecteur prêt", + "s0369": "La configuration du connecteur est déjà en cours.", + "s0370": "Le contenu déborde", + "s0371": "Contexte", + "s0372": "Cache de contexte", + "s0373": "Le cache de contexte a besoin de plus de mémoire", + "s0374": "Remplissage du contexte", + "s0375": "Longueur du contexte", + "s0376": "Limite de contexte", + "s0377": "Mémoire de contexte", + "s0378": "Le contexte a besoin de plus de mémoire", + "s0379": "Contexte non pris en charge", + "s0380": "Préréglages de contexte", + "s0381": "Contexte trop long", + "s0382": "Contexte trop court", + "s0383": "Contexte utilisé", + "s0384": "Fenêtre de contexte utilisée", + "s0385": "Continuer", + "s0386": "Reprenez là où vous vous êtes arrêté. Ne répétez pas ce que vous avez déjà écrit.", + "s0387": "Passer à la conversation sans résultat de vitesse", + "s0388": "Contraste", + "s0389": "Contrôle", + "s0390": "Cache de conversation", + "s0391": "Mémoire du cache de conversation", + "s0392": "Contexte de la conversation", + "s0393": "Contexte de la conversation ·", + "s0394": "Taille du texte des conversations. Les commandes de l’interface restent à part.", + "s0395": "Copier l’URL de base de l’API", + "s0396": "Copier l’URL du tunnel Cloudflare", + "s0397": "Copier l’ID du modèle", + "s0398": "Copier le code", + "s0399": "Copier l’URL du réseau local", + "s0400": "Copier le message", + "s0401": "Copier l’ID du modèle {0}", + "s0402": "Copier la nouvelle clé API", + "s0403": "Copier le modèle de requête", + "s0404": "Copier la réponse", + "s0405": "Copier l’évaluation", + "s0406": "Copiez cette clé dans votre client. Elle prend effet quand vous choisissez Utiliser cette clé.", + "s0407": "Copier l’URL du tunnel", + "s0408": "Copier l’URL du service du tunnel", + "s0409": "Mise en page de base", + "s0410": "Corrigez la configuration avant d’enregistrer un profil.", + "s0411": "Impossible de calculer la prochaine exécution.", + "s0412": "Impossible de rechercher les mises à jour.", + "s0413": "Impossible de rechercher les mises à jour. Réessayez.", + "s0414": "Impossible de supprimer cette version. Consultez la notification et réessayez.", + "s0415": "Impossible de récupérer les modèles. Vous pouvez ajouter un ID de modèle ci-dessous.", + "s0416": "Impossible de récupérer la liste des modèles.", + "s0417": "Impossible de charger le modèle", + "s0418": "Impossible de lire les métadonnées GGUF.", + "s0419": "Impossible de lire l’image jointe.", + "s0420": "Impossible de lire le fichier.", + "s0421": "Impossible de lire ce fichier.", + "s0422": "Impossible de lire cette image.", + "s0423": "Impossible de supprimer la connexion.", + "s0424": "Impossible d’enregistrer la connexion.", + "s0425": "Impossible de stocker cette image. Vérifiez le stockage du navigateur.", + "s0426": "Impossible de décharger le modèle. Réessayez quand le moteur est inactif.", + "s0427": "Impossible d’ajouter ce dossier", + "s0428": "Impossible de retirer cet espace de travail", + "s0429": "Copie impossible", + "s0430": "Impossible de charger les tâches.", + "s0431": "Impossible de charger cette image.", + "s0432": "Impossible d’ouvrir ce PDF.", + "s0433": "Composant compteur", + "s0434": "Créez une clé API Strata avant de connecter Cloudflare.", + "s0435": "Créez une clé pour protéger votre API. Vous reviendrez ici quand elle sera prête.", + "s0436": "Créer un plan avant de modifier quoi que ce soit", + "s0437": "Créez un tunnel dans votre", + "s0438": "Créer une clé API", + "s0439": "Créez d’abord une clé API", + "s0440": "Créer la tâche", + "s0441": "Créer une URL temporaire", + "s0442": "Créer avec l’IA", + "s0443": "Identifiants et environnement", + "s0444": "Ctrl", + "s0445": "Ctrl+Maj+A", + "s0446": "Contexte actuel", + "s0447": "Moteur actuel", + "s0448": "Progression du téléchargement du fichier en cours", + "s0449": "Réglages actuels", + "s0450": "Personnalisé", + "s0451": "Contexte personnalisé en K tokens", + "s0452": "API de modèle personnalisée", + "s0453": "Modèle personnalisé · la compatibilité avec le moteur est vérifiée au chargement. Les estimations de mémoire s’appuient sur les métadonnées du fichier.", + "s0454": "Tous les jours", + "s0455": "Point quotidien", + "s0456": "Activité quotidienne des messages. {0} jours actifs sur cette période.", + "s0457": "Sombre", + "s0458": "Jour", + "s0459": "Jour de la semaine", + "s0460": "Décodage", + "s0461": "Décodage de la dernière requête", + "s0462": "Décodage actuel", + "s0463": "Décodage :", + "s0464": "Par défaut", + "s0465": "Valeur par défaut pour ce modèle", + "s0466": "Supprimer", + "s0467": "Supprimer la conversation", + "s0468": "Supprimer la version téléchargée du modèle", + "s0469": "Supprimer les fichiers", + "s0470": "Supprimer les fichiers…", + "s0471": "Supprimer la tâche", + "s0472": "Supprimer la tâche {0}", + "s0473": "Supprimer cette conversation ?", + "s0474": "Supprimer cette tâche ?", + "s0475": "Supprimer cette version ?", + "s0476": "Supprimer la version", + "s0477": "Supprimer {0}", + "s0478": "Supprimer {0} ?", + "s0479": "Tâches supprimées", + "s0480": "Suppression…", + "s0481": "Simulé", + "s0482": "Votre approbation est nécessaire", + "s0483": "Refusé. Rien n’a été exécuté.", + "s0484": "Approbation enregistrée. Rien n’a été exécuté.", + "s0485": "Estimation indicative", + "s0486": "État d’installation d’exemple effacé.", + "s0487": "Installation d’exemple lancée", + "s0488": "État de chargement d’exemple effacé.", + "s0489": "Modèle d’exemple prêt", + "s0490": "Modèle d’exemple · réponses fictives.", + "s0491": "Aperçu terminé. Aucune mesure n’a été effectuée.", + "s0492": "Progression", + "s0493": "Suggestion d’exemple.", + "s0494": "Tokens en entrée / sortie (exemple)", + "s0495": "Refusé", + "s0496": "Zone de texte dense", + "s0497": "Refuser", + "s0498": "Décrivez les tâches", + "s0499": "Décrivez d’abord la tâche.", + "s0500": "Décrivez cette image.", + "s0501": "Description", + "s0502": "Descriptions", + "s0503": "Aperçu du design · les réponses sont fictives.", + "s0504": "Revue du design · six aperçus", + "s0505": "Détails", + "s0506": "Deutsch", + "s0507": "Diagnostic", + "s0508": "Dictée", + "s0509": "Impossible de lancer la dictée. Réessayez ou utilisez la dictée intégrée à votre ordinateur.", + "s0510": "Dictée terminée", + "s0511": "Dictée arrêtée", + "s0512": "Dictée indisponible", + "s0513": "Chemin du dossier", + "s0514": "Désactivé", + "s0515": "Abandonner", + "s0516": "Abandonner toutes les modifications non enregistrées du moteur et revenir à la configuration enregistrée.", + "s0517": "Abandonner les modifications", + "s0518": "Abandonner les modifications de la configuration ?", + "s0519": "Abandon de la révision la plus faible et reprise à partir de B.", + "s0520": "Lecture disque", + "s0521": "Ignorer", + "s0522": "Nom affiché", + "s0523": "Texte du document", + "s0524": "Documents / Strata / Models", + "s0525": "La modification tient-elle la route ?", + "s0526": "Terminé", + "s0527": "Comparaison terminée", + "s0528": "Télécharger", + "s0529": "Télécharger et charger", + "s0530": "Télécharger et préparer", + "s0531": "Téléchargement annulé.", + "s0532": "Échec du téléchargement", + "s0533": "Télécharger le modèle", + "s0534": "Télécharger la version du modèle", + "s0535": "Télécharger le journal de session", + "s0536": "Taille du téléchargement", + "s0537": "Téléchargement lancé", + "s0538": "Téléchargement arrêté. Reprenez quand vous voulez.", + "s0539": "Télécharger la conversation active au format Markdown", + "s0540": "Téléchargez d’abord la version sélectionnée du modèle d’image.", + "s0541": "Téléchargez ce modèle avant de le charger.", + "s0542": "Téléchargez cette version du modèle avant de la charger.", + "s0543": "Téléchargez cette version pour l’utiliser.", + "s0544": "Le téléchargement a expiré. Réessayez depuis Modèles.", + "s0545": "Télécharger la version", + "s0546": "Télécharger {0}", + "s0547": "Télécharger · {0}", + "s0548": "Téléchargé", + "s0549": "Modèles téléchargés", + "s0550": "Versions téléchargées de {0}", + "s0551": "Téléchargé · moteur d’image requis", + "s0552": "Téléchargement", + "s0553": "Téléchargement et préparation des fichiers du modèle…", + "s0554": "Téléchargement des fichiers du modèle…", + "s0555": "Téléchargement du modèle...", + "s0556": "Téléchargement : {0} %", + "s0557": "Téléchargement…", + "s0558": "Les téléchargements ne démarrent que lorsque vous êtes prêt.", + "s0559": "Les échecs de téléchargement, de préparation et du moteur affichent ici leurs messages d’origine.", + "s0560": "Brouillon", + "s0561": "Brouillon / spéculation", + "s0562": "Profondeur du brouillon", + "s0563": "Brouillon : {0}{1} Go estimés", + "s0564": "Rédaction…", + "s0565": "Faites glisser pour comparer", + "s0566": "Faites glisser pour redimensionner · les flèches ajustent · double-clic pour réinitialiser", + "s0567": "Durée", + "s0568": "Mode simple", + "s0569": "Facile à utiliser", + "s0570": "Modifier", + "s0571": "Modifier le serveur MCP {0}", + "s0572": "Modifier les réglages enregistrés…", + "s0573": "Modifier les raccourcis", + "s0574": "Modifier la compétence", + "s0575": "Modifier la tâche", + "s0576": "Modifier la tâche {0}", + "s0577": "Modifier le serveur d’outils", + "s0578": "Modifier {0}", + "s0579": "Modification à partir d’un message précédent. Mettez à jour le prompt ci-dessous.", + "s0580": "Cache d’experts GPU élastique", + "s0581": "Activer le serveur MCP {0}", + "s0582": "Activez Lire les images pour ce modèle avant d’envoyer des images.", + "s0583": "Activez Lire les images dans Modèles pour envoyer cette image au modèle. Elle est ouverte dans l’aperçu.", + "s0584": "Activer les outils connectés ?", + "s0585": "Activer les outils", + "s0586": "Activer {0}", + "s0587": "Activé", + "s0588": "Moteur", + "s0589": "Les arguments du moteur et les variables d’environnement STRATA se modifient ici. Les chemins des programmes et l’accès réseau restent gérés par l’hôte.", + "s0590": "Les arguments du moteur doivent être des valeurs de texte. L’accès réseau reste géré par Strata.", + "s0591": "Moteur modifié · réoptimisez avant de lancer", + "s0592": "Le moteur n’est pas devenu opérationnel à temps", + "s0593": "L’environnement du moteur doit être un objet.", + "s0594": "Erreur du moteur", + "s0595": "Hôte du moteur injoignable", + "s0596": "Installation du moteur", + "s0597": "Journal du moteur", + "s0598": "Niveau de journalisation du moteur", + "s0599": "Opération du moteur", + "s0600": "Emplacements de requêtes du moteur", + "s0601": "Moteur redémarré", + "s0602": "Délai de blocage du moteur (secondes)", + "s0603": "Moteur décompressé, mais aucun binaire llama-server n’a été trouvé", + "s0604": "La recherche de mises à jour du moteur n’est pas disponible dans cette version.", + "s0605": "Anglais", + "s0606": "Suffisant pour un modèle", + "s0607": "Suffisant pour le modèle recommandé", + "s0608": "Suffisant pour le plus petit modèle", + "s0609": "Saisir la clé API", + "s0610": "Saisissez un nom affiché de 160 caractères maximum.", + "s0611": "Saisissez un nom affiché.", + "s0612": "Saisissez le nom d’une famille de polices", + "s0613": "Saisissez une adresse complète en http:// ou https://.", + "s0614": "Saisissez un chemin complet.", + "s0615": "Saisissez un nom d’hôte comme ai.example.com, sans https:// ni chemin.", + "s0616": "Saisissez un dossier de modèles.", + "s0617": "Saisissez un nombre positif.", + "s0618": "Saisissez le chemin complet d’un dossier existant.", + "s0619": "Saisissez l’URL du serveur ou le programme.", + "s0620": "Saisissez votre clé API existante dans le client.", + "s0621": "Erreur", + "s0622": "Erreurs", + "s0623": "Échap", + "s0624": "Estimé", + "s0625": "Mémoire estimée", + "s0626": "Mémoire de travail estimée (", + "s0627": "Tous les jours", + "s0628": "Toutes les heures", + "s0629": "Toutes les valeurs sont revenues à la valeur par défaut sûre.", + "s0630": "Toutes les semaines", + "s0631": "Au quotidien", + "s0632": "Choix au quotidien", + "s0633": "Travail au quotidien", + "s0634": "Tout ce qu’il faut pour le modèle recommandé est présent.", + "s0635": "Valeur exacte", + "s0636": "Exemple", + "s0637": "Exemple : Passez en revue ce projet et résumez ce qui a changé.", + "s0638": "Dépasse le budget de mémoire estimé", + "s0639": "Dépasse le budget de mémoire", + "s0640": "Périphérique d’exécution", + "s0641": "Les fichiers existants sont vérifiés et réutilisés. Les modèles natifs actuellement chargés seront déchargés avant la préparation des fichiers.", + "s0642": "Les fichiers existants restent où ils sont. Strata cherche dans ce dossier les fichiers GGUF pris en charge.", + "s0643": "Dossier de modèles existant", + "s0644": "Quitter l’aperçu plein écran", + "s0645": "Une capture d’écran PNG de moins de 18 Mo était attendue.", + "s0646": "Expérience attendue", + "s0647": "Vecteur de contrôle expérimental. Nécessite un moteur compatible avec le vecteur chargé.", + "s0648": "Cache d’experts", + "s0649": "Cache d’experts / mode RAM", + "s0650": "Emplacements du cache d’experts", + "s0651": "Éditeur expert", + "s0652": "Mode expert", + "s0653": "Réglages experts", + "s0654": "Valeur experte", + "s0655": "Experts en VRAM", + "s0656": "Experts signalés par ce moteur.", + "s0657": "Explique en langage simple ce que cette machine peut exécuter, d’après le CPU, le GPU et la mémoire détectés.", + "s0658": "Explorer une révision", + "s0659": "Explorez le déroulement du test. Les valeurs de l’aperçu ne sont jamais enregistrées comme des performances mesurées ni utilisées comme preuve pour une vraie recommandation.", + "s0660": "Exploration d’une idée", + "s0661": "Exporter", + "s0662": "Exporter la conversation", + "s0663": "Marge supplémentaire", + "s0664": "Échec", + "s0665": "Adéquation rapide", + "s0666": "Réponses plus rapides", + "s0667": "Le plus rapide", + "s0668": "IA la plus rapide", + "s0669": "Modèle favori", + "s0670": "Récupérer les modèles disponibles", + "s0671": "Récupération…", + "s0672": "Peu de cœurs : attendez-vous à une lecture lente du prompt", + "s0673": "Fieldnotes cover.svg", + "s0674": "Fieldnotes — site web", + "s0675": "Emplacement du fichier", + "s0676": "Le fichier a renvoyé {0}", + "s0677": "Les mises à jour de fichiers ne peuvent pas être annulées sans risque pendant le remplacement des fichiers.", + "s0678": "Fichiers installés", + "s0679": "Fichiers supprimés", + "s0680": "Les fichiers restent sur votre ordinateur. Ajoutez à nouveau ce dossier pour rouvrir ses conversations.", + "s0681": "Filtrer les modèles disponibles", + "s0682": "Filtrer les modèles…", + "s0683": "Filtrer les lignes…", + "s0684": "Filtrer le tableau", + "s0685": "Trouvez un point de départ pour votre matériel, puis vérifiez avant d’enregistrer.", + "s0686": "Trouver les réglages les plus rapides pour ce PC", + "s0687": "Prise de rythme", + "s0688": "Terminer plus tard", + "s0689": "Terminez ou annulez les téléchargements et les chargements pour changer de dossier.", + "s0690": "Terminez ou annulez les téléchargements et les chargements de modèles avant de changer de dossier.", + "s0691": "Terminez ou annulez les requêtes du modèle avant de changer de dossier.", + "s0692": "Terminez ou annulez les requêtes natives avant de changer de modèle.", + "s0693": "Terminez ou annulez les requêtes avant de préparer les fichiers du modèle.", + "s0694": "Terminez ou annulez d’abord l’opération en cours du moteur.", + "s0695": "Terminez ou annulez d’abord le téléchargement du modèle d’image en cours.", + "s0696": "Terminez ou annulez d’abord le téléchargement de l’image.", + "s0697": "Terminez ou annulez les requêtes de ce modèle avant de le décharger.", + "s0698": "Terminez ou annulez d’abord les requêtes de ce modèle.", + "s0699": "Terminez les requêtes avant de changer de moteur.", + "s0700": "Terminez les requêtes avant d’optimiser.", + "s0701": "Terminez l’opération en cours avant de changer de dossier.", + "s0702": "Terminez l’opération en cours avant d’enregistrer les réglages natifs.", + "s0703": "Terminez les requêtes de ce modèle avant d’enregistrer ses réglages.", + "s0704": "Fin de la dictée…", + "s0705": "Finalisation…", + "s0706": "Adéquation", + "s0707": "Ajuster la sortie au contexte restant", + "s0708": "Adéquation inconnue", + "s0709": "Tient en mémoire", + "s0710": "Tient dans la fenêtre", + "s0711": "Corriger la réinitialisation et l’affichage mobile en conservant la mise en page.", + "s0712": "Corrigez le JSON avant de changer d’onglet.", + "s0713": "Corrigez le JSON de configuration de l’outil.", + "s0714": "Corriger les 3 principaux problèmes", + "s0715": "Flash attention", + "s0716": "Se concentrer sur la conversation", + "s0717": "Lecture ciblée", + "s0718": "Concentrez cet ordinateur sur votre IA.", + "s0719": "Dossier contenant setup.py", + "s0720": "Suivre le système", + "s0721": "Suivre le réglage par défaut du modèle, ou ne réfléchir que sur demande.", + "s0722": "Les requêtes suivantes peuvent réutiliser les tokens en cache du prompt précédent.", + "s0723": "Police", + "s0724": "Famille de polices", + "s0725": "Par exemple : /time-skip Faites un plan de lancement pour mon application", + "s0726": "{0} modèles trouvés. Choisissez ceux à afficher dans la conversation.", + "s0727": "Stockage libre", + "s0728": "URL temporaire gratuite", + "s0729": "Libère la mémoire du modèle", + "s0730": "Pénalité de fréquence", + "s0731": "Vendredis", + "s0732": "D’après les métadonnées GGUF", + "s0733": "Complet", + "s0734": "Chemin complet du dossier", + "s0735": "Chemin complet d’un dossier existant", + "s0736": "Performances maximales", + "s0737": "Priorité maximale pour Strata", + "s0738": "Aperçu plein écran", + "s0739": "Pleine vitesse", + "s0740": "Go", + "s0741": "Go de RAM", + "s0742": "Go de RAM", + "s0743": "Go de marge en RAM · les estimations incluent tous les modèles chargés", + "s0744": "Go de VRAM", + "s0745": "Go de budget", + "s0746": "Go restants dans ce fichier", + "s0747": "Go restants à télécharger", + "s0748": "Go requis", + "s0749": "Go à télécharger", + "s0750": "Go/s", + "s0751": "Le GGUF contient des noms de tenseurs en double.", + "s0752": "Fichiers GGUF de ce dossier. Les téléchargements dans des sous-dossiers sont vérifiés par l’installateur.", + "s0753": "Un entier du GGUF est trop grand.", + "s0754": "Un tableau de métadonnées GGUF est trop grand.", + "s0755": "Les tableaux de métadonnées GGUF sont imbriqués trop profondément.", + "s0756": "Les métadonnées GGUF contiennent une clé en double.", + "s0757": "Les métadonnées GGUF contiennent une chaîne trop longue.", + "s0758": "Les métadonnées GGUF contiennent un entier non pris en charge.", + "s0759": "Les métadonnées GGUF contiennent trop d’entrées.", + "s0760": "Les métadonnées GGUF utilisent un type de valeur non pris en charge.", + "s0761": "L’alignement des tenseurs du GGUF n’est pas valide.", + "s0762": "Les dimensions des tenseurs du GGUF ne sont pas valides.", + "s0763": "La disposition des tenseurs du GGUF n’est pas valide.", + "s0764": "GPU", + "s0765": "GPU / répartition des couches", + "s0766": "GPU et pilote", + "s0767": "L’attribution des GPU nécessite un adaptateur de moteur natif. Utilisez Automatique avec cet hôte.", + "s0768": "Charge du GPU", + "s0769": "Mémoire du GPU", + "s0770": "Détail de la mémoire du GPU", + "s0771": "Mémoire GPU réservée aux autres applications (Mio)", + "s0772": "Ordre des GPU", + "s0773": "Puissance du GPU", + "s0774": "Consommation du GPU", + "s0775": "Les mesures du GPU incluent tout le travail effectué sur ce périphérique. La RAM système est partagée par tous les modèles.", + "s0776": "Temp. GPU", + "s0777": "Température du GPU", + "s0778": "GPU indisponible", + "s0779": "GPU {0}", + "s0780": "GPU {0} ·", + "s0781": "GPU {0} · {1}", + "s0782": "GPU", + "s0783": "GPU connectés", + "s0784": "Général", + "s0785": "Générer", + "s0786": "Générer une autre", + "s0787": "Générer un exemple de réponse", + "s0788": "Génération", + "s0789": "Génération en tok/s", + "s0790": "Échec de la génération", + "s0791": "Vitesse de génération", + "s0792": "Obtenir Strata", + "s0793": "Préparez mon portfolio pour la publication.", + "s0794": "Faites avancer vos projets sur du matériel qui vous appartient.", + "s0795": "Obtenir la mise à jour", + "s0796": "Préparation des fichiers…", + "s0797": "Préparation de votre installation…", + "s0798": "Git n’a pas pu mettre à jour cette installation. Ouvrez le diagnostic.", + "s0799": "Donner la priorité à Strata", + "s0800": "Donnez à chaque serveur d’outils un nom simple et unique.", + "s0801": "Donnez-moi un court exercice d’écriture et un exemple de réponse. Restez pratique et sous les 200 mots.", + "s0802": "Donner plus de threads CPU au moteur", + "s0803": "Donnez une ligne d’arrivée à votre IA.", + "s0804": "Donnez à votre IA les ressources disponibles pour travailler sans distraction.", + "s0805": "Donnez à votre API locale une adresse HTTPS qu’une autre application peut atteindre.", + "s0806": "Donner plus de ressources à votre modèle", + "s0807": "Global · toutes les conversations", + "s0808": "Aller", + "s0809": "Aller directement à l’application", + "s0810": "Aller à", + "s0811": "Objectif", + "s0812": "Grammaire", + "s0813": "Aperçu HTML", + "s0814": "Serveur HTTP", + "s0815": "Marge pour vos autres applications", + "s0816": "Bonjour, je suis Strata.", + "s0817": "Aidez-moi à pratiquer l’espagnol chaque matin…", + "s0818": "Masquer", + "s0819": "Masquer la clé API", + "s0820": "Masquer les journaux", + "s0821": "Masquer la barre latérale", + "s0822": "Masque la navigation dans la conversation. Les Paramètres restent ouverts au-dessus de la conversation.", + "s0823": "Élevé", + "s0824": "Haute qualité", + "s0825": "Plus haute borne inférieure de {0} prise en charge parmi les candidats comparables qui tiennent. {1}.", + "s0826": "Historique", + "s0827": "GPU sélectionné le plus chaud", + "s0828": "Ce que votre modèle peut garder en tête.", + "s0829": "Comment fonctionne le partage des ressources", + "s0830": "Comment souhaitez-vous travailler avec Strata ?", + "s0831": "ID", + "s0832": "INT8", + "s0833": "Inactif", + "s0834": "Illustratif", + "s0835": "Exemple d’interface illustratif · ni une mesure ni une prévision matérielle", + "s0836": "Estimations illustratives", + "s0837": "Aperçu de design illustratif avec contexte, utilisation de l’ordinateur et débordement sur SSD. Pas un test de performance.", + "s0838": "Image", + "s0839": "Séparateur de comparaison d’images", + "s0840": "Périphérique de l’encodeur d’images", + "s0841": "Génération d’images", + "s0842": "La génération d’images nécessite un moteur d’images, un encodeur de texte et un VAE compatibles.", + "s0843": "Modèle d’image", + "s0844": "Progression du téléchargement du modèle d’image", + "s0845": "La mémoire du modèle d’image n’est pas incluse dans cette estimation.", + "s0846": "Version du modèle d’image", + "s0847": "Lecture d’images", + "s0848": "Importer", + "s0849": "Échec de l’importation : {0}", + "s0850": "Améliorez ce plan de lancement.", + "s0851": "Amélioration du brouillon enregistré.", + "s0852": "En cours", + "s0853": "Dans votre client, choisissez un fournisseur compatible.", + "s0854": "Inclure les conversations archivées", + "s0855": "Incluez le préfixe de l’API, comme /v1, mais sans /models ni /chat/completions.", + "s0856": "Augmenter le contraste du texte et des bordures.", + "s0857": "Augmenté", + "s0858": "Tokens en entrée", + "s0859": "Installez un moteur llama-server compatible avant de quitter Strata natif.", + "s0860": "Dossier d’installation", + "s0861": "Installé", + "s0862": "Polices installées", + "s0863": "Version installée", + "s0864": "Instructions", + "s0865": "Instructions envoyées :", + "s0866": "Revue des interactions", + "s0867": "Taille de l’interface", + "s0868": "Espacement de l’interface", + "s0869": "Port interne du moteur", + "s0870": "Clé API non valide", + "s0871": "JSON non valide", + "s0872": "Capture d’écran PNG non valide.", + "s0873": "Inviter quelques testeurs", + "s0874": "Ses fichiers seront supprimés de cet ordinateur.", + "s0875": "Ses modèles seront retirés du sélecteur de conversation. Vos conversations restent enregistrées.", + "s0876": "JSON", + "s0877": "Japonais", + "s0878": "K de contexte · lot", + "s0879": "K tokens", + "s0880": "K. Choisissez un contexte pris en charge pour l’exécuter.", + "s0881": "Mode KV", + "s0882": "Conserver les métadonnées des requêtes API", + "s0883": "Gardez une clé tant que l’API est accessible à d’autres appareils.", + "s0884": "Garder la conversation", + "s0885": "Garder la connexion", + "s0886": "Continuer à modifier", + "s0887": "Garder le moteur prêt", + "s0888": "Garder les experts en RAM", + "s0889": "Garder la clé", + "s0890": "Garder les modèles chargés quand vous en ajoutez un autre.", + "s0891": "Garder la tâche", + "s0892": "Garder le style botanique et rendre le titre plus facile à parcourir.", + "s0893": "Conserver la progression réalisée.", + "s0894": "Garder l’idée la plus solide.", + "s0895": "Garder cet ordinateur réactif", + "s0896": "Garder les outils désactivés", + "s0897": "Garder le résultat mis à jour", + "s0898": "Garder la version", + "s0899": "Garder l’espace de travail", + "s0900": "Gardez votre navigateur et vos outils à côté de votre IA.", + "s0901": "Conservation de B", + "s0902": "L’original est conservé pendant qu’un candidat comble ses lacunes.", + "s0903": "Résultat conservé", + "s0904": "Conservé de la mise à jour", + "s0905": "Détail clé supprimé", + "s0906": "Raccourcis clavier", + "s0907": "Coréen", + "s0908": "Libellés et descriptions relus.", + "s0909": "Langue", + "s0910": "Dernière requête", + "s0911": "Taille de la dernière requête", + "s0912": "Dernier résultat", + "s0913": "Dernière exécution échouée · Voir", + "s0914": "Dernier changement", + "s0915": "Révision ultérieure non conservée", + "s0916": "Dernière version", + "s0917": "Vitesse de la dernière réponse", + "s0918": "Plan de lancement", + "s0919": "Répartition des couches", + "s0920": "Les points de répartition des couches doivent augmenter de 1 à 47, par exemple 16,32.", + "s0921": "Revue de la mise en page", + "s0922": "Mise en page simplifiée", + "s0923": "Apprenez une notion utile à la fois.", + "s0924": "Prompt d’apprentissage", + "s0925": "Garder 20 % pour mon travail", + "s0926": "Laissez vide pour utiliser la valeur par défaut du modèle.", + "s0927": "Laissez vide pour garder la clé enregistrée", + "s0928": "Quitter le mode concentration", + "s0929": "Laisser de la place aux autres applications", + "s0930": "Moins", + "s0931": "Laissez un autre appareil de votre réseau utiliser vos modèles chargés.", + "s0932": "Laissez le travail utile se répéter.", + "s0933": "C’est parti", + "s0934": "Clair", + "s0935": "Clair par défaut. Système suit votre ordinateur.", + "s0936": "Devrait tenir (estimation)", + "s0937": "Limite l’échantillonnage aux mots les plus probables.", + "s0938": "Ligne {0}, colonne {1} : {2}", + "s0939": "Je vous écoute…", + "s0940": "Estimation en direct d’après la longueur de la réponse et le temps écoulé. L’utilisation finale vient du moteur.", + "s0941": "Charger", + "s0942": "Chargez à nouveau un modèle après le changement.", + "s0943": "Chargez un modèle avant de terminer l’installation.", + "s0944": "Chargez un modèle dans Modèles pour le rendre disponible ici.", + "s0945": "Chargez un modèle Strata natif pour utiliser l’API Responses.", + "s0946": "Chargez d’abord un modèle natif.", + "s0947": "Charger le modèle", + "s0948": "Charger à la première requête", + "s0949": "Les réglages de chargement s’appliquent au prochain chargement. Les valeurs d’échantillonnage par défaut s’appliquent à la prochaine requête.", + "s0950": "Les réglages de chargement s’appliquent quand vous lancez le modèle.", + "s0951": "Chargez le modèle pour démarrer une requête.", + "s0952": "Charger {0} pour toutes les conversations. Le chargement peut prendre quelques instants.", + "s0953": "Chargé", + "s0954": "Modèle chargé", + "s0955": "Modèles chargés", + "s0956": "Chargement", + "s0957": "Le chargement ajoute un modèle. Les modèles existants gardent leurs réglages et leurs GPU.", + "s0958": "Charger un autre modèle laisse les autres chargés.", + "s0959": "Le chargement applique ces réglages à cette instance. Les autres modèles restent chargés.", + "s0960": "Chargement du document…", + "s0961": "Chargement des polices installées…", + "s0962": "Chargement du modèle", + "s0963": "Chargement des versions du modèle…", + "s0964": "Chargement des réglages…", + "s0965": "Chargement des tâches…", + "s0966": "Chargement de vos modèles et de vos réglages…", + "s0967": "Chargement…", + "s0968": "L’IA en local. La vôtre.", + "s0969": "GGUF local ·", + "s0970": "Fichier local", + "s0971": "Fichiers de modèle locaux", + "s0972": "Modèle local retiré", + "s0973": "Modèle local ·", + "s0974": "Modèles locaux", + "s0975": "Les modèles locaux ne sont pas téléchargés. Choisissez à nouveau leur fichier GGUF pour les reconnecter.", + "s0976": "Réseau local", + "s0977": "Programme local", + "s0978": "Partage local", + "s0979": "Verrouiller le modèle en mémoire", + "s0980": "Contexte long", + "s0981": "Phrase plus longue", + "s0982": "Boucle", + "s0983": "Mode peu de RAM", + "s0984": "Mo/s", + "s0985": "Réglages de connexion avancés MCP", + "s0986": "Programme MCP", + "s0987": "Arguments du programme MCP", + "s0988": "URL du serveur MCP", + "s0989": "Configuration du serveur MCP", + "s0990": "Nom du serveur MCP", + "s0991": "Serveurs MCP", + "s0992": "Les serveurs MCP doivent former un objet de 30 entrées au maximum.", + "s0993": "Outils MCP", + "s0994": "Transport MCP", + "s0995": "Les 3 étapes ont été précisées", + "s0996": "Mise en page adaptée aux petits écrans", + "s0997": "Idée principale", + "s0998": "Navigation principale", + "s0999": "Apporter des améliorations", + "s1000": "Personnalisez", + "s1001": "Tirez le meilleur de cet ordinateur", + "s1002": "Rendre les étapes concrètes et ajouter un moyen de vérifier le résultat.", + "s1003": "Clarification de l’étape suivante.", + "s1004": "Gérer / arrêter", + "s1005": "Gérer les modèles API", + "s1006": "Gérer le tunnel Cloudflare", + "s1007": "Gérer la famille de modèles", + "s1008": "Gérer les modèles", + "s1009": "Manuel", + "s1010": "Vue Markdown", + "s1011": "Tokens de sortie max.", + "s1012": "Tokens max.", + "s1013": "Tokens d’image maximum", + "s1014": "Performances maximales", + "s1015": "Nombre maximal de caractères d’un résultat d’outil", + "s1016": "Nombre maximal de tours d’outils", + "s1017": "Peut être plus lent", + "s1018": "Peut être plus lent · Les données du modèle peuvent être lues sur le SSD.", + "s1019": "Mesurer les performances", + "s1020": "Mesurer la vitesse", + "s1021": "Mesurez la vitesse avec un test court. La calibration experte essaie des réglages du moteur et enregistre la configuration mesurée la plus rapide.", + "s1022": "Mesuré", + "s1023": "Mesure en cours…", + "s1024": "Mémoire", + "s1025": "Détail de la mémoire", + "s1026": "La mémoire pourrait être juste", + "s1027": "La mémoire pourrait être juste (estimation)", + "s1028": "Mémoire nécessaire", + "s1029": "Le placement en mémoire n’est pas disponible pour cette configuration.", + "s1030": "Mémoire · Non estimée ·", + "s1031": "Mapper les fichiers du modèle en mémoire", + "s1032": "Écrire à Strata", + "s1033": "Écrire à Strata…", + "s1034": "Messages", + "s1035": "Meta", + "s1036": "Mesures indisponibles", + "s1037": "L’accès au microphone a été refusé. Autorisez-le dans votre navigateur, puis réessayez.", + "s1038": "Tokens d’image minimum", + "s1039": "Mode", + "s1040": "Modèle", + "s1041": "Modèle / périphérique", + "s1042": "ID du modèle", + "s1043": "ID du modèle donné par votre fournisseur ou votre serveur", + "s1044": "Activité du modèle", + "s1045": "Changement de modèle indisponible", + "s1046": "Dossier des modèles", + "s1047": "Exécution du modèle", + "s1048": "Famille de modèles", + "s1049": "Chemin du fichier ou du dossier du modèle", + "s1050": "Fichiers du modèle", + "s1051": "Fichiers du modèle supprimés du disque.", + "s1052": "Modèle pour cette application", + "s1053": "Liste des modèles :", + "s1054": "Modèle chargé", + "s1055": "Mémoire du modèle libérée.", + "s1056": "Nom du modèle", + "s1057": "Le modèle a besoin de plus de mémoire", + "s1058": "Modèle pas prêt", + "s1059": "Performances du modèle", + "s1060": "Priorité du modèle", + "s1061": "Progression du modèle", + "s1062": "Modèle prêt", + "s1063": "Raisonnement du modèle", + "s1064": "Réglages du modèle", + "s1065": "Réglages et outils du modèle", + "s1066": "État du modèle", + "s1067": "Modèle optimisé", + "s1068": "Modèle déchargé", + "s1069": "Version du modèle", + "s1070": "Versions du modèle", + "s1071": "Poids du modèle", + "s1072": "Modèle {0} Go, contexte {1} Go, exécution {2} Go. {3}", + "s1073": "Modèles", + "s1074": "Modèles ajoutés. Choisissez-en un dans le sélecteur de modèle de la conversation.", + "s1075": "Modèles dans la conversation", + "s1076": "Moniteur", + "s1077": "Surveiller le GPU", + "s1078": "Surveiller le modèle", + "s1079": "Surveiller le processeur", + "s1080": "Capture d’écran du moniteur", + "s1081": "Plus", + "s1082": "Autres actions Time-skip", + "s1083": "Autres actions", + "s1084": "Plus concis", + "s1085": "Plus d’historique de conversation utilise plus de mémoire.", + "s1086": "D’autres paramètres du moteur deviennent disponibles après la préparation de cette version.", + "s1087": "Plus de mains, une seule conversation.", + "s1088": "Autres actions sur le message", + "s1089": "Plus d’espace libre", + "s1090": "Autres actions sur la réponse", + "s1091": "Plus d’emplacements demandent plus de mémoire et peuvent ralentir chaque réponse.", + "s1092": "Plus de texte utilise plus de mémoire.", + "s1093": "Plus — Serveur API et Paramètres", + "s1094": "Animations", + "s1095": "Cet hôte ne prend pas encore en charge plusieurs moteurs natifs ni l’attribution des GPU.", + "s1096": "Les performances de mon IA locale avec Strata", + "s1097": "Mon autre PC", + "s1098": "Mon propre domaine", + "s1099": "Politique NUMA", + "s1100": "Nom", + "s1101": "Nom affiché dans la conversation", + "s1102": "Format KV natif", + "s1103": "JSON de configuration native", + "s1104": "La connexion de contrôle native est fermée.", + "s1105": "Réglages du moteur natif", + "s1106": "Mode peu de RAM natif", + "s1107": "Modèle natif", + "s1108": "Éditeur de réglages natifs", + "s1109": "Modèle des réglages natifs", + "s1110": "Les réglages natifs doivent former un objet.", + "s1111": "{0} natif", + "s1112": "Un test de vitesse est nécessaire", + "s1113": "Les nouvelles requêtes API sont en pause.", + "s1114": "Les nouvelles requêtes API sont en pause. Reprenez-les dans Serveur API.", + "s1115": "Nouvelle conversation", + "s1116": "Nouvelle conversation", + "s1117": "Nouvelle tâche", + "s1118": "Page suivante", + "s1119": "Prochaine exécution", + "s1120": "Étapes suivantes", + "s1121": "Astuce suivante", + "s1122": "Aucune clé API", + "s1123": "Aucun fichier GGUF ici", + "s1124": "Aucun accélérateur GPU trouvé — Strata fonctionnera sur le CPU", + "s1125": "Aucun GPU détecté", + "s1126": "Aucune mesure du GPU pour l’instant", + "s1127": "Aucun PDF à afficher.", + "s1128": "Ni compte ni domaine nécessaires. Idéal pour une connexion rapide.", + "s1129": "Aucun candidat agent approuvé ne convient à cette configuration. Essayez Équilibré ou envisagez un contexte plus court.", + "s1130": "Aucune conversation pour l’instant", + "s1131": "Aucune commande ne correspond à « /", + "s1132": "Aucune mesure de vitesse comparable pour cette configuration.", + "s1133": "Aucun modèle compatible ne tient dans ce contexte et ce budget de mémoire. Envisagez un contexte plus court.", + "s1134": "Aucune conversation sélectionnée", + "s1135": "Aucune tâche supprimée", + "s1136": "Aucun modèle téléchargé", + "s1137": "Aucun message du moteur pour l’instant.", + "s1138": "Aucun contenu de fichier n’a été fourni.", + "s1139": "Aucun port privé libre n’a été trouvé pour le moteur.", + "s1140": "Aucun fichier local n’est disponible.", + "s1141": "Aucun modèle local téléchargé pour l’instant.", + "s1142": "Aucune conversation correspondante", + "s1143": "Aucune conversation correspondante. Essayez une autre recherche.", + "s1144": "Aucune version de llama.cpp correspondante pour cette plateforme", + "s1145": "Aucune requête correspondante", + "s1146": "Aucune compétence correspondante", + "s1147": "Aucune tâche correspondante", + "s1148": "Aucun message pour l’instant", + "s1149": "Aucun microphone disponible. Vérifiez la connexion de votre microphone.", + "s1150": "Aucun modèle n’est chargé.", + "s1151": "Aucun modèle n’est chargé. Choisissez-en un dans Modèles, puis réessayez.", + "s1152": "Aucun modèle chargé", + "s1153": "Aucun modèle chargé — rien à redémarrer", + "s1154": "Aucune version de modèle disponible.", + "s1155": "Aucun modèle sélectionné pour l’instant. Récupérez la liste ou ajoutez un ID de modèle.", + "s1156": "Aucun connecteur officiel à télécharger n’a été trouvé pour cet ordinateur.", + "s1157": "Aucun paramètre ne correspond à vos filtres.", + "s1158": "Aucun paramètre ne correspond.", + "s1159": "Aucune utilisation de requête enregistrée", + "s1160": "Aucun échantillon de vitesse enregistré pour l’instant", + "s1161": "Aucune version publiée", + "s1162": "Aucune utilisation de modèle signalée sur cette période.", + "s1163": "Aucune requête pour l’instant", + "s1164": "Aucune requête pour l’instant", + "s1165": "Aucun résultat pour l’instant.", + "s1166": "Aucune conversation enregistrée à cette position.", + "s1167": "Aucun moteur précédent enregistré n’est disponible.", + "s1168": "Aucune version précédente enregistrée", + "s1169": "Aucune tâche planifiée pour l’instant", + "s1170": "Aucune compétence pour l’instant", + "s1171": "Aucune parole détectée. Essayez de parler plus près du microphone.", + "s1172": "Aucune version stable de Strata n’est encore publiée dans ce flux.", + "s1173": "Aucun sous-agent enregistré", + "s1174": "Aucun GPU pris en charge n’a été signalé par cette installation.", + "s1175": "Aucune longueur de contexte prise en charge.", + "s1176": "Aucune tâche pour l’instant", + "s1177": "Aucun texte n’a été ajouté. Votre brouillon est prêt à être modifié.", + "s1178": "Aucun appel d’outil dans cette conversation.", + "s1179": "Aucun message de l’utilisateur trouvé", + "s1180": "Aucune version disponible.", + "s1181": "Aucune version téléchargée pour l’instant. Choisissez-en une ci-dessus pour commencer.", + "s1182": "Aucun dossier de données accessible en écriture trouvé — définissez STRATA_HOME sur un chemin accessible en écriture", + "s1183": "Indisponible", + "s1184": "Pas disponible pour toutes les requêtes", + "s1185": "Non défini", + "s1186": "Pas encore défini", + "s1187": "Non téléchargé", + "s1188": "Espace disque insuffisant", + "s1189": "Stockage insuffisant", + "s1190": "Non estimé", + "s1191": "Introuvable", + "s1192": "Non installé", + "s1193": "Non conservé", + "s1194": "Non communiqué", + "s1195": "Non évalué pour les tâches d’agent", + "s1196": "Non pris en charge par ce moteur", + "s1197": "Non utilisé par ce moteur", + "s1198": "Pas encore disponible", + "s1199": "Rien ne correspond à « ", + "s1200": "Maintenant", + "s1201": "Désactivé", + "s1202": "Activé", + "s1203": "Dans les temps", + "s1204": "Sur cet ordinateur", + "s1205": "Sur cet ordinateur. Restaurez-le quand vous voulez depuis Modèles.", + "s1206": "Une seule URL d’API · routage par ID de modèle", + "s1207": "Une seule configuration pour toutes les commandes.", + "s1208": "Un seul fichier", + "s1209": "Un modèle à la fois. Le chargement bascule vers le modèle sélectionné.", + "s1210": "Un plan, tout réuni", + "s1211": "Une vérification qui passait auparavant échoue maintenant.", + "s1212": "Un seul pool de mémoire partagé", + "s1213": "Mesure unique · environ 5 à 10 minutes. Votre ordinateur sera occupé.", + "s1214": "Seules les applications dotées de votre clé API Strata peuvent utiliser cette connexion.", + "s1215": "Seuls les dossiers et les fichiers GGUF sont affichés. Les adaptateurs LoRA et les projecteurs d’images demandent une prise en charge distincte.", + "s1216": "Seulement dans {0}", + "s1217": "Seule l’API d’inférence est partagée. Votre ordinateur et Strata doivent rester allumés.", + "s1218": "Opaque", + "s1219": "Ouvrir", + "s1220": "Ouvrez Modèles et déchargez d’abord les modèles natifs en cours d’exécution.", + "s1221": "Ouvrir le moniteur", + "s1222": "Ouvrir les tâches", + "s1223": "Ouvrez une conversation et attendez la fin de la réponse en cours.", + "s1224": "Ouvrez d’abord une conversation qui contient des messages.", + "s1225": "Ouvrir un fichier local dans le panneau d’aperçu", + "s1226": "Ouvrir un site web", + "s1227": "Ouvrir un site web dans le panneau d’aperçu", + "s1228": "Ouvrez un autre dossier ou saisissez plus haut le chemin complet du modèle.", + "s1229": "Ouvrir le dossier", + "s1230": "Ouvrir avec l’application par défaut", + "s1231": "Ouvrir dans le panneau latéral", + "s1232": "Ouvrir la navigation", + "s1233": "Ouvrir l’original", + "s1234": "Ouvrir hors de l’aperçu", + "s1235": "Ouvrir l’aperçu", + "s1236": "Aperçus ouverts", + "s1237": "Ouvrir le résultat", + "s1238": "Ouvrez six types de sorties différents pour que je puisse affiner l’aperçu du design.", + "s1239": "Ouvrez l’application Strata locale pour utiliser les commandes de l’hôte.", + "s1240": "Ouvrez la page de la version pour mettre à jour cette installation", + "s1241": "Ouvrez le nombre de sous-agents ci-dessus pour examiner cette exécution d’exemple. Chaque ligne indique l’état, l’utilisation de tokens et le temps écoulé.", + "s1242": "Ouvrir {0}", + "s1243": "Ouvrir {0} dans le panneau latéral", + "s1244": "OpenAI Chat Completions", + "s1245": "OpenAI Responses", + "s1246": "Composition aérée", + "s1247": "Ouverture de la visionneuse PDF…", + "s1248": "Ouvre une copie locale de cet aperçu.", + "s1249": "Fichiers de modèle Strata optimisés", + "s1250": "Facultatif", + "s1251": "Options pour {0}", + "s1252": "Original", + "s1253": "Couverture Fieldnotes d’origine : Room to begin again, avec des formes botaniques.", + "s1254": "Idée d’origine conservée", + "s1255": "Original restauré", + "s1256": "Original restauré dans cet exemple.", + "s1257": "Original enregistré", + "s1258": "Autres applications", + "s1259": "D’autres modèles chargés ont réservé cette mémoire. Choisissez un autre GPU, réduisez le contexte ou déchargez un modèle.", + "s1260": "Les autres modèles chargés restent disponibles.", + "s1261": "Autres modèles locaux", + "s1262": "Autres modèles locaux…", + "s1263": "Sortie", + "s1264": "Tokens de sortie", + "s1265": "Vue d’ensemble", + "s1266": "PCIe", + "s1267": "Transfert PCIe", + "s1268": "PDF", + "s1269": "Commandes du PDF", + "s1270": "Page {0} du PDF", + "s1271": "Les requêtes parallèles multiplient la mémoire du cache KV — laissez 1 sur une mémoire unifiée.", + "s1272": "Groupe de paramètres", + "s1273": "Paramètres", + "s1274": "En réserve", + "s1275": "En réserve / restaurées", + "s1276": "Conversations en réserve", + "s1277": "Les conversations en réserve reprennent depuis leur état enregistré. La plus ancienne est retirée quand le cache est plein.", + "s1278": "Le placement partiel des couches sur le GPU nécessite un plan d’allocation vérifié. Choisissez Automatique, Toutes les couches ou CPU uniquement.", + "s1279": "Déchargement partiel : la répartition entre le GPU et la mémoire système n’est pas estimée.", + "s1280": "Collez uniquement le token qui suit --token", + "s1281": "Collez le token du tunnel fourni par Cloudflare, pas la commande d’installation complète.", + "s1282": "Mettre l’animation en pause", + "s1283": "En pause", + "s1284": "Heure de pointe", + "s1285": "Fenêtre de pénalité", + "s1286": "En attente", + "s1287": "Performances", + "s1288": "Choisir une planification", + "s1289": "Les images sont ouvertes dans l’aperçu. Choisissez un modèle local avec Lire les images activé pour les envoyer.", + "s1290": "Les images doivent être des fichiers PNG, JPEG ou WebP joints.", + "s1291": "Épingler", + "s1292": "Épinglé", + "s1293": "Plan", + "s1294": "Lancer l’animation", + "s1295": "Portfolio prêt à publier", + "s1296": "Portugais", + "s1297": "Puissance", + "s1298": "Traitement du prompt", + "s1299": "Traitement du prompt de la dernière requête", + "s1300": "Traiter le prompt maintenant", + "s1301": "Traiter le prompt de cette requête", + "s1302": "Préparer", + "s1303": "Préparez d’abord un modèle. Son installateur télécharge le moteur correspondant.", + "s1304": "Préparez un modèle dans Modèles pour configurer les paramètres de son moteur et ses outils MCP.", + "s1305": "Préparez d’abord l’environnement Python.", + "s1306": "Préparez le modèle avant d’optimiser.", + "s1307": "Préparez ce modèle avant de calibrer.", + "s1308": "Préparez les fichiers de vision de ce modèle avant d’activer la lecture d’images.", + "s1309": "Préparation des fichiers…", + "s1310": "Préparation de la capture d’écran…", + "s1311": "Préparation de votre connecteur", + "s1312": "Préparation de votre modèle", + "s1313": "Préparation de votre modèle…", + "s1314": "Préparation de votre capture d’écran…", + "s1315": "Préparation…", + "s1316": "Pénalité de présence", + "s1317": "Conservé avant toute révision.", + "s1318": "Appuyez sur les touches…", + "s1319": "Aperçu", + "s1320": "Version d’aperçu", + "s1321": "Actions sur le fichier d’aperçu", + "s1322": "Aperçu des statistiques des sous-agents", + "s1323": "Test d’aperçu · Exemple", + "s1324": "Largeur de l’aperçu : {0} pixels", + "s1325": "Moteur précédent disponible", + "s1326": "Page précédente", + "s1327": "Confidentialité", + "s1328": "La confidentialité d’abord", + "s1329": "Informations sur le processeur indisponibles", + "s1330": "Programme", + "s1331": "La progression s’affiche dans Modèles.", + "s1332": "Prompt", + "s1333": "Lot de prompts", + "s1334": "Lot de prompts ·", + "s1335": "Le contenu du prompt et la position passée dans la file ne sont pas conservés. Cette vue se met à jour pendant l’exécution de la requête.", + "s1336": "Lecture du prompt", + "s1337": "Protégez votre connexion", + "s1338": "Fournisseur", + "s1339": "Valeur par défaut du fournisseur", + "s1340": "Nom du fournisseur", + "s1341": "Quantification", + "s1342": "Longueur de la file", + "s1343": "En file d’attente", + "s1344": "Qwen · IQ2_M", + "s1345": "Qwen · IQ3_XXS", + "s1346": "Qwen · Q2_K", + "s1347": "RAM", + "s1348": "Marge de RAM", + "s1349": "Configuration brute", + "s1350": "Lecture", + "s1351": "Lire les experts depuis le disque", + "s1352": "Lire les images", + "s1353": "Lire les images quand ce modèle se charge", + "s1354": "Lire le prompt", + "s1355": "Lire un prompt d’exemple", + "s1356": "Débit de lecture", + "s1357": "Lecture", + "s1358": "Lecture et concentration", + "s1359": "Vitesses de lecture et de réponse. {0}.", + "s1360": "Lecture des fichiers…", + "s1361": "Lecture de la mémoire…", + "s1362": "Lecture du dossier des modèles…", + "s1363": "Lecture du prompt", + "s1364": "Lecture des réglages enregistrés…", + "s1365": "Taille de lecture", + "s1366": "Taille du texte de lecture", + "s1367": "Lecture en tok/s", + "s1368": "Lectures", + "s1369": "Prêt", + "s1370": "Prêt pour une requête.", + "s1371": "Prêt pour les requêtes.", + "s1372": "Prêt à se connecter", + "s1373": "Prêt à écouter", + "s1374": "Prêt pour l’aperçu", + "s1375": "Prêt à être restauré depuis les Réglages enregistrés.", + "s1376": "Prêt pour la revue", + "s1377": "Effort de raisonnement", + "s1378": "Niveau d’effort de raisonnement", + "s1379": "Effort de raisonnement : {0}", + "s1380": "Le raisonnement utilise les valeurs par défaut du fournisseur d’API.", + "s1381": "Conversations récentes", + "s1382": "Requêtes récentes", + "s1383": "Recommandé", + "s1384": "Valeurs par défaut recommandées", + "s1385": "Recommandé :", + "s1386": "Reconnecter le fichier", + "s1387": "Reconnecter le fichier local", + "s1388": "Durée enregistrée", + "s1389": "Tokens enregistrés en entrée / sortie", + "s1390": "Réduisez le contexte ou choisissez une version plus petite pour que ce modèle tienne.", + "s1391": "Réduit", + "s1392": "Réduire les animations désactive aussi le défilement fluide.", + "s1393": "Faites le point sur l’avancement et planifiez la semaine prochaine.", + "s1394": "Actualiser les compétences", + "s1395": "Révision de la couverture Fieldnotes rejetée : la mise en page raccourcie supprime le sous-titre utile.", + "s1396": "Recharger l’aperçu", + "s1397": "Recharger l’enregistré", + "s1398": "Recharge le modèle en mémoire", + "s1399": "Retirer", + "s1400": "Retirer la clé API ?", + "s1401": "Retirer le serveur MCP {0}", + "s1402": "Supprimer la connexion", + "s1403": "Échec du retrait", + "s1404": "Retirer de Strata ?", + "s1405": "Retirer de Strata…", + "s1406": "Retirer de la barre latérale", + "s1407": "Retirer la clé", + "s1408": "Retirer le modèle", + "s1409": "Retirer la clé API enregistrée", + "s1410": "Retire ce modèle de Strata. Vos fichiers GGUF d’origine restent dans leur dossier.", + "s1411": "Retirer l’espace de travail de la barre latérale ?", + "s1412": "Retirer {0}", + "s1413": "Supprime {0} Go de fichiers téléchargés. Vous pourrez télécharger à nouveau cette version.", + "s1414": "Retirer {0} du sélecteur de conversation", + "s1415": "Retirer {0} de la barre latérale", + "s1416": "Supprime {0} de fichiers téléchargés. Vous pourrez télécharger à nouveau cette version.", + "s1417": "Retirer {0} ?", + "s1418": "Retrait…", + "s1419": "Renommer", + "s1420": "Renommer la conversation", + "s1421": "Affichage de la page…", + "s1422": "Répéter", + "s1423": "Répéter automatiquement", + "s1424": "Pénalité de répétition", + "s1425": "Répéter la tâche", + "s1426": "Se répète chaque jour de la semaine", + "s1427": "Pénalité de répétition", + "s1428": "Remplacer ce brouillon par les réglages enregistrés en dernier dans le moteur.", + "s1429": "Rejouer", + "s1430": "Rejouer l’exemple", + "s1431": "Revoir cette astuce", + "s1432": "Signalé par le modèle", + "s1433": "Utilisation de tokens signalée par modèle au fil du temps. {0} tokens.", + "s1434": "Requête", + "s1435": "Corps de la requête trop volumineux", + "s1436": "Détails de la requête", + "s1437": "Échec de la requête ({0} {1})", + "s1438": "La taille de la requête est l’entrée plus la sortie à la fin. Ce n’est pas une lecture en direct du cache du modèle. Les anciens messages peuvent n’avoir aucune utilisation enregistrée.", + "s1439": "Filtre d’état des requêtes", + "s1440": "État de la requête indisponible. Reconnectez-vous avant de changer le modèle chargé.", + "s1441": "Délai d’attente de la requête", + "s1442": "Requêtes", + "s1443": "Les requêtes apparaissent ici quand un client ou la conversation Strata utilise l’API.", + "s1444": "Les requêtes, le contexte et la vitesse concernent ce modèle. Les mesures du GPU incluent tout le travail des périphériques sélectionnés.", + "s1445": "Requis ·", + "s1446": "Nécessite une installation de Strata plus récente.", + "s1447": "Recherche", + "s1448": "Réinitialiser", + "s1449": "Rétablir les valeurs par défaut", + "s1450": "La réinitialisation a perdu son état", + "s1451": "La réinitialisation est à revoir", + "s1452": "Revenir aux réglages recommandés", + "s1453": "La réinitialisation fonctionne", + "s1454": "Remettre {0} sur la valeur recommandée", + "s1455": "Redimensionner le panneau d’aperçu", + "s1456": "Aperçu de la préférence de ressources", + "s1457": "Ressources", + "s1458": "Réglages des réponses", + "s1459": "Sections des réglages des réponses", + "s1460": "Responses", + "s1461": "Responses nécessite un modèle natif en cours d’exécution et une version de Strata qui prend en charge cette API. Si besoin, mettez à jour l’installation native dans Paramètres → À propos.", + "s1462": "Les réponses sont des exemples simulés, pas celles d’un vrai modèle.", + "s1463": "Redémarrer le moteur", + "s1464": "Échec du redémarrage", + "s1465": "Le redémarrage n’est pas disponible avec le moteur d’exemple. Enregistrez les réglages pour le prochain chargement.", + "s1466": "Redémarrage indisponible avec le moteur d’exemple", + "s1467": "Restaurer", + "s1468": "Rétablir les valeurs par défaut", + "s1469": "Restaurer le résultat d’origine", + "s1470": "Restaurer le moteur précédent", + "s1471": "Restaurer l’enregistré", + "s1472": "Restaurer les réglages enregistrés", + "s1473": "Restaurer les réglages enregistrés ?", + "s1474": "Restaurer les réglages", + "s1475": "Restaurez d’abord cette tâche.", + "s1476": "Restauré", + "s1477": "Comparaison des résultats", + "s1478": "Résultat prêt · comparez les versions", + "s1479": "Version du résultat", + "s1480": "Reprendre le téléchargement", + "s1481": "Réessayer", + "s1482": "Réessayer le téléchargement", + "s1483": "Réessayer le chargement", + "s1484": "Réessayer l’installation", + "s1485": "Nouvelle tentative…", + "s1486": "Réutilisation non communiquée", + "s1487": "Réutilisé", + "s1488": "Réutilisé depuis le démarrage", + "s1489": "Rétablir", + "s1490": "Relire", + "s1491": "Revoir les réglages recommandés", + "s1492": "Revoir les résultats", + "s1493": "Revoyez les réglages en surbrillance avant de charger.", + "s1494": "Relisez les instructions, puis choisissez une planification.", + "s1495": "Examen des paramètres pris en charge", + "s1496": "Relit un fichier ou un diff : d’abord l’exactitude, puis le style, et signale ses constats avec les numéros de ligne.", + "s1497": "Révision du brouillon enregistré. Suivez le résultat dans la barre latérale. Cet exemple utilise des sorties factices et des vérifications simulées.", + "s1498": "Révision · suivre la progression", + "s1499": "Révision…", + "s1500": "Révision", + "s1501": "Révision rejetée · le meilleur point de départ est conservé.", + "s1502": "Revenir ici", + "s1503": "Ici même, sur votre ordinateur", + "s1504": "Base RoPE", + "s1505": "Mise à l’échelle RoPE", + "s1506": "Revenir à une version antérieure", + "s1507": "Revenir en arrière…", + "s1508": "Le retour en arrière nécessite un moteur précédent enregistré par une version de Strata qui le prend en charge.", + "s1509": "De la place pour les autres applications", + "s1510": "De la place pour votre travail au quotidien", + "s1511": "Place restante inconnue", + "s1512": "Lancez un prompt selon un horaire, ou quand vous en avez besoin.", + "s1513": "JSON de configuration d’exécution", + "s1514": "Lancer le modèle", + "s1515": "Exécuter plusieurs modèles", + "s1516": "Lancer maintenant", + "s1517": "Exécuter sur", + "s1518": "Exécuter selon un horaire", + "s1519": "Impossible de charger les profils d’exécution.", + "s1520": "Réglages d’exécution", + "s1521": "Lancer l’installation", + "s1522": "Lancer le test court", + "s1523": "Lancer le test de vitesse", + "s1524": "Lancez cette tâche pour voir ici son premier résultat.", + "s1525": "Lancer {0} maintenant", + "s1526": "En cours", + "s1527": "En cours…", + "s1528": "Exécute une commande", + "s1529": "S’exécute tant que l’hôte de Strata est ouvert. Exécute les instructions enregistrées avec le modèle chargé.", + "s1530": "Exécution", + "s1531": "Russe", + "s1532": "SSD", + "s1533": "Informations sur le débordement sur SSD", + "s1534": "Débordement sur SSD probable", + "s1535": "Débordement sur SSD probable. Une partie de ce modèle peut être lue depuis le stockage, les réponses peuvent donc être plus lentes.", + "s1536": "Débordement sur SSD · réponses plus lentes", + "s1537": "Mêmes vérifications, deux versions", + "s1538": "Même pool de mémoire que la RAM système", + "s1539": "L’exemple dépasse le contexte, 256 tokens de sortie compris. Choisissez un texte plus court ou augmentez le contexte.", + "s1540": "Image d’exemple · 1200 × 900", + "s1541": "Charge de travail d’exemple", + "s1542": "Échantillonnage", + "s1543": "L’échantillonnage doit être un objet.", + "s1544": "Enregistrer", + "s1545": "Enregistrer la capture d’écran du moniteur", + "s1546": "Enregistrez une configuration pour la réutiliser.", + "s1547": "Enregistrer et redémarrer", + "s1548": "Enregistrer sous un nouveau nom…", + "s1549": "Enregistrer les modifications", + "s1550": "Enregistrer les réglages actuels…", + "s1551": "Enregistrer les journaux", + "s1552": "Enregistrer le nom", + "s1553": "Enregistrer le rapport", + "s1554": "Enregistrer les réglages", + "s1555": "Enregistrer les réglages pour le prochain chargement.", + "s1556": "Enregistrer le brouillon et redémarrer", + "s1557": "Enregistrer l’original", + "s1558": "Enregistrer dans", + "s1559": "Brouillon enregistré", + "s1560": "Enregistré sur l’hôte Strata, jamais dans le stockage du navigateur.", + "s1561": "Impossible de lire les profils d’exécution enregistrés.", + "s1562": "Enregistré en lieu sûr", + "s1563": "Réglages enregistrés", + "s1564": "Réglages enregistrés{0}{1}", + "s1565": "Enregistré. Rechargez le modèle pour appliquer ces réglages. Une sauvegarde de la configuration précédente a été conservée.", + "s1566": "Enregistrement de l’original…", + "s1567": "Enregistrement du premier brouillon avant d’explorer une autre direction.", + "s1568": "Enregistrement…", + "s1569": "Dites bonjour, ou lancez-vous directement.", + "s1570": "Agrandir la navigation et les commandes.", + "s1571": "Planifier votre tâche", + "s1572": "Planifier {0}", + "s1573": "Tâches planifiées", + "s1574": "Planifiée · calcul de la prochaine exécution", + "s1575": "Impossible de préparer la capture d’écran.", + "s1576": "Impossible d’enregistrer la capture d’écran.", + "s1577": "Impossible de charger les icônes de la capture d’écran. Réessayez.", + "s1578": "Faire défiler les onglets d’aperçu vers la gauche", + "s1579": "Faire défiler les onglets d’aperçu vers la droite", + "s1580": "Rechercher dans toutes les conversations", + "s1581": "Rechercher dans les conversations", + "s1582": "Rechercher des conversations, des écrans ou des actions…", + "s1583": "Rechercher des conversations…", + "s1584": "Rechercher des commandes", + "s1585": "Rechercher des paramètres du moteur", + "s1586": "Rechercher un nom ou une clé technique…", + "s1587": "Rechercher des paramètres natifs", + "s1588": "Rechercher des paramètres", + "s1589": "Rechercher des paramètres…", + "s1590": "Rechercher des requêtes", + "s1591": "Rechercher des compétences", + "s1592": "Rechercher des compétences…", + "s1593": "Rechercher des tâches", + "s1594": "Rechercher des tâches…", + "s1595": "Graine", + "s1596": "Sélectionnez un fichier de modèle .gguf. Les dossiers, adaptateurs et projecteurs ne peuvent pas être chargés comme modèle de conversation.", + "s1597": "Sélectionnez un modèle pour voir son contexte et sa vitesse. Les mesures du GPU et de la RAM système sont des mesures partagées de l’hôte.", + "s1598": "Sélectionnez un modèle pour voir le contexte", + "s1599": "Sélectionnez le modèle à lancer.", + "s1600": "Sélectionnez le fichier .gguf du modèle, et non son dossier.", + "s1601": "Sélectionnez la valeur et copiez-la manuellement.", + "s1602": "Sélectionnez cette version pour voir le contexte, la mémoire et les performances.", + "s1603": "Sélectionné", + "s1604": "Sélectionné automatiquement pour ce modèle sur cet ordinateur.", + "s1605": "Envoyer", + "s1606": "Envoyer le message", + "s1607": "Séparez les expressions par des virgules.", + "s1608": "URL du serveur", + "s1609": "Accès au serveur", + "s1610": "L’accès au serveur se gère dans Serveur API", + "s1611": "Serveur API", + "s1612": "Filtre du modèle servi", + "s1613": "Statistiques de la session", + "s1614": "Sessions", + "s1615": "Définir", + "s1616": "Définissez une clé API avant de partager avec d’autres appareils.", + "s1617": "Définissez son URL de base sur", + "s1618": "Définir la clé", + "s1619": "Définissez les combinaisons de touches qui vous conviennent.", + "s1620": "Fixez le résultat voulu", + "s1621": "Configurer Strata", + "s1622": "Configurer une tâche récurrente", + "s1623": "Configurer manuellement", + "s1624": "Configurer votre domaine", + "s1625": "Configuration…", + "s1626": "Paramètres", + "s1627": "Les réglages sont prêts. Chargez le modèle quand vous voulez.", + "s1628": "Réglages de ce modèle. Les valeurs vides utilisent les valeurs par défaut de Strata.", + "s1629": "Nom des réglages", + "s1630": "Réglages enregistrés", + "s1631": "Sections des paramètres", + "s1632": "Contexte de conversation de l’installation", + "s1633": "Objectif de l’installation", + "s1634": "Modèle de l’installation", + "s1635": "Installation requise", + "s1636": "Progression de l’installation", + "s1637": "Partager", + "s1638": "Partager sur Reddit", + "s1639": "Partager sur X", + "s1640": "Partagé", + "s1641": "Mémoire GPU partagée", + "s1642": "RAM partagée après le chargement", + "s1643": "RAM partagée réservée", + "s1644": "Mémoire partagée · pas de liaison PCIe", + "s1645": "Partagé sur le réseau local", + "s1646": "Mémoire système partagée", + "s1647": "Mémoire unifiée partagée", + "s1648": "Partagé avec la RAM", + "s1649": "Le partage télécharge l’image et ouvre un brouillon. Joignez l’image à votre publication.", + "s1650": "Le partage est déjà en cours de démarrage.", + "s1651": "Maj + Entrée ajoute une ligne. Tapez / pour les commandes de conversation. Échap ferme les panneaux.", + "s1652": "Texte court", + "s1653": "Raccourcir le titre et aérer la composition en gardant le style botanique.", + "s1654": "Raccourci encore", + "s1655": "Titre raccourci", + "s1656": "Raccourcit la limite de sortie demandée quand le prompt laisse moins de place.", + "s1657": "Plus court et plus clair", + "s1658": "Plus court n’est pas toujours mieux.", + "s1659": "Afficher", + "s1660": "Afficher la clé API", + "s1661": "Tout afficher ({0})", + "s1662": "Afficher les descriptions", + "s1663": "Afficher moins", + "s1664": "Afficher dans l’explorateur de fichiers", + "s1665": "Afficher moins", + "s1666": "Afficher ou masquer la barre latérale", + "s1667": "Afficher la barre latérale", + "s1668": "Afficher les éléments non pris en charge", + "s1669": "Afficher {0} de plus", + "s1670": "Affichage des 1 000 premiers éléments. Saisissez un chemin pour ouvrir un fichier précis.", + "s1671": "Affichage des 1 000 premières lignes correspondantes.", + "s1672": "Vérifications de comparaison simulées", + "s1673": "Depuis", + "s1674": "Taille", + "s1675": "Sections de l’éditeur de compétences", + "s1676": "Compétence activée", + "s1677": "Portée de la compétence dans l’espace de travail", + "s1678": "Compétences", + "s1679": "Ignorer les demandes d’autorisation", + "s1680": "Commandes slash", + "s1681": "Plus lent · mémoire système", + "s1682": "Petits écrans", + "s1683": "Logiciel", + "s1684": "Logiciel à gérer", + "s1685": "Certains fichiers n’ont pas pu être lus. Essayez de les ajouter séparément.", + "s1686": "Des fichiers du modèle sont manquants. Utilisez Télécharger / réparer pour les restaurer.", + "s1687": "Quelque chose demande votre attention.", + "s1688": "Trier les tâches", + "s1689": "Source", + "s1690": "Espace", + "s1691": "Espace disponible", + "s1692": "Espace restant", + "s1693": "Espacement", + "s1694": "Espagnol", + "s1695": "Parler à nouveau", + "s1696": "Dicter dans la zone de message sans envoyer", + "s1697": "Parlez naturellement. Une pause de 3,5 secondes termine la dictée. Le texte apparaît dans votre zone de message sans être envoyé.", + "s1698": "Précis et ordonné", + "s1699": "La reconnaissance vocale n’est pas disponible dans ce navigateur. Essayez un navigateur compatible avec la dictée.", + "s1700": "La reconnaissance vocale n’est pas disponible dans ce navigateur. Utilisez la dictée intégrée à votre ordinateur.", + "s1701": "Dictée vocale", + "s1702": "Dictée vocale · {0}", + "s1703": "Vitesse", + "s1704": "Historique de vitesse", + "s1705": "Projection de vitesse", + "s1706": "La projection de vitesse doit être activée ou désactivée.", + "s1707": "Aperçu du test de vitesse", + "s1708": "Les vitesses proviennent de chaque instance du moteur. Les mesures manquantes affichent —.", + "s1709": "Les noms de fichiers GGUF fractionnés doivent contenir 00001-of-000NN et correspondre à leurs métadonnées.", + "s1710": "Répartir sur les GPU…", + "s1711": "Standard / système", + "s1712": "Démarrez une nouvelle conversation quand vous voulez.", + "s1713": "Recommencer", + "s1714": "Commencer à répondre", + "s1715": "Lancer la calibration", + "s1716": "Commencer à discuter", + "s1717": "Lancer l’aperçu", + "s1718": "Lancez-le avec `npm run host` puis rechargez la page.", + "s1719": "Démarrer ou arrêter la dictée", + "s1720": "Démarrer le partage", + "s1721": "Démarrez le connecteur pour le domaine que vous avez configuré.", + "s1722": "Partez d’une idée ci-dessous, ou créez la vôtre.", + "s1723": "Démarrer votre première conversation", + "s1724": "Démarrage · 0.5B Q4_K_M", + "s1725": "Démarrage du microphone…", + "s1726": "Démarrage…", + "s1727": "État", + "s1728": "À la pointe. Chez vous.", + "s1729": "Statut", + "s1730": "Statut indisponible", + "s1731": "Statut :", + "s1732": "Étape", + "s1733": "Tient toujours", + "s1734": "Arrêter", + "s1735": "Arrêter le test", + "s1736": "Arrêtez le partage local et Cloudflare avant de retirer la clé API.", + "s1737": "Arrêter le partage", + "s1738": "Arrêtez le test avant de décharger ce modèle.", + "s1739": "Arrêtez l’exécution en cours avant de modifier.", + "s1740": "Arrêtez le tunnel en cours avant d’en démarrer un autre.", + "s1741": "Arrêtez le serveur natif qui tourne hors de cette interface avant d’optimiser.", + "s1742": "Arrêtez le serveur natif qui tourne hors de cette interface avant de modifier les fichiers du moteur.", + "s1743": "Arrêtez le serveur natif qui tourne hors de cette interface avant de préparer les fichiers.", + "s1744": "Arrêtez cette tâche avant de la supprimer", + "s1745": "Arrêter l’optimisation", + "s1746": "Arrêter le tunnel", + "s1747": "Arrêter {0}", + "s1748": "Arrêté", + "s1749": "Arrêt du tunnel…", + "s1750": "Arrêt…", + "s1751": "Stockage", + "s1752": "Réglages du stockage", + "s1753": "Strata", + "s1754": "Strata peut maintenant lire les fichiers de {0}.", + "s1755": "Le contrôle de Strata s’est arrêté. Python 3.10 ou plus récent est requis.", + "s1756": "Strata n’a pas pu afficher cet écran", + "s1757": "Strata télécharge et configure le connecteur Cloudflare pour vous.", + "s1758": "Dossier Strata", + "s1759": "Police de Strata", + "s1760": "Dossier d’installation de Strata", + "s1761": "Strata n’est pas connecté à son moteur.", + "s1762": "Modèles optimisés par Strata", + "s1763": "Strata prépare tous les fragments, la couche de brouillon et les fichiers partagés. Les téléchargements terminés sont réutilisés.", + "s1764": "Strata n’envoie aucune télémétrie d’utilisation. Les conversations restent dans le stockage du navigateur. Quand vous choisissez un modèle API, cette conversation et les instructions des compétences activées sont envoyées à son fournisseur. Le journal des requêtes de l’interface garde en mémoire le client, les durées et les métadonnées de tokens. La surveillance de l’API native peut conserver le contenu des requêtes en mémoire lorsqu’elle est activée. Les outils connectés accèdent aux ressources que vous configurez.", + "s1765": "Strata utilise ces fichiers sur place. Vous pourrez charger le modèle après l’avoir ajouté.", + "s1766": "Strata — ouvrir la conversation", + "s1767": "Budget de Strata", + "s1768": "Échec du flux ({0})", + "s1769": "Version la plus solide conservée", + "s1770": "Structure en place", + "s1771": "Structure conservée", + "s1772": "Aperçu des sous-agents", + "s1773": "Sous-agents", + "s1774": "Les sous-agents lancés dans cette conversation apparaissent ici, avec leur progression, leur utilisation de tokens et leur durée. Les exécutions terminées restent visibles.", + "s1775": "Sous-agents — afficher la vue d’ensemble", + "s1776": "Vérification de réussite", + "s1777": "Suggérer une tâche", + "s1778": "Pris en charge", + "s1779": "Pris en charge, lecture du prompt plus lente", + "s1780": "Swift 1.5", + "s1781": "Basculer toutes les conversations sur {0} ({1}). Le chargement peut prendre quelques instants.", + "s1782": "Passer à", + "s1783": "Passez à un modèle local avec Lire les images activé, ou retirez les pièces jointes.", + "s1784": "Passer en mode sombre", + "s1785": "Passer au thème sombre", + "s1786": "Passer en mode clair", + "s1787": "Passer au thème clair", + "s1788": "Passer à {0} ?", + "s1789": "Changer de version", + "s1790": "Changer de version ?", + "s1791": "Système", + "s1792": "RAM système", + "s1793": "Budget système de {0} Go compté à part ; l’utilisation supplémentaire de l’hôte n’est pas estimée.", + "s1794": "Mémoire système", + "s1795": "Le budget de mémoire système réserve de la place pour le système d’exploitation.", + "s1796": "Jetez un œil pendant que nous préparons tout.", + "s1797": "On retient la direction la plus solide.", + "s1798": "Tâche supprimée", + "s1799": "Idées de tâches", + "s1800": "Tâche introuvable.", + "s1801": "Résultat de la tâche", + "s1802": "Étapes de configuration de la tâche", + "s1803": "Tâches", + "s1804": "Apprenez-moi une notion utile de statistiques. Ajoutez un exemple simple et une question pour vérifier ma compréhension.", + "s1805": "Température", + "s1806": "Adresse temporaire · désactivez le streaming dans votre client.", + "s1807": "Répartition des tenseurs", + "s1808": "Le texte est dans votre zone de message. Relisez-le avant de l’envoyer.", + "s1809": "Ce fichier n’existe plus.", + "s1810": "Ce fichier est en dehors de l’espace de travail.", + "s1811": "Ce dossier n’existe pas.", + "s1812": "Ce dossier ne contient pas de SKILL.md, le modèle n’a donc rien à lire. Un dossier de compétence contient un fichier SKILL.md avec ses instructions.", + "s1813": "Ce dossier est déjà dans vos espaces de travail.", + "s1814": "Cet ID de modèle n’est pas chargé. Choisissez-en un dans /v1/models.", + "s1815": "Ce nom de serveur est déjà utilisé.", + "s1816": "C’est un fichier, pas un dossier.", + "s1817": "C’est un dossier, pas un fichier.", + "s1818": "Le fichier GGUF est incomplet. Téléchargez tous ses poids avant de l’ajouter.", + "s1819": "L’en-tête GGUF est tronqué ou dépasse la taille de métadonnées prise en charge.", + "s1820": "L’environnement Python de Strata est introuvable. Utilisez d’abord Télécharger / réparer.", + "s1821": "Le service vocal du navigateur n’a pas pu se connecter. Vérifiez votre connexion ou essayez un autre navigateur.", + "s1822": "Le candidat ajoute du détail sans perdre l’idée d’origine.", + "s1823": "L’ordinateur sera occupé pendant environ 5 à 15 minutes. Déchargez d’abord les modèles.", + "s1824": "Le connecteur n’a pas pu être téléchargé. Vérifiez votre connexion et réessayez.", + "s1825": "Le connecteur n’a pas pu être préparé automatiquement.", + "s1826": "Le connecteur n’a pas pu être préparé automatiquement. Relancez la configuration du connecteur.", + "s1827": "Le téléchargement du connecteur n’a pas pu être vérifié. Relancez la configuration automatique.", + "s1828": "Le téléchargement du connecteur est anormalement volumineux.", + "s1829": "Le paquet du connecteur contenait un exécutable non valide.", + "s1830": "Le paquet du connecteur ne contenait pas l’exécutable attendu.", + "s1831": "Le cache de contexte et l’exécution doivent tenir dans la RAM ou la mémoire du GPU.", + "s1832": "Le modèle actuellement chargé peut différer de celui qui a répondu aux messages précédents.", + "s1833": "Le dossier de modèles par défaut est en conflit avec une autre bibliothèque. Choisissez un autre dossier.", + "s1834": "Le modèle d’image téléchargé n’a pas passé la vérification. Relancez le téléchargement.", + "s1835": "Le moteur ne s’est pas relancé.", + "s1836": "Le moteur ne tourne pas. Chargez un modèle avant d’appliquer les réglages.", + "s1837": "Le moteur a renvoyé une liste de modèles incomplète. Relancez l’opération.", + "s1838": "Le moteur indique toujours cette instance du modèle comme chargée.", + "s1839": "La mémoire estimée nécessaire dépasse celle de cet ordinateur.", + "s1840": "Le premier fragment est manquant ou non valide. Gardez tous les fragments du modèle dans le même dossier.", + "s1841": "Le premier espace de travail ne peut pas être retiré.", + "s1842": "Le parcours est prêt. Les vitesses restent non mesurées tant qu’aucun adaptateur de test local n’est connecté.", + "s1843": "L’hôte est en cours d’arrêt.", + "s1844": "Le fichier du modèle d’image est plus gros que prévu.", + "s1845": "La révision suivante supprime le sous-titre utile. Gardez la couverture complète.", + "s1846": "Le modèle chargé sera déchargé.", + "s1847": "La configuration du modèle est en dehors de l’installation de Strata.", + "s1848": "Le modèle n’a pas pu être chargé.", + "s1849": "Le modèle n’a pas fini de se charger.", + "s1850": "Le modèle ne s’est pas chargé.", + "s1851": "Le modèle n’a pas renvoyé de brouillon utilisable. Réessayez ou configurez manuellement.", + "s1852": "Les fichiers du modèle n’ont pas été supprimés.", + "s1853": "Le modèle n’a renvoyé aucune réponse.", + "s1854": "Les fragments du modèle ne forment pas un ensemble cohérent. Retéléchargez le fragment manquant ou différent.", + "s1855": "Le modèle sera retiré de Strata.", + "s1856": "Le modèle sera déchargé puis retiré de Strata.", + "s1857": "Le moteur natif n’a pas répondu à temps. Consultez les journaux du moteur.", + "s1858": "L’installation native doit utiliser le dépôt officiel de Strata pour se mettre à jour ici.", + "s1859": "L’installateur natif peut restaurer son moteur précédent. Les fichiers des modèles restent en place.", + "s1860": "L’installateur natif met à jour l’installation. Les fichiers des modèles et les réglages sont conservés. Déchargez les modèles natifs avant la mise à jour.", + "s1861": "La nouvelle révision est concise, mais perd un détail utile.", + "s1862": "L’opération n’a pas pu se terminer. Vérifiez la connexion au moteur et réessayez.", + "s1863": "Les fichiers GGUF d’origine sont conservés.", + "s1864": "L’original reste toujours disponible.", + "s1865": "L’original est enregistré. Le nouveau résultat apparaîtra ici quand il sera prêt à être comparé.", + "s1866": "L’original reste disponible.", + "s1867": "Le vrai moteur d’inférence est indisponible. Chargez un modèle et réessayez.", + "s1868": "Le service de versions a renvoyé une réponse non valide.", + "s1869": "Le résultat est prêt. Passez de l’original à la version mise à jour, ou comparez-les côte à côte. Cet exemple utilise des sorties factices et des vérifications simulées.", + "s1870": "Le modèle en cours d’exécution sera déchargé et ses fichiers supprimés.", + "s1871": "L’exemple ou le contexte n’est pas pris en charge par cette configuration.", + "s1872": "La boîte de dialogue d’enregistrement n’a pas pu s’ouvrir. Essayez d’enregistrer à nouveau la capture d’écran.", + "s1873": "La mise à jour enregistrée reste disponible.", + "s1874": "Le modèle sélectionné", + "s1875": "La révision plus courte casse la réinitialisation. Gardez les commandes fonctionnelles de B.", + "s1876": "La révision plus courte supprime une étape utile. Gardez la version complète de B.", + "s1877": "La version la plus solide est conservée.", + "s1878": "Le token sert uniquement à cette connexion et n’est pas enregistré.", + "s1879": "Le tunnel est en cours de mise à jour. Réessayez dans un instant.", + "s1880": "Le service de mise à jour a renvoyé un résultat incomplet.", + "s1881": "Le résultat mis à jour est prêt. Passez de l’original à la version mise à jour, ou comparez-les côte à côte. Cet exemple utilise des sorties factices et des vérifications simulées.", + "s1882": "Le résultat mis à jour reste disponible.", + "s1883": "La version n’a pas pu se charger. Réessayez quand le moteur sera prêt.", + "s1884": "Leur mémoire (RAM)", + "s1885": "Il n’y a pas assez de stockage libre pour ce modèle d’image.", + "s1886": "Il n’y a pas assez d’espace libre pour télécharger ce modèle.", + "s1887": "Ces fragments déclarent des architectures différentes.", + "s1888": "Réflexion", + "s1889": "Réflexion et rédaction", + "s1890": "Budget de tokens de réflexion", + "s1891": "Cette API n’a renvoyé aucun modèle. Ajoutez un ID de modèle ci-dessous.", + "s1892": "Ce GGUF n’inclut pas son tokenizer. Choisissez le modèle complet, pas un projecteur ni un adaptateur.", + "s1893": "Ce format de tenseur GGUF n’est pas encore pris en charge par l’importateur.", + "s1894": "Cette version de GGUF ou cet ordre des octets n’est pas pris en charge.", + "s1895": "Cette copie de Strata contient des modifications locales. Enregistrez-les ou validez-les avant de mettre à jour.", + "s1896": "Cette action est indisponible.", + "s1897": "Cet adaptateur ne peut pas appliquer les réglages de lot de prompts.", + "s1898": "Cet alias correspond à plusieurs instances. Choisissez l’ID exact du modèle.", + "s1899": "Ce navigateur n’offre pas de reconnaissance vocale. Utilisez la dictée intégrée à votre ordinateur dans la zone de message.", + "s1900": "Cette conversation sera supprimée définitivement.", + "s1901": "Cet ordinateur", + "s1902": "Cette configuration a besoin de plus de mémoire résidente. Revoyez le mappage mémoire ou choisissez une version plus petite.", + "s1903": "Cette conversation", + "s1904": "Ce moteur ne peut pas encore exécuter de modèles d’images. Choisissez Désactivé pour lancer le modèle de conversation.", + "s1905": "Ce fichier ne peut pas être ouvert.", + "s1906": "Ce fichier n’est pas un aperçu local.", + "s1907": "Ce fichier ou ce dossier est indisponible. Vérifiez son emplacement et ses autorisations.", + "s1908": "Ce type de fichier ne peut pas être ouvert depuis un aperçu.", + "s1909": "Ce dossier est indisponible ou protégé en écriture. Vérifiez le chemin et les autorisations du dossier.", + "s1910": "Cette installation ne calibre que les GPU NVIDIA. Utilisez le test court sur les autres appareils.", + "s1911": "Cette installation n’a pas de numéro de version comparable.", + "s1912": "C’est un adaptateur ou un fichier auxiliaire. Choisissez le GGUF du modèle complet.", + "s1913": "Ce n’est qu’un avertissement : le modèle risque d’être plus lent à cause du déchargement sur le SSD.", + "s1914": "Ce n’est pas un fichier de modèle GGUF.", + "s1915": "Cette API locale n’a pas de clé configurée.", + "s1916": "Ce média n’a pas pu se charger.", + "s1917": "Ce modèle ne tient pas dans la configuration choisie.", + "s1918": "Les métadonnées d’attention ou d’experts de ce modèle ne sont pas valides.", + "s1919": "Il manque des tenseurs ou des fragments à ce modèle.", + "s1920": "Ce modèle n’est plus chargé.", + "s1921": "Ce modèle n’est pas installé. Téléchargez-le et préparez-le d’abord.", + "s1922": "Ce modèle n’est pas prêt.", + "s1923": "Ce modèle a besoin d’un moteur plus récent.", + "s1924": "Ce modèle a besoin d’environ {0} Go.{1}", + "s1925": "Ce modèle prend en charge jusqu’à", + "s1926": "Cette version du modèle est indisponible.", + "s1927": "Ce modèle a été déchargé avant l’envoi.", + "s1928": "Cet hôte natif prend actuellement en charge un seul modèle avec placement automatique sur le GPU.", + "s1929": "Cet hôte natif prend en charge un seul modèle avec placement automatique sur le GPU.", + "s1930": "Cette opération n’est plus en cours.", + "s1931": "Cette image n’a pas pu être enregistrée.", + "s1932": "Ce port privé du moteur est déjà utilisé.", + "s1933": "Cet hôte ne peut pas annuler cette requête.", + "s1934": "Cette requête n’est plus conservée dans le journal de session.", + "s1935": "Cette requête n’est plus conservée.", + "s1936": "Cette configuration ne peut pas faire tenir son contexte et son exécution dans la mémoire disponible. Réduisez le contexte ou utilisez une version plus petite.", + "s1937": "Ce modèle fractionné a un nombre de fragments non pris en charge.", + "s1938": "Cela change la version du modèle pour toutes les conversations. Vos conversations restent enregistrées.", + "s1939": "Cela fait passer cette conversation en mode Ignorer les autorisations. Serveurs :", + "s1940": "Ce fichier texte est trop volumineux pour être prévisualisé.", + "s1941": "Cela prend en général quelques secondes. Vous pouvez fermer cette fenêtre pendant la connexion.", + "s1942": "Cette version n’est plus téléchargée.", + "s1943": "Cette version a besoin de plus de mémoire avec le contexte actuel. Choisissez une version plus petite ou réduisez le contexte dans Moteur.", + "s1944": "Ce site web n’a pas de fichier local", + "s1945": "Cet espace de travail", + "s1946": "Trois tâches qui avancent ensemble", + "s1947": "Juste — choisissez la plus petite variante", + "s1948": "Heure", + "s1949": "Time-skip", + "s1950": "Actions Time-skip", + "s1951": "Time-skip {0}", + "s1952": "Vers le GPU {0} Mo/s{1}", + "s1953": "Tok/s", + "s1954": "Utilisation des tokens", + "s1955": "Tokens en entrée / sortie", + "s1956": "Tokens de la requête en cours ou de la dernière requête de ce modèle.", + "s1957": "Demain est déjà planifié", + "s1958": "Trop gros", + "s1959": "Trop gros pour ce PC", + "s1960": "Trop général", + "s1961": "Activité des outils ·", + "s1962": "L’exécution des outils n’est pas connectée dans cette version. Les propositions et approbations enregistrées sont des exemples. La disponibilité n’accorde aucune autorisation.", + "s1963": "Temps des outils", + "s1964": "Délai d’attente des outils (secondes)", + "s1965": "Outils", + "s1966": "Outils et longs prompts", + "s1967": "Top-k", + "s1968": "Top-p", + "s1969": "Total sur les GPU sélectionnés", + "s1970": "Total dans cette conversation", + "s1971": "Mémoire totale", + "s1972": "Capacité physique totale de la RAM et de tous les GPU dédiés. Le placement du modèle détermine comment elle est utilisée.", + "s1973": "Total de tokens", + "s1974": "Transfert total vers les GPU sélectionnés", + "s1975": "Sujet de la visite", + "s1976": "Transfert vers le GPU indisponible", + "s1977": "Translucide", + "s1978": "Commandes translucides ou surfaces pleines. Le texte reste opaque.", + "s1979": "Transparence", + "s1980": "Phrases déclencheuses", + "s1981": "Essayez /time-skip, ou chargez un modèle pour discuter…", + "s1982": "Réessayer", + "s1983": "Essayez un autre filtre ou un autre nom de client.", + "s1984": "Essayez une autre recherche.", + "s1985": "Essayez ceci dans Strata", + "s1986": "Essayez deux versions et gardez la meilleure", + "s1987": "Essai d’une nouvelle direction", + "s1988": "Nouvel essai de révision. Votre progression est enregistrée.", + "s1989": "Optimiser et commencer à discuter", + "s1990": "Optimiser le modèle", + "s1991": "Optimisé pour votre ordinateur", + "s1992": "Optimisation arrêtée. Vos fichiers de modèle sont intacts.", + "s1993": "Optimisation…", + "s1994": "Token du tunnel", + "s1995": "Tournez le cadran · ou utilisez les flèches", + "s1996": "Transformez vos notes en plan de matinée ciblé.", + "s1997": "Tours / appels d’outils", + "s1998": "Transforme les commits fusionnés en notes de version destinées aux utilisateurs, regroupées par nouveauté, correctif et changement majeur.", + "s1999": "Deux passes. Une amélioration utile. L’original est toujours là.", + "s2000": "Deux directions possibles.", + "s2001": "Tapez /loop pour ouvrir les Tâches. Choisissez une tâche, fixez sa planification et laissez Strata la répéter, comme un point quotidien chaque jour de la semaine à 8 h.", + "s2002": "Tapez /time-skip et ce que vous voulez améliorer. Strata explore une révision, la compare à l’original et garde la meilleure version.", + "s2003": "Indisponible", + "s2004": "Comprend les photos et les captures d’écran. Les fichiers de vision sont déjà téléchargés.", + "s2005": "Comprend les photos, les captures d’écran et les graphiques. Les fichiers de vision se téléchargent automatiquement. Activez-les au chargement de ce modèle.", + "s2006": "Annuler", + "s2007": "Unifiée", + "s2008": "Mémoire unifiée", + "s2009": "Action de contrôle native inconnue.", + "s2010": "Action de tunnel inconnue.", + "s2011": "Décharger", + "s2012": "Déchargez un modèle avant d’en ajouter un autre. Cet aperçu prend en charge huit instances.", + "s2013": "Décharger après N secondes d’inactivité", + "s2014": "Déchargez une instance avant d’en ajouter une autre. Jusqu’à huit instances natives peuvent tourner ici.", + "s2015": "Décharger et changer de dossier", + "s2016": "Déchargez toutes les instances de ce modèle avant de supprimer ses fichiers.", + "s2017": "Échec du déchargement", + "s2018": "Décharger le modèle", + "s2019": "Déchargez les modèles et terminez les opérations avant de modifier l’installation.", + "s2020": "Déchargez les modèles natifs avant de modifier les fichiers du moteur.", + "s2021": "Déchargez les modèles natifs avant de changer le dossier des modèles.", + "s2022": "Déchargez les modèles actuels avant de changer de dossier.", + "s2023": "Déchargez ce modèle local avant de remplacer la référence de son fichier.", + "s2024": "Déchargez ce modèle avant de supprimer ses fichiers.", + "s2025": "Déchargez d’abord cette version", + "s2026": "Décharger {0} instances", + "s2027": "Déchargement…", + "s2028": "Détacher", + "s2029": "Non lu", + "s2030": "Mesures du moteur non reconnues", + "s2031": "Modifications non enregistrées", + "s2032": "Unsloth", + "s2033": "Non pris en charge", + "s2034": "Opération native non prise en charge.", + "s2035": "Dossier parent", + "s2036": "À jour", + "s2037": "Mettre à jour", + "s2038": "Mettre à jour Strata", + "s2039": "Mettre à jour Strata ?", + "s2040": "Mise à jour disponible", + "s2041": "Mettre à jour le moteur", + "s2042": "Mettre à jour le moteur ?", + "s2043": "La mise à jour a passé les vérifications d’exemple", + "s2044": "Mise à jour prête à être vérifiée", + "s2045": "Mettre à jour les réglages enregistrés", + "s2046": "Mettre à jour les réglages", + "s2047": "Mettez à jour l’installation native de Strata pour utiliser l’API Responses.", + "s2048": "Mettez à jour votre moteur ou importez un GGUF local pour ce modèle.", + "s2049": "Mis à jour", + "s2050": "Couverture Fieldnotes mise à jour : Make room for ideas, avec plus d’espace libre autour du titre.", + "s2051": "Résultat mis à jour conservé", + "s2052": "Mise à jour…", + "s2053": "Tableau de bord d’utilisation", + "s2054": "Période d’utilisation", + "s2055": "Source d’utilisation", + "s2056": "Utilisation indisponible", + "s2057": "Vue d’utilisation", + "s2058": "Utilisez Commande/Ctrl avec une lettre, un chiffre ou un signe de ponctuation.", + "s2059": "Utilisez Entrée ou Commande/Ctrl + Entrée. Maj + Entrée reste disponible pour une nouvelle ligne.", + "s2060": "Utilisez des variables d’environnement STRATA_ avec des valeurs de texte.", + "s2061": "Utilisez Strata en naviguant, en écrivant ou en travaillant.", + "s2062": "Utiliser une police de votre ordinateur", + "s2063": "Utiliser un GGUF local…", + "s2064": "Utiliser un modèle local", + "s2065": "Utiliser un modèle local…", + "s2066": "Utilisez un ID de modèle de /v1/models.", + "s2067": "Utilisez un nom de serveur simple : lettres, chiffres, tirets ou tirets bas.", + "s2068": "Utilisez un nom de tâche de 1 à 120 caractères.", + "s2069": "Utilisez un objet avec une entrée par serveur d’outils.", + "s2070": "Utiliser par défaut pour ce modèle", + "s2071": "Utiliser les outils MCP connectés", + "s2072": "Utilisez ici env, headers et cwd. Les identifiants existants sont masqués et conservés si vous gardez le masque.", + "s2073": "Utiliser les performances maximales", + "s2074": "Utiliser dans la conversation", + "s2075": "Utilisez des instructions de 1 à 12 000 caractères.", + "s2076": "Utilisez l’intelligence comme vous l’entendez.", + "s2077": "Utiliser l’ID du modèle", + "s2078": "Utiliser ma propre clé", + "s2079": "Utiliser un seul GPU quand le modèle y tient", + "s2080": "Utilisez l’adresse API du serveur. Pour un autre PC, saisissez son adresse réseau au lieu de localhost.", + "s2081": "Utilisez cette adresse et votre clé API Strata dans votre autre application.", + "s2082": "Utiliser ce dossier", + "s2083": "Utiliser ce dossier", + "s2084": "Utilisez ce nom d’hôte et votre clé API Strata dans votre client. Le streaming est pris en charge.", + "s2085": "Utiliser cette clé", + "s2086": "Utiliser ce modèle", + "s2087": "Utiliser cette version", + "s2088": "Utilisez jusqu’à 32 phrases déclencheuses, de 160 caractères maximum chacune.", + "s2089": "Utiliser la version", + "s2090": "Utilisez votre clé existante dans l’application que vous connectez.", + "s2091": "Utilisé au prochain chargement de ce modèle. Les valeurs d’échantillonnage par défaut s’appliquent à la prochaine requête.", + "s2092": "Sous-titre utile perdu", + "s2093": "Utilise le service vocal de votre navigateur.", + "s2094": "Utilise vos réglages enregistrés", + "s2095": "VRAM", + "s2096": "Taux de réussite en VRAM", + "s2097": "Valider le brouillon", + "s2098": "Version", + "s2099": "Actions sur la version", + "s2100": "Détails de la version", + "s2101": "Version indisponible", + "s2102": "Très élevé", + "s2103": "Vidéo", + "s2104": "Voir toutes les conversations", + "s2105": "Voir et changer de modèle", + "s2106": "Voir les journaux du moteur", + "s2107": "Voir le dernier résultat", + "s2108": "Voir le journal", + "s2109": "Voir les versions du modèle", + "s2110": "Voir le journal des requêtes", + "s2111": "Voir la requête {0}", + "s2112": "Voir les requêtes", + "s2113": "Voir la vue d’ensemble des sous-agents", + "s2114": "Voir la révision rejetée", + "s2115": "Les fichiers de l’encodeur de vision sont inclus. La lecture d’images ne se charge que si elle est activée.", + "s2116": "Style visuel", + "s2117": "Style visuel conservé", + "s2118": "Attendez la fin de la vérification du dossier des modèles.", + "s2119": "Attendez que ce modèle ait terminé avant de lancer un test.", + "s2120": "En attente de l’état de l’API…", + "s2121": "En attente d’une requête", + "s2122": "En attente de la télémétrie du moteur…", + "s2123": "Préchauffer", + "s2124": "Le préchauffage prend quelques secondes.", + "s2125": "Nous réservons de la mémoire GPU et limitons les workers d’experts CPU pour laisser de la marge aux autres applications. L’utilisation réelle varie selon votre modèle. Les besoins en RAM du modèle et les réserves de sécurité du système s’appliquent toujours.", + "s2126": "Adresse du site web", + "s2127": "Les sites web s’ouvrent dans votre navigateur par défaut.", + "s2128": "Jours de semaine", + "s2129": "Bilan hebdomadaire", + "s2130": "Bienvenue", + "s2131": "Nous appliquerons votre préférence et lancerons un court test de vitesse.", + "s2132": "Nous ouvrirons la conversation quand votre modèle sera prêt.", + "s2133": "Nous mesurons, appliquons votre préférence et préparons la conversation.", + "s2134": "Ce qui a changé", + "s2135": "Par quoi commençons-nous ?", + "s2136": "Que voulez-vous que Strata fasse ?", + "s2137": "Travaillez aux côtés de votre modèle", + "s2138": "Dérouler le plan", + "s2139": "Mise à jour en cours", + "s2140": "Travailler ensemble", + "s2141": "En cours…", + "s2142": "Espace de travail ajouté", + "s2143": "Espaces de travail", + "s2144": "Rédiger les récits du projet", + "s2145": "Écriture {0} Mo/s", + "s2146": "Écritures", + "s2147": "Rédige des messages de commit conventionnels à partir d’un diff, avec une ligne de portée et un paragraphe sur le pourquoi.", + "s2148": "Entraînement à l’écriture", + "s2149": "Vous pourrez toujours changer de modèles plus tard.", + "s2150": "Vous disposez de {0} Go libres.", + "s2151": "Il vous faut plus de stockage.", + "s2152": "Votre CPU", + "s2153": "Votre connecteur Cloudflare est installé et prêt.", + "s2154": "Votre route Cloudflare doit pointer vers {0}.", + "s2155": "Votre GPU", + "s2156": "Votre navigateur ne peut pas lister les polices installées. Saisissez le nom d’une police installée sur votre ordinateur.", + "s2157": "Le service vocal de votre navigateur ne prend pas en charge cette langue.", + "s2158": "Votre choix :", + "s2159": "Votre ordinateur", + "s2160": "Votre ordinateur peut sembler plus lent pendant le chargement des poids. Vous pouvez arrêter le téléchargement et le reprendre plus tard.", + "s2161": "Votre conversation et vos brouillons sont conservés pendant la reconnexion.", + "s2162": "Votre nom d’hôte", + "s2163": "Votre API d’inférence est accessible aux appareils de ce réseau.", + "s2164": "Votre installation locale de Strata gère les modèles optimisés, les fichiers complémentaires et les mises à jour du moteur.", + "s2165": "Votre modèle local reste disponible. Ajoutez une connexion API pour utiliser plus de modèles dans Strata.", + "s2166": "Votre modèle", + "s2167": "Votre dossier de modèles", + "s2168": "Vos modèles sont enregistrés ici. Utilisez un dossier existant pour réutiliser les téléchargements pris en charge.", + "s2169": "Votre nouvelle clé", + "s2170": "Votre ancienne clé cessera de fonctionner.", + "s2171": "Votre propre clé", + "s2172": "Vos conversations et vos réglages enregistrés sont toujours disponibles.", + "s2173": "Vous êtes connecté", + "s2174": "Zéro garde le modèle chargé.", + "s2175": "\\ -H 'Authorization: Bearer YOUR_API_KEY'", + "s2176": "accent", + "s2177": "actif", + "s2178": "actif ·", + "s2179": "réel", + "s2180": "avancé", + "s2181": "ai.example.com", + "s2182": "tout", + "s2183": "un autre espace de travail", + "s2184": "réponse", + "s2185": "vitesse de réponse", + "s2186": "api server endpoint openai anthropic port API serveur point d’accès port", + "s2187": "appearance colours apparence couleurs", + "s2188": "artifact-content", + "s2189": "croissant", + "s2190": "attribué", + "s2191": "à {0} tok/s", + "s2192": "auto", + "s2193": "auto ou 16,32", + "s2194": "auto, ou des points de répartition croissants comme 18 ou 16,32.", + "s2195": "débutant", + "s2196": "éclair", + "s2197": "branche", + "s2198": "brand brand--{0} {1}", + "s2199": "occupé", + "s2200": "button:not([disabled])", + "s2201": "cache ·", + "s2202": "calc(100dvh - {0}px)", + "s2203": "modification", + "s2204": "modifications", + "s2205": "chat", + "s2206": "chat, programmation", + "s2207": "chat:send", + "s2208": "chat:slot:", + "s2209": "vérification", + "s2210": "horloge", + "s2211": "code", + "s2212": "code-preview", + "s2213": "colonnes", + "s2214": "confortable", + "s2215": "commande", + "s2216": "compact", + "s2217": "terminé", + "s2218": "terminés ·", + "s2219": "ordinateur", + "s2220": "config-errors", + "s2221": "de contexte. Modifiez le contexte sur la page Modèle.", + "s2222": "réduire", + "s2223": "conversation prompt ask discussion prompt demander", + "s2224": "copier", + "s2225": "cœurs ·", + "s2226": "compteur", + "s2227": "CPU", + "s2228": "curl", + "s2229": "personnalisé", + "s2230": "valeurs personnalisées", + "s2231": "danger", + "s2232": "sombre", + "s2233": "décimal", + "s2234": "exemple", + "s2235": "refusé", + "s2236": "décroissant", + "s2237": "bureau", + "s2238": "détails", + "s2239": "dial-detent", + "s2240": "dial-detent dial-detent--recommended", + "s2241": "dialog", + "s2242": "dialog-surface", + "s2243": "dialog-surface dialog-surface--sheet", + "s2244": "dialog-surface--compact", + "s2245": "dialog-surface--wide", + "s2246": "dictation-feedback", + "s2247": "disque", + "s2248": "ne tient pas", + "s2249": "domaine", + "s2250": "terminé", + "s2251": "télécharger", + "s2252": "download weights gguf choose tune engine parameters context sampling télécharger poids gguf choisir optimiser moteur paramètres contexte échantillonnage", + "s2253": "eject stop vram éjecter arrêter vram", + "s2254": "fin", + "s2255": "moteur", + "s2256": "erreur du moteur", + "s2257": "erreur", + "s2258": "échap", + "s2259": "développer", + "s2260": "expert", + "s2261": "experts", + "s2262": "family-qwen", + "s2263": "rapide", + "s2264": "fichier", + "s2265": "fichiers ou recherche", + "s2266": "tient", + "s2267": "dossier", + "s2268": "pour les commandes,", + "s2269": "pour les conversations,", + "s2270": "pour les espaces de travail.", + "s2271": "libre", + "s2272": "depuis l’écran Modèles après le chargement", + "s2273": "complet", + "s2274": "génération", + "s2275": "génération · {0} tok/s", + "s2276": "go:models", + "s2277": "go:monitor", + "s2278": "go:tasks", + "s2279": "bon", + "s2280": "groupe", + "s2281": "matériel", + "s2282": "élevé", + "s2283": "inactif", + "s2284": "image", + "s2285": "image:select", + "s2286": "img", + "s2287": "dans chaque requête. Chaque modèle a sa propre file d’attente.", + "s2288": "dans cette bibliothèque d’exemple", + "s2289": "entrée ·", + "s2290": "info", + "s2291": "entrée · 256 en sortie ·", + "s2292": "input:not(:disabled),button:not(:disabled)", + "s2293": "input:not([disabled])", + "s2294": "instantané", + "s2295": "instructions", + "s2296": "instructions prompts abilities consignes prompts compétences", + "s2297": "est calibré. L’installateur enregistre les réglages mesurés à la fin.", + "s2298": "est une mémoire rapide. L’adéquation réelle", + "s2299": "est une mémoire rapide. L’adéquation réelle et le comportement de déchargement", + "s2300": "is-open", + "s2301": "à l’instant", + "s2302": "keys bindings help touches raccourcis aide", + "s2303": "dernier", + "s2304": "launch-plan", + "s2305": "couches", + "s2306": "quitter", + "s2307": "clair", + "s2308": "lien", + "s2309": "chargement", + "s2310": "markdown", + "s2311": "moyen", + "s2312": "un message est requis", + "s2313": "micro", + "s2314": "milieu", + "s2315": "mobile", + "s2316": "mode", + "s2317": "modèle", + "s2318": "fichiers du modèle ·", + "s2319": "version du modèle", + "s2320": "model-file", + "s2321": "modèles", + "s2322": "lune", + "s2323": "plusieurs", + "s2324": "non", + "s2325": "aucun modèle chargé", + "s2326": "aucun", + "s2327": "noopener,noreferrer", + "s2328": "normal", + "s2329": "maintenant", + "s2330": "npx, uvx ou python", + "s2331": "nombre", + "s2332": "numérique", + "s2333": "sur", + "s2334": "sur une limite de {0} W", + "s2335": "désactivé", + "s2336": "activé", + "s2337": "onboard-art onboard-art--{0}", + "s2338": "onboard-tour-preview preview-{0}", + "s2339": "original", + "s2340": "sortie", + "s2341": "vue d’ensemble", + "s2342": "page", + "s2343": "mot de passe", + "s2344": "PDF", + "s2345": "pdfjs-dist/build/pdf.worker.min.mjs?url", + "s2346": "crayon", + "s2347": "en attente", + "s2348": "plus", + "s2349": "preferences theme appearance text size préférences thème apparence taille du texte", + "s2350": "préparer", + "s2351": "préparation des résultats", + "s2352": "principal", + "s2353": "project-brief.md", + "s2354": "project-brief.pdf", + "s2355": "tokens du prompt", + "s2356": "lecture du prompt", + "s2357": "px", + "s2358": "en file d’attente", + "s2359": "en file d’attente ·", + "s2360": "rapide", + "s2361": "radio", + "s2362": "radiogroup", + "s2363": "lecture à {0} tok/s", + "s2364": "lecture", + "s2365": "lecture du prompt", + "s2366": "prêt", + "s2367": "reboot refresh redémarrer actualiser", + "s2368": "actualiser", + "s2369": "release-plan.csv", + "s2370": "requests reused prompt tokens requêtes tokens du prompt réutilisés", + "s2371": "requêtes ·", + "s2372": "relisez ceci, vérifiez mon code", + "s2373": "lignes ·", + "s2374": "lancer", + "s2375": "en cours ·", + "s2376": "s ont été", + "s2377": "échantillonnage", + "s2378": "save download markdown enregistrer télécharger markdown", + "s2379": "schedule recurring loop automation planifier récurrent boucle automatisation", + "s2380": "select:not([disabled])", + "s2381": "sélectionné", + "s2382": "serveurs connectés", + "s2383": "partagé", + "s2384": "bouclier", + "s2385": "unique", + "s2386": "plus lent", + "s2387": "fluide", + "s2388": "speech microphone voice transcribe parole microphone voix transcrire", + "s2389": "sr-only", + "s2390": "démarrer", + "s2391": "stats performance speed hardware statistiques performances vitesse matériel", + "s2392": "état indisponible", + "s2393": "étape", + "s2394": "arrêter", + "s2395": "strata:dictation", + "s2396": "strata:open-preview", + "s2397": "strata:open-website", + "s2398": "strata:tasks", + "s2399": "réussite", + "s2400": "soleil", + "s2401": "svg use", + "s2402": "syntax-code {0} {1}", + "s2403": "onglet", + "s2404": "tableau", + "s2405": "tablist", + "s2406": "tabpanel", + "s2407": "texte", + "s2408": "textarea:not([disabled])", + "s2409": "le modèle chargé", + "s2410": "réflexion", + "s2411": "threads", + "s2412": "juste", + "s2413": "time-skip-content", + "s2414": "pour rechercher, rédiger et relire mon plan de lancement.", + "s2415": "à faire", + "s2416": "basculer", + "s2417": "tok", + "s2418": "tok/s", + "s2419": "tokens", + "s2420": "tokens / seconde", + "s2421": "too-big", + "s2422": "too-large", + "s2423": "outil", + "s2424": "outils", + "s2425": "outils ·", + "s2426": "total", + "s2427": "true", + "s2428": "tours", + "s2429": "indisponible", + "s2430": "mémoire unifiée", + "s2431": "inconnu", + "s2432": "mis à jour", + "s2433": "mises à jour", + "s2434": "url", + "s2435": "version", + "s2436": "version-ladder--compact", + "s2437": "versions", + "s2438": "préchauffage", + "s2439": "avertissement", + "s2440": "était", + "s2441": "site web", + "s2442": "ne s’exécutera plus et sera retirée de vos tâches actives.", + "s2443": "wizard onboarding install resume assistant prise en main installation reprendre", + "s2444": "écrit", + "s2445": "ws__chev {0}", + "s2446": "oui", + "s2447": "your-next-idea.md", + "s2448": "{0} / {1} tokens · {2} %", + "s2449": "{0} Go de VRAM", + "s2450": "{0} Go en cache.", + "s2451": "{0} Go de capacité prévue restent disponibles.", + "s2452": "{0} Go au-dessus du budget", + "s2453": "{0} Go restants", + "s2454": "{0} GPU · utilisation moyenne", + "s2455": "{0} Vous pourrez le télécharger à nouveau dans Modèles.", + "s2456": "{0} Vos fichiers GGUF d’origine restent dans leur dossier.", + "s2457": "{0} actives · {1} en file d’attente", + "s2458": "{0} actives · {1} en file d’attente. Terminez ou annulez d’abord les requêtes.", + "s2459": "{0} cœurs ·", + "s2460": "{0} valeur exacte", + "s2461": "{0} experts en cache", + "s2462": "{0} fichiers trouvés", + "s2463": "{0} fichier(s) ignoré(s). Ajoutez jusqu’à 64 fichiers texte, avec 256 Ko de texte au total. Les photos et les PDF peuvent s’ouvrir séparément.", + "s2464": "{0} n’est plus dans le stockage du navigateur. Joignez-le à nouveau.", + "s2465": "{0} modèles chargés", + "s2466": "{0} modèles chargés", + "s2467": "{0} tokens du prompt sur {1} réutilisés", + "s2468": "{0} sur cet ordinateur. Choisissez une version pour supprimer ses fichiers.", + "s2469": "{0} processeurs · {1} cœurs · {2} threads", + "s2470": "{0} sous-agents en cours · Voir la vue d’ensemble", + "s2471": "{0} sous-agents en cours — afficher la vue d’ensemble", + "s2472": "{0} tokens · {1} tok/s", + "s2473": "Trouvé : {0} {1}{2}. Les prochains téléchargements utiliseront ce dossier.", + "s2474": "{0} · {1} · {2} · prompt hors cache", + "s2475": "{0} — afficher les détails", + "s2476": "{0} % du contexte", + "s2477": "{0} % de ce fichier", + "s2478": "{0}, 60 dernières secondes", + "s2479": "{0}, 60 dernières secondes. Utilisez les flèches pour examiner les échantillons.", + "s2480": "{0} : en dehors de la période sélectionnée", + "s2481": "{0} : utilisez une valeur texte, nombre ou vrai/faux.", + "s2482": "Le contexte de {0} K dépasse le budget disponible du modèle.", + "s2483": "{0}{1} tokens au total", + "s2484": "· Par défaut dans la conversation", + "s2485": "· Compatibilité vérifiée au chargement.", + "s2486": "· Exemple", + "s2487": "· Résultat d’exemple", + "s2488": "· Téléchargé", + "s2489": "· Image {0}", + "s2490": "· Local", + "s2491": "· Les exécutions manquées sont ignorées quand Strata est fermé.", + "s2492": "· Ouvrir dans le panneau latéral", + "s2493": "· Lit les images", + "s2494": "· environ", + "s2495": "· inactif Gen{0}", + "s2496": "· dernière réponse", + "s2497": "· nécessite plus de contexte", + "s2498": "· recommandé", + "s2499": "· {0} Go de marge en RAM dans l’estimation", + "s2500": "— modifications non enregistrées", + "s2501": "« {0} » est arrêtée. Restaurez-la depuis Tâches supprimées quand vous voulez.", + "s2502": " ». Essayez", + "s2503": "−1 choisit une graine aléatoire.", + "s2504": "-y\n@modelcontextprotocol/server-filesystem\n/your/folder", + "s2505": ". Copiez le token depuis la configuration de son connecteur.", + "s2506": ". L’accès au réseau dépend de l’adresse d’écoute de l’hôte et de votre pare-feu.", + "s2507": ". Les mesures conservées peuvent être périmées. Démarrez l’hôte du moteur configuré, puis réessayez.", + "s2508": "i-quant 2 bits, qualité un peu meilleure, vitesse proche", + "s2509": "2 bits, le plus rapide", + "s2510": "i-quant 3 bits, meilleure qualité, plus lent (plus de calcul CPU par token)", + "s2511": "i-quant 3,5 bits, la meilleure qualité (équivalente au modèle complet), le plus lent ; demande un PC de 64 Go avec peu d’autres programmes", + "s2512": "4 bits (Unsloth Dynamic), EXPÉRIMENTAL : la meilleure qualité, mais la plupart des experts viennent du SSD sur un PC de 64 Go (7 à 8,5 tokens/s mesurés)", + "s2513": "4 bits, téléchargement de 111 Go, la plupart des experts lus depuis le SSD : lent (7 à 8,5 tokens/s sur un PC de 64 Go)", + "s2514": "Une recommandation fondée sur le matériel détecté et les valeurs par défaut prises en charge. Enregistrez pour l’appliquer ; la vitesse n’a pas été mesurée.", + "s2515": "Choisissez le dossier de données Strata qui contient vos modèles téléchargés. Les fichiers correspondants sont réutilisés ; les fichiers manquants sont préparés automatiquement.", + "s2516": "Choisissez le fichier .gguf du modèle. Pour un modèle fractionné, choisissez n’importe quel fragment ; Strata trouve le premier et vérifie l’ensemble.", + "s2517": "Les fichiers terminés sont conservés. Le téléchargement, l’empaquetage et le chargement sont des étapes distinctes ; c’est le moteur qui confirme que tout est prêt.", + "s2518": "Experts déjà dans la mémoire du GPU ; la part PCIe est indiquée à part quand elle est communiquée.", + "s2519": "Nom de la famille de polices", + "s2520": "Des lots plus grands peuvent utiliser plus de mémoire ; ils ne sont pas toujours plus rapides.", + "s2521": "La mémoire est une approximation du catalogue, pas une mesure de mémoire libre. L’espace de travail des lots et le déchargement partiel ne sont pas prévus. Le temps de raisonnement et de planification n’est pas estimé ; ces durées ne sont pas le temps total de la tâche.", + "s2522": "Mode : {0}", + "s2523": "Aucun modèle de conversation n’est déclaré ; la mise en forme des réponses dépend du moteur.", + "s2524": "Rien ne correspond à « {0} ». Essayez > pour les commandes, # pour les conversations ou @ pour les espaces de travail.", + "s2525": "Seule l’API d’inférence est partagée. Les clients ont besoin de votre clé API. Utilisez un réseau local de confiance ; cette connexion utilise HTTP.", + "s2526": "Revoir le contexte", + "s2527": "Lancer l’installation guidée", + "s2528": "Les identifiants enregistrés sont masqués. Gardez le masque pour conserver une valeur existante ; saisissez une nouvelle valeur pour la remplacer.", + "s2529": "Ce modèle a besoin d’un moteur plus récent. Mettez à jour votre moteur ou importez un GGUF local pour ce modèle.", + "s2530": "Vos instructions et le dernier résultat sont conservés dans Tâches supprimées. Vous pouvez y restaurer la tâche ; sa planification restera en pause.", + "s2531": "la moitié des experts (code, outils, images conservés) : demande environ 32 Go de RAM, plus rapide ; moins bon hors programmation", + "s2532": "http://192.168.1.20:1234/v1", + "s2533": "https://example.com", + "s2534": "la seule taille de Coder : la moitié des experts, stockés comme IQ3_S (3,5 bits)", + "s2535": "le modèle d’origine", + "s2536": "réfléchit beaucoup plus court (−63 % de tokens de réflexion, des réponses 1,8 fois plus rapides d’après les chiffres de ses auteurs)", + "s2537": "Aperçu {0}", + "s2538": "Zoom {0}", + "s2539": "{0} · journal", + "s2540": "{0}. Utilisez les flèches pour examiner les échantillons.", + "s2541": "{0} : indisponible", + "s2542": "{0}{1} tok/s{2}", + "s2543": "Aperçu : {0}…", + "s2544": "Génération : {0} tok/s", + "s2545": "Lecture : {0} tok/s", + "s2546": "Réutilisés : {0} tokens", + "s2547": "Depuis {0} : {1} requêtes · {2} tokens de prompt · {3} tokens de sortie", + "s2548": "Strata va calibrer {0} et enregistrer les réglages les plus rapides mesurés.", + "s2549": "{0} requêtes sur {1} ont réutilisé des tokens du prompt", + "s2550": "{0} outils · {1} serveurs sur {2} connectés", + "s2551": "Un contexte plus court peut laisser de la place à une version plus petite.", + "s2552": "Vérifiez la connexion du client et réessayez la requête.", + "s2553": "Analysez cet ordinateur pour voir quelles versions conviennent.", + "s2554": "Vérifiez votre connexion internet, puis réessayez.", + "s2555": "Choisissez un fichier GGUF de modèle de texte complet.", + "s2556": "Corrigez le JSON avant d’enregistrer ou d’appliquer.", + "s2557": "Gérer votre bibliothèque de compétences", + "s2558": "Réessayez, ou désactivez la mesure plus longue ci-dessus.", + "s2559": "Essayez de relancer cette tâche.", + "s2560": "Essayez de renvoyer le message.", + "s2561": "Vos fichiers téléchargés sont conservés.", + "s2562": "Messages de commit", + "s2563": "Revue de code", + "s2564": "Notes de version", + "s2565": "Rapport matériel", + "s2566": "Impossible de charger les réglages du modèle.", + "s2567": "Vérifiez que le moteur est connecté et que ce modèle est installé, puis réessayez.", + "s2568": "Exécuté", + "s2569": "Non autorisé dans ce mode. Rien n’a été exécuté.", + "s2570": "Rejouer l’aperçu", + "s2571": "Environ {0} min restantes", + "s2572": "Environ {0} h {1} min restantes", + "s2573": "Environ {0} h restantes", + "s2574": "Le thème Système suit votre ordinateur par défaut.", + "s2575": "La lecture d’images n’est pas disponible pour ce modèle.", + "s2576": "Désactivez la lecture d’images et réessayez.", + "s2577": "Le modèle s’est arrêté au démarrage, très probablement parce que le PC manquait de mémoire.", + "s2578": "Fermez les autres programmes et réessayez, ou choisissez « Garder 20 % pour mon travail ». En mode expert, vous pouvez aussi activer l’option peu de RAM : une partie du modèle est alors lue depuis le SSD.", + "s2579": "Le chargement prend trop de temps.", + "s2580": "Le PC manque peut-être de mémoire. Fermez les autres programmes et réessayez.", + "s2581": "Le moteur de Strata pour cet ordinateur n’est pas encore installé.", + "s2582": "Il est ajouté quand vous téléchargez un modèle. Téléchargez à nouveau votre modèle pour l’ajouter.", + "s2583": "Le téléchargement n’a pas pu accéder à internet.", + "s2584": "Vérifiez votre connexion, puis appuyez sur Reprendre le téléchargement.", + "s2585": "Un fichier téléchargé n’a pas passé le contrôle de sécurité de Strata.", + "s2586": "Appuyez sur Reprendre le téléchargement et Strata le récupérera à nouveau.", + "s2587": "L’assistant de programmation n’est pas encore installé sur cet ordinateur.", + "s2588": "La conversation fonctionne sans lui.", + "s2589": "Strata n’a pas pu lire ses propres composants.", + "s2590": "Fermez puis rouvrez Strata. Si le problème persiste, réinstallez l’application.", + "s2591": "Un problème est survenu.", + "s2592": "Réessayez. Si le problème persiste, ouvrez Détails et partagez-les quand vous demandez de l’aide.", + "s2593": "Analyse de votre ordinateur…", + "s2594": "Préparation en cours…", + "s2595": "Téléchargement de votre modèle…", + "s2596": "Préparation de votre modèle pour Strata…", + "s2597": "Mettre à jour le composant", + "s2598": "Mettez à jour le moteur de cet ordinateur. Vos modèles et vos réglages sont conservés.", + "s2599": "Enregistré dans {0}", + "s2600": "Vous avez déjà un modèle pris en charge sur cet ordinateur ? Choisissez le dossier qui contient ses fichiers. Strata les vérifie, prépare le modèle et le charge. Rien n’est copié ni téléchargé.", + "s2601": "Dossier contenant les fichiers GGUF", + "s2602": "Chemin complet du dossier", + "s2603": "Vérifier les fichiers", + "s2604": "Modèle trouvé", + "s2605": "{0} fichiers · {1}", + "s2606": "Préparer et charger", + "s2607": "Certaines parties de ce modèle sont manquantes, ou le dossier contient plus d’un modèle.", + "s2608": "Mettez toutes les parties d’un seul modèle dans un seul dossier, puis vérifiez à nouveau.", + "s2609": "Strata ne peut pas encore exécuter ces fichiers.", + "s2610": "Strata exécute les modèles Qwen3.8-Flash-Next. Téléchargez-en un depuis Modèles, ou choisissez un dossier contenant ses fichiers.", + "s2611": "Ces fichiers n’ont pas pu être vérifiés.", + "s2612": "Vérifiez que le dossier contient des fichiers GGUF complets, puis réessayez.", + "s2613": "Budget de réflexion", + "s2614": "Sans limite", + "s2615": "Ce que cette tâche peut faire", + "s2616": "Regarder seulement, ne rien modifier", + "s2617": "M’arrêter et me prévenir avant toute modification", + "s2619": "Tâche terminée", + "s2620": "La tâche attend votre accord", + "s2621": "La tâche a échoué", + "s2622": "Écriture d’un fichier", + "s2623": "Fichier écrit", + "s2624": "Impossible d’écrire le fichier", + "s2625": "Modification d’un fichier", + "s2626": "Fichier modifié", + "s2627": "Impossible de modifier le fichier", + "s2628": "Lecture d’un fichier", + "s2629": "Fichier lu", + "s2630": "Impossible de lire le fichier", + "s2631": "Observation d’une image", + "s2632": "Image observée", + "s2633": "Impossible d’observer l’image", + "s2634": "Recherche de fichiers", + "s2635": "Fichiers recherchés", + "s2636": "Impossible de rechercher des fichiers", + "s2637": "Recherche dans les fichiers", + "s2638": "Recherche faite dans les fichiers", + "s2639": "Impossible de chercher dans les fichiers", + "s2640": "Exécution d’une commande", + "s2641": "Commande exécutée", + "s2642": "La commande a échoué", + "s2643": "Ouverture d’une page web", + "s2644": "Page web ouverte", + "s2645": "Impossible d’ouvrir la page web", + "s2646": "Recherche sur le web", + "s2647": "Recherche web effectuée", + "s2648": "Impossible de faire la recherche web", + "s2649": "Mise à jour de sa liste de tâches", + "s2650": "Liste de tâches mise à jour", + "s2651": "Impossible de mettre à jour sa liste de tâches", + "s2652": "Affichage d’un résultat", + "s2653": "Résultat affiché", + "s2654": "Impossible d’afficher le résultat", + "s2655": "Vérification du dossier", + "s2656": "Dossier vérifié", + "s2657": "Impossible de vérifier le dossier", + "s2658": "Vérification des tâches en arrière-plan", + "s2659": "Tâches en arrière-plan vérifiées", + "s2660": "Impossible de vérifier les tâches en arrière-plan", + "s2661": "Lecture d’une tâche en arrière-plan", + "s2662": "Tâche en arrière-plan lue", + "s2663": "Impossible de lire la tâche en arrière-plan", + "s2664": "Arrêt d’une tâche en arrière-plan", + "s2665": "Tâche en arrière-plan arrêtée", + "s2666": "Impossible d’arrêter la tâche en arrière-plan", + "s2667": "Utilisation d’un outil", + "s2668": "Outil utilisé", + "s2669": "L’outil a échoué", + "s2670": "Appliquer les réglages et charger", + "s2671": "Appliquer et charger", + "s2672": "Les fichiers du modèle sont déjà sur cet ordinateur. Rien ne sera téléchargé ; seuls les réglages que vous avez choisis sont appliqués.", + "s2673": "Les modèles natifs actuellement chargés seront d’abord déchargés.", + "s2674": "Strata ne peut pas ouvrir son fichier de réglages.", + "s2675": "Lancez Strata une fois avec votre propre compte (pas en administrateur) ou appuyez sur Réparer.", + "s2676": "Essayer une modification sur une copie, la vérifier, et ne la garder que si elle est meilleure", + "s2677": "Fixer un objectif et laisser l’assistant travailler jusqu’à ce qu’il soit atteint", + "s2678": "Répéter un message toutes les quelques minutes tant que cette conversation est ouverte", + "s2679": "Tapez /loop, la fréquence et ce qu’il faut faire — par exemple /loop 10m vérifiez la compilation. Strata l’envoie encore et encore tant que la conversation est ouverte. Pour un travail qui doit continuer Strata fermé, utilisez les Tâches.", + "s2680": "Indiquer la fréquence", + "s2681": "Indiquer quoi faire", + "s2682": "Arrêt à tout moment", + "s2683": "Garder la mise à jour", + "s2684": "Remettre l’original", + "s2685": "La mise à jour est dans vos fichiers. Vous pouvez remettre l’original.", + "s2686": "Vos fichiers sont inchangés. Gardez la mise à jour pour l’appliquer à votre dossier ; vous pourrez remettre l’original plus tard.", + "s2687": "Vérifications", + "s2688": "Résultat", + "s2689": "Aucune vérification n’est configurée pour ce dossier, rien n’a donc été jugé automatiquement. Regardez les deux versions et choisissez celle à garder.", + "s2690": "Conservé avant toute modification.", + "s2691": "Révision {0}", + "s2692": "Ce qui n’a pas fonctionné", + "s2693": "Arrêter Time-skip", + "s2694": "Mise à jour conservée · vos fichiers l’ont maintenant", + "s2695": "Original conservé · vos fichiers sont inchangés", + "s2696": "Prêt à comparer · vous choisissez ce qu’on garde", + "s2697": "Tapez /loop, la fréquence, puis ce qu’il faut faire. Par exemple : /loop 10m vérifiez si la compilation réussit. Utilisez /loop stop pour l’arrêter.", + "s2698": "Indiquez d’abord la fréquence, comme 10m (minutes) ou 2h (heures), puis ce qu’il faut faire.", + "s2699": "Le délai le plus court entre deux exécutions est de 1 minute, pour que le modèle ait le temps de terminer chacune.", + "s2700": "Le délai le plus long entre deux exécutions est de 24 heures. Pour des attentes plus longues, utilisez une tâche dans l’écran Tâches.", + "s2701": "toutes les minutes", + "s2702": "toutes les {0} minutes", + "s2703": "toutes les heures", + "s2704": "toutes les {0} heures", + "s2705": "Une boucle tourne dans cette conversation : elle envoie « {0} » {1}, tant que la conversation est ouverte. Tapez /loop stop pour l’arrêter.", + "s2706": "Boucle lancée : « {0} » {1}, tant que la conversation est ouverte. Tapez /loop stop pour l’arrêter. Pour un travail qui doit continuer Strata fermé, utilisez l’écran Tâches.", + "s2707": "Aucune boucle ne tourne dans cette conversation.", + "s2708": "La boucle est arrêtée.", + "s2709": "La boucle s’est arrêtée après {0} exécutions. Tapez /loop à nouveau pour la relancer.", + "s2710": "Cette conversation a déjà une boucle. Tapez d’abord /loop stop, puis lancez-en une nouvelle.", + "s2713": "Vos fichiers ont changé après le début de cet essai, rien n’a donc été écrasé. Relancez Time-skip.", + "s2714": "Chargez d’abord un modèle, puis relancez Time-skip.", + "s2715": "Impossible de joindre l’assistant. Réessayez.", + "s2716": "Time-skip s’est arrêté. {0} Vos fichiers n’ont pas été modifiés.", + "s2717": "Time-skip a été arrêté avant la fin. Vos fichiers n’ont pas été modifiés.", + "s2718": "L’assistant n’a rien modifié, il n’y a donc rien à comparer. Vos fichiers n’ont pas été modifiés.", + "s2719": "Time-skip n’a pas pu démarrer. {0}", + "s2720": "Time-skip a perdu le contact avec l’application et s’est arrêté. Vos fichiers n’ont pas été modifiés.", + "s2721": "La mise à jour est maintenant dans vos fichiers", + "s2722": "Vos fichiers d’origine sont revenus", + "s2724": "Vos fichiers n’ont pas été modifiés", + "s2725": "Chargement de la liste des outils…", + "s2726": "Choisissez ce que l’assistant peut utiliser dans vos conversations. Un changement s’applique dès votre prochain message. En mode Manuel, tout ce qui modifie votre ordinateur demande d’abord votre accord.", + "s2727": "Sur le web", + "s2728": "Pour les gros travaux", + "s2729": "Exécuter des commandes", + "s2730": "Permet à l’assistant d’exécuter des commandes, par exemple pour ouvrir un dossier ou lancer un programme.", + "s2731": "Lire et modifier des fichiers", + "s2732": "Permet à l’assistant de lire, créer et modifier des fichiers dans le dossier de votre conversation.", + "s2733": "Trouver des fichiers et du texte", + "s2734": "Permet à l’assistant de chercher des fichiers par nom et dans leur contenu. Il ne fait que lire.", + "s2735": "Tâches longues", + "s2736": "Permet à l’assistant de lancer une commande lente en arrière-plan et d’en vérifier l’avancement plus tard.", + "s2737": "Ouvrir des pages web", + "s2738": "Permet à l’assistant de lire une page web que vous lui indiquez.", + "s2739": "Rechercher sur le web", + "s2740": "Permet à l’assistant de chercher sur le web quand il a besoin d’informations récentes.", + "s2741": "Assistants auxiliaires", + "s2742": "Permet à l’assistant de lancer des auxiliaires qui travaillent en même temps sur des parties d’une tâche.", + "s2743": "Objectifs", + "s2744": "Permet de fixer un objectif avec /goal. L’assistant continue de travailler jusqu’à ce qu’il soit atteint.", + "s2745": "Liste de tâches", + "s2746": "Permet à l’assistant de tenir une liste de contrôle pendant une grande tâche.", + "s2747": "Permet à l’assistant d’utiliser vos compétences enregistrées quand elles conviennent à la tâche.", + "s2748": "Afficher les résultats", + "s2749": "Permet à l’assistant d’afficher une page ou un fichier dans l’aperçu à côté de la conversation.", + "s2750": "Recherche web", + "s2751": "D’où viennent les résultats", + "s2752": "Les recherches utilisent votre propre compte auprès de ce service.", + "s2753": "Les résultats viennent de DuckDuckGo. Vous n’avez besoin ni de compte ni de clé.", + "s2754": "DuckDuckGo (sans clé)", + "s2755": "Exa (votre propre clé)", + "s2756": "Perplexity (votre propre clé)", + "s2757": "DeepSeek (votre propre clé)", + "s2758": "Votre clé", + "s2759": "Une clé est enregistrée sur cet ordinateur. Saisissez-en une nouvelle pour la remplacer.", + "s2760": "Enregistrée sur cet ordinateur uniquement. Strata ne la réaffiche jamais.", + "s2761": "Collez votre clé", + "s2762": "Enregistrer la clé", + "s2763": "Clé enregistrée", + "s2764": "Navigateur web", + "s2765": "Utiliser un navigateur web", + "s2766": "L’assistant peut ouvrir des pages, cliquer et saisir du texte dans {0}. En mode Manuel, chaque action demande d’abord votre accord.", + "s2767": "votre navigateur", + "s2768": "Chrome ou Edge est introuvable sur cet ordinateur. Installez-en un, puis revenez l’activer.", + "s2769": "Vos propres outils", + "s2770": "Apprenez quelque chose de nouveau à l’assistant : donnez-lui des instructions à suivre, une commande à exécuter, ou connectez un serveur d’outils. Les commandes et les serveurs demandent d’abord votre accord en mode Manuel.", + "s2771": "Pas encore d’outils à vous", + "s2772": "Par exemple : « Rédigez les notes de version dans notre style maison », ou une commande qui vérifie que votre site est en ligne.", + "s2773": "Ajouter un outil", + "s2774": "Modifier l’outil", + "s2775": "Enregistrer l’outil", + "s2776": "Commande", + "s2777": "Serveur d’outils", + "s2778": "Suivre mes instructions", + "s2779": "Exécuter une commande", + "s2780": "Connecter un serveur d’outils (MCP)", + "s2781": "Par exemple : Notes de version", + "s2782": "Ce qu’il fait", + "s2783": "Une phrase. L’assistant la lit pour décider quand utiliser l’outil.", + "s2784": "Comment il fonctionne", + "s2785": "Écrivez ce que l’assistant doit faire quand il utilise cet outil.", + "s2786": "Commande à exécuter", + "s2787": "Par exemple : curl -I https://example.com", + "s2788": "L’assistant peut transmettre du texte à la commande. La commande le lit dans le réglage STRATA_INPUT. Ce qu’elle affiche est renvoyé à l’assistant.", + "s2789": "Adresse web ou programme", + "s2790": "https://… ou le programme qui démarre le serveur", + "s2791": "Réglages supplémentaires pour le programme", + "s2792": "(facultatif, un par ligne)", + "s2793": "Retirer cet outil ?", + "s2794": "Le garder", + "s2795": "« {0} » ne sera plus disponible pour l’assistant.", + "s2796": "Donnez à l’outil un nom court : lettres, chiffres, espaces ou tirets.", + "s2797": "Dites en une phrase ce que fait l’outil. L’assistant la lit pour décider quand l’utiliser.", + "s2798": "Écrivez les instructions que l’assistant doit suivre quand il utilise cet outil.", + "s2799": "Saisissez la commande à exécuter.", + "s2800": "Saisissez l’adresse web du serveur d’outils, ou le programme qui le démarre.", + "s2801": "La liste des outils n’a pas pu être chargée.", + "s2802": "La modification n’a pas pu être enregistrée.", + "s2803": "L’outil n’a pas pu être enregistré.", + "s2804": "L’outil n’a pas pu être retiré.", + "s2805": "L’outil de navigateur ne fait pas partie de cette installation.", + "s2806": "Travail sur une copie de vos fichiers. Suivez l’avancement dans la barre latérale.", + "s2807": "Le résultat est prêt. Passez de l’original à la version mise à jour, ou comparez-les côte à côte.", + "s2808": "Ouverture d’une page dans le navigateur", + "s2809": "Page ouverte dans le navigateur", + "s2810": "Impossible d’ouvrir la page", + "s2811": "Clic sur la page", + "s2812": "Clic effectué sur la page", + "s2813": "Impossible de cliquer sur la page", + "s2814": "Pointage sur la page", + "s2815": "Pointage effectué sur la page", + "s2816": "Impossible de pointer sur la page", + "s2817": "Saisie sur la page", + "s2818": "Saisie effectuée sur la page", + "s2819": "Impossible de saisir sur la page", + "s2820": "Observation de la page", + "s2821": "Page observée", + "s2822": "Impossible d’observer la page", + "s2823": "Utilisation du navigateur", + "s2824": "Navigateur utilisé", + "s2825": "L’étape du navigateur a échoué", + "s2826": "Lecture de vos instructions", + "s2827": "Instructions lues", + "s2828": "Impossible de lire vos instructions", + "s2829": "Exécution de votre outil", + "s2830": "Outil exécuté", + "s2831": "Votre outil a échoué", + "s2832": "Ce dossier est trop gros pour tester une modification sur une copie. Ouvrez un dossier plus petit pour cette conversation, puis réessayez.", + "s2833": "Time-skip travaille sur un dossier qui vous appartient. Choisissez un dossier de travail pour cette conversation, puis réessayez.", + "s2834": "Exécution d’un petit programme sur la page", + "s2835": "Petit programme exécuté sur la page", + "s2836": "Impossible d’exécuter le programme sur la page", + "s2837": "Attente de la page", + "s2838": "Page attendue", + "s2839": "Impossible d’attendre la page", + "s2840": "Retour à la page précédente", + "s2841": "Retour effectué à la page précédente", + "s2842": "Impossible de revenir en arrière", + "s2843": "Gestion des onglets du navigateur", + "s2844": "Onglets du navigateur gérés", + "s2845": "Impossible de gérer les onglets du navigateur", + "s2846": "Fermeture de la page du navigateur", + "s2847": "Page du navigateur fermée", + "s2848": "Impossible de fermer la page du navigateur", + "s2849": "Renommer {0}", + "s2850": "Renommer l’espace de travail", + "s2851": "Nom de l’espace de travail", + "s2852": "Seul le nom change. Le dossier reste où il est.", + "s2853": "Impossible de renommer cet espace de travail", + "s2854": "Modèles Swift", + "s2855": "Modèles GSQ-RCO", + "s2856": "Modèles NVFP4", + "s2857": "Modèles Gyro", + "s2858": "Modèles Unsloth", + "s2859": "Modèles Qwen3.6", + "s2860": "Utiliser votre propre GGUF…", + "s2861": "RAM + VRAM", + "s2862": "Utilise {0} Go de SSD", + "s2863": "le plus petit", + "s2864": "bon équilibre", + "s2865": "la meilleure qualité pour sa taille", + "s2866": "plus de qualité", + "s2867": "sur {0}", + "s2868": "{0} : environ {1} sur {2} utilisés par ce modèle", + "s2869": "{0} · {1} de mémoire graphique", + "s2870": "Aucune carte graphique prise en charge n’est signalée par cette installation.", + "s2871": "Mémoire graphique", + "s2872": " · {0} de RAM", + "s2873": "Environ {0} Go seront lus depuis le SSD, les réponses peuvent donc être un peu plus lentes.", + "s2874": "Tient entièrement en mémoire.", + "s2875": "Ouvrir votre dossier {0} dans l’Explorateur de fichiers ?", + "s2876": "Ouvrir le dossier {0} dans l’Explorateur de fichiers ?", + "s2877": "Ouvrir le fichier {0} ?", + "s2878": "Ouvrir l’Explorateur de fichiers ?", + "s2879": "Lancer un programme : {0} ?", + "s2880": "Exécuter le script {0} ?", + "s2881": "Exécuter {0} étapes sur votre ordinateur ?", + "s2882": "Exécuter une commande sur votre ordinateur ?", + "s2883": "Créer le fichier {0} ?", + "s2884": "Créer le dossier {0} ?", + "s2885": "Écrire dans le fichier {0} ?", + "s2886": "Modifier le fichier {0} ?", + "s2887": "Copier {0} ?", + "s2888": "Déplacer {0} ?", + "s2889": "Renommer {0} ?", + "s2890": "Exécuter git {0} ?", + "s2891": "Installer des paquets avec {0} ?", + "s2892": "Arrêter une tâche en arrière-plan ?", + "s2893": "Ouvrir la page web {0} ?", + "s2894": "Utiliser l’outil connecté {0} ?", + "s2895": "Utiliser l’outil {0} ?", + "s2896": "Une fenêtre va s’ouvrir. Rien n’est modifié.", + "s2897": "Peut modifier votre ordinateur.", + "s2898": "Est supprimé de votre ordinateur.", + "s2899": "Remplace le fichier s’il existe déjà.", + "s2900": "Modifie les fichiers ou l’historique du projet.", + "s2901": "Télécharge des logiciels et modifie votre ordinateur.", + "s2902": "Plusieurs choses se passent. Détails montre chaque étape.", + "s2903": "Détails montre exactement ce que cela fait.", + "s2904": "Peut agir sur le service que vous avez connecté.", + "s2905": "Mettre {0} en pause", + "s2906": "Reprendre {0}", + "s2907": "Résumé de la tâche", + "s2908": "Planification", + "s2909": "Ce qu’elle peut faire", + "s2910": "Dernière exécution échouée", + "s2911": "Pas encore exécutée", + "s2912": "Ce qu’elle fait", + "s2913": "Dernière réponse", + "s2914": "Suivante : {0}", + "s2915": "Calcul de la prochaine exécution…", + "s2916": "Analyse de votre PC", + "s2917": "Examen de votre carte graphique et de votre mémoire", + "s2918": "Mesure de la vitesse de base", + "s2919": "Chronométrage de vos réglages actuels", + "s2920": "Point de départ : {0} tokens par seconde", + "s2921": "Essai de réglages", + "s2922": "Essai d’autres réglages, un par un", + "s2923": "Confirmation du meilleur", + "s2924": "Le test est répété pour être sûr", + "s2925": "Enregistrement", + "s2926": "Conservé pour ce modèle ; vous pouvez l’annuler", + "s2927": "Étapes de l’optimisation", + "s2928": "En attente", + "s2929": "Vitesse actuelle", + "s2930": "tokens par seconde", + "s2931": "Vos réglages", + "s2932": "{0} à {1} tokens par seconde", + "s2933": "Avant", + "s2934": "Réflexion…", + "s2935": "Je réfléchis…", + "s2936": "Je mijote une réponse…", + "s2937": "Je rumine…", + "s2938": "Je relie les points…", + "s2939": "Je suis une idée…", + "s2940": "Je fais un brouillon…", + "s2941": "Je pèse le pour et le contre…", + "s2942": "Je lis entre les lignes…", + "s2943": "Je prépare une réponse…", + "s2944": "J’assemble le tout…", + "s2945": "Je suis une intuition…", + "s2946": "Lecture de votre message…", + "s2947": "Rédaction de la réponse…", + "s2948": "En attente de votre réponse…", + "s2949": "Les auxiliaires travaillent ({0})…", + "s2950": "Travail sur l’objectif, étape {0}", + "s2951": "{0} tokens", + "s2952": "A réfléchi pendant {0}", + "s2953": "Raisonnement", + "s2954": "Aller au dernier message", + "s2955": "A besoin de vous", + "s2956": "étape {0} sur {1}", + "s2957": "En cours de travail", + "s2958": "Reprendre l’objectif", + "s2959": "Mettre l’objectif en pause", + "s2960": "Modifier l’objectif", + "s2961": "Supprimer l’objectif", + "s2962": "L’objectif n’a pas été modifié", + "s2963": "Enregistrer l’objectif", + "s2964": "Vers quoi l’assistant doit-il continuer à travailler ?", + "s2965": "Supprimer cet objectif ?", + "s2966": "nouveau", + "s2967": "supprimé", + "s2968": "modifié", + "s2969": "Ce fichier est trop gros, ou n’est pas du texte : il est listé mais pas affiché.", + "s2970": "Absent auparavant.", + "s2971": "Supprimé.", + "s2972": "Voir l’aperçu", + "s2973": "Voir le code", + "s2974": "Page d’origine", + "s2975": "Page mise à jour", + "s2976": "{0} lignes inchangées", + "s2977": "Modifications", + "s2978": "Agrandir l’image {0}", + "s2979": "Cette image n’a pas pu être chargée.", + "s2980": "Original et version mise à jour, côte à côte", + "s2981": "Fichiers modifiés", + "s2982": "+{0} de plus", + "s2983": "Time-skip est au travail", + "s2984": "Révision en cours", + "s2985": "Lecture de vos fichiers…", + "s2986": "Essai d’une version améliorée…", + "s2987": "Vérification du résultat…", + "s2988": "Comparaison des deux versions…", + "s2989": "Après", + "s2990": "Enregistré sous {0}. Il est utilisé à chaque chargement de ce modèle.", + "s2991": "Optimisé et enregistré", + "s2992": "Définition de l’objectif", + "s2993": "Objectif défini", + "s2994": "Impossible de définir l’objectif", + "s2995": "Mise à jour de l’objectif", + "s2996": "Objectif mis à jour", + "s2997": "Impossible de mettre à jour l’objectif", + "s2998": "Vérification de l’objectif", + "s2999": "Objectif vérifié", + "s3000": "Impossible de vérifier l’objectif", + "s3001": "Lecture de votre message…", + "s3002": "Détermination de la prochaine étape…", + "s3003": "Réflexion… {0} tokens", + "s3004": "Rédaction de la réponse…", + "s3005": "En attente de votre réponse…", + "s3006": "Les auxiliaires travaillent ({0})…", + "s3007": "Travail sur l’objectif, étape {0}", + "s3008": "Écriture de {0}…", + "s3009": "Écriture d’un fichier…", + "s3010": "Écriture de {0}… ({1} Ko)", + "s3011": "Écriture d’un fichier… ({0} Ko)", + "s3012": "Modification de {0}…", + "s3013": "Modification d’un fichier…", + "s3014": "Modification de {0}… ({1} Ko)", + "s3015": "Modification d’un fichier… ({0} Ko)", + "s3016": "Lecture de {0}…", + "s3017": "Lecture d’un fichier…", + "s3018": "Observation d’une image…", + "s3019": "Exécution d’une commande…", + "s3020": "Recherche dans vos fichiers…", + "s3021": "Recherche sur le web…", + "s3022": "Ouverture de {0}…", + "s3023": "Ouverture d’une page web…", + "s3024": "Ouverture d’une page…", + "s3025": "Utilisation du navigateur…", + "s3026": "Définition de l’objectif…", + "s3027": "Mise à jour de l’objectif…", + "s3028": "Vérification de l’objectif…", + "s3029": "Mise à jour de sa liste de tâches…", + "s3030": "Utilisation d’une compétence enregistrée…", + "s3031": "Affichage d’un résultat…", + "s3032": "Exécution d’un plan en plusieurs étapes…", + "s3033": "Vérification des tâches en arrière-plan…", + "s3034": "Lecture de vos instructions…", + "s3035": "Exécution de votre outil…", + "s3036": "Utilisation d’un outil…", + "s3037": "Lecture de vos fichiers…", + "s3038": "Essai d’une version améliorée…", + "s3039": "Vérification du résultat…", + "s3040": "Comparaison des deux versions…", + "s3041": "Nouvelle compétence", + "s3042": "Voir les journaux", + "s3043": "Journaux du moteur", + "s3044": "Strata n’envoie aucune télémétrie d’utilisation.", + "s3045": "Les conversations restent dans le stockage du navigateur.", + "s3046": "Quand vous choisissez un modèle API, cette conversation et les instructions des compétences activées sont envoyées à son fournisseur.", + "s3047": "Le journal des requêtes de l’interface garde en mémoire le client, les durées et les métadonnées de tokens.", + "s3048": "La surveillance de l’API native peut conserver le contenu des requêtes en mémoire lorsqu’elle est activée.", + "s3049": "Les outils connectés accèdent aux ressources que vous configurez.", + "s3050": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s et la lecture du prompt de {2} tok/s, avec {3} tokens réutilisés.", + "s3051": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s et la lecture du prompt de {2} tok/s.", + "s3052": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s, avec {2} tokens réutilisés.", + "s3053": "Sur {0} requêtes, votre sortie moyenne était de {1} tok/s.", + "s3054": "{0} requêtes jusqu’ici.", + "s3055": "Tâche retirée", + "s3056": "Retirer cette tâche ?", + "s3057": "{0} % plus rapide", + "s3058": "Déjà le plus rapide", + "s3059": "Toujours aussi rapide qu’avant", + "s3060": "Plus lent qu’avant", + "s3061": "Mesure non fiable", + "s3062": "Impossible de savoir pour l’instant", + "s3063": "L’optimisation n’est pas terminée", + "s3064": "Vos réponses arrivent maintenant plus vite. La qualité reste la même.", + "s3065": "Rien de ce que nous avons essayé n’a fait mieux que vos réglages actuels, rien n’a donc été modifié.", + "s3066": "Votre optimisation enregistrée fonctionne toujours aussi bien qu’au moment de son enregistrement.", + "s3067": "Votre optimisation a été conservée. Refaites la vérification plus tard.", + "s3068": "Votre PC était trop occupé pour essayer d’autres réglages, rien n’a donc été modifié. Réessayez quand les autres programmes sont fermés.", + "s3069": "Votre PC était occupé pendant le test, nous n’avons donc pas pu mesurer de façon fiable. Rien n’a été modifié. Réessayez quand les autres programmes sont fermés.", + "s3070": "Il n’y avait pas assez de mémoire libre pour tester. Rien n’a été modifié. Fermez les autres programmes et réessayez.", + "s3071": "Le moteur n’a pas pu démarrer avec ces réglages. Rien n’a été modifié.", + "s3072": "Le moteur s’est arrêté pendant la mesure. Rien n’a été modifié.", + "s3074": "Enregistré sous", + "s3075": "Le plan n’a pas été modifié", + "s3076": "Modifier le plan", + "s3077": "Étape {0}", + "s3078": "Supprimer cette étape", + "s3079": "Ajouter une étape", + "s3080": "Enregistrer le plan", + "s3081": "{0} étapes", + "s3082": "{0} sur {1} terminées", + "s3083": "Rien ne s’exécute tant que vous n’avez pas approuvé.", + "s3084": "Rejeter", + "s3085": "Lancer comme objectif", + "s3086": "Il n’y a pas de plan dans cette conversation.", + "s3087": "En attente — part quand l’étape {0} se termine", + "s3088": "En attente — part quand l’assistant a terminé", + "s3089": "Annuler ce message", + "s3090": "Reprendre", + "s3091": "ignorée", + "s3092": "En pause · {0} sur {1} terminées", + "s3093": "Plan approuvé.", + "s3094": "Expérimental", + "s3095": "Autres façons d’ouvrir {0}", + "s3096": "Actions sur le fichier", + "s3097": "Afficher dans le dossier", + "s3098": "Copier le chemin", + "s3099": "Joindre comme contexte", + "s3100": "Chemin copié", + "s3101": "Joint à votre prochain message", + "s3102": "Le fichier n’a pas été ouvert", + "s3103": "Le fichier n’a pas d’aperçu", + "s3104": "Le dossier n’a pas été ouvert", + "s3105": "Le chemin n’a pas été copié", + "s3106": "Le fichier n’a pas été joint", + "s3107": "Sélectionner un dossier", + "s3108": "Choisissez le dossier dans lequel cette conversation travaille", + "s3109": "Dossier du projet : {0}. Le changer.", + "s3110": "Utiliser le dossier par défaut", + "s3111": "Le dossier n’a pas été modifié", + "s3112": "Le plan", + "s3113": "C’est ici que la vérification compte le plus", + "s3114": "choisie par défaut", + "s3115": "C’est un travail court, il n’y a donc qu’une version. Rien ne vaut la peine d’être divisé en branches.", + "s3116": "Étape {0} sur {1} : {2}", + "s3117": "Démarre quand A atteint l’étape {0}", + "s3118": "En attente de démarrage", + "s3119": "En attente du plan", + "s3120": "Progression de {0}", + "s3121": "Garder une version", + "s3122": "La version A est dans vos fichiers.", + "s3123": "La version B est dans vos fichiers.", + "s3124": "La lecture d’images demande quelques fichiers de plus qui ne sont pas encore sur cet ordinateur.", + "s3125": "Télécharger les fichiers de lecture d’images", + "s3126": "Deux versions à comparer", + "s3127": "A et B sont allées jusqu’au bout. Gardez celle que vous préférez.", + "s3128": "Time-skip travaille avec un modèle chargé. Choisissez-en un dans l’onglet Modèles, puis réessayez.", + "s3129": "Ceci est un essai d’exemple réalisé alors que l’application ne pouvait pas joindre son hôte.", + "s3130": "Démarrage en cours", + "s3131": "Time-skip a besoin que l’application finisse de démarrer. Réessayez dans un instant.", + "s3132": "Travail sur une copie de vos fichiers.", + "s3133": "Le moteur n’a pas pu démarrer car l’un de ses fichiers de programme est absent de cet ordinateur.", + "s3134": "Réinstallez Strata (l’installateur l’inclut) ou appuyez sur Réparer. Fermer d’autres programmes n’aidera pas.", + "s3135": "Le moteur n’a pas pu démarrer car l’un de ses fichiers de programme ne convient pas à cet ordinateur ou est endommagé.", + "s3136": "Réinstallez Strata ou appuyez sur Réparer. Si le problème persiste, mettez à jour votre pilote graphique.", + "s3137": "Le moteur a besoin d’une fonction de processeur plus récente que celle de cet ordinateur.", + "s3138": "Ouvrez Détails et partagez-les quand vous demandez de l’aide.", + "s3139": "Le moteur a planté au démarrage.", + "s3140": "Redémarrez le PC et réessayez. Si le problème persiste, mettez à jour votre pilote graphique et ouvrez Détails quand vous demandez de l’aide.", + "s3141": "Windows ou votre logiciel de sécurité a empêché le moteur de démarrer.", + "s3142": "Autorisez Strata dans votre logiciel de sécurité, puis réessayez.", + "s3143": "Strata n’a pas trouvé un fichier dont il a besoin pour démarrer le moteur.", + "s3144": "Réinstallez Strata ou appuyez sur Réparer.", + "s3145": "Le modèle s’est arrêté au démarrage.", + "s3146": "Aucun sélecteur de dossier n’a été trouvé. Installez zenity ou kdialog pour choisir un dossier, ou saisissez le chemin.", + "s3147": "Le sélecteur de dossier n’a pas pu s’ouvrir. Installez zenity ou kdialog pour choisir un dossier, ou saisissez le chemin.", + "s3148": "Saisissez le chemin du dossier", + "s3149": "Chemin du dossier", + "s3150": "/home/you/Documents", + "s3151": "Quitter Strata", + "s3152": "Quitter Strata ?", + "s3153": "Cela arrête le modèle et ferme Strata. Vos conversations et vos fichiers restent comme ils sont. Fermer seulement l’onglet du navigateur laisserait Strata en marche.", + "s3154": "Strata est arrêté", + "s3155": "Strata est arrêté. Vous pouvez fermer cet onglet. Pour le réutiliser, lancez Strata depuis son icône.", + "s3156": "Strata n’a pas pu être arrêté d’ici. Lancez l’application avec --quit dans un terminal, ou réessayez.", + "s3157": "Fermeture…", + "s3158": "Décompression du moteur fourni avec l’application. Cela prend environ une minute la première fois.", + "s3159": "Utilisation de {0}", + "s3160": "Installé · cloudflared {0}", + "s3161": "Le connecteur de Cloudflare tourne déjà sur cet ordinateur comme service système, Strata n’en a donc pas démarré un second. Arrêtez d’abord ce service (ou utilisez son tunnel tel quel), puis reconnectez-vous ici.", + "s3162": "Le connecteur de Cloudflare (cloudflared) tourne déjà sur cet ordinateur, Strata n’en a donc pas démarré un second. Fermez-le d’abord (ou utilisez son tunnel tel quel), puis reconnectez-vous ici.", + "s3163": "Strata n’a pas trouvé le connecteur de Cloudflare (cloudflared) sur cet ordinateur.", + "s3164": "Installez cloudflared (avec votre gestionnaire de paquets, ou depuis le site de Cloudflare), puis appuyez sur Réessayer l’installation. Strata le cherche dans votre PATH et aux emplacements habituels.", + "s3165": "Le connecteur Cloudflare de cet ordinateur est trop ancien.", + "s3166": "Mettez cloudflared à jour vers une version plus récente, puis appuyez sur Réessayer l’installation.", + "s3167": "Le fichier trouvé comme cloudflared ne s’est pas exécuté.", + "s3168": "Réinstallez cloudflared, puis appuyez sur Réessayer l’installation.", + "s3169": "Fichier de réglages", + "s3170": "Ouvrir le fichier de réglages", + "s3171": "Les modifications que vous faites dans le fichier s’appliquent au prochain démarrage du modèle.", + "s3172": "Ouvrez plutôt le fichier depuis son dossier, ou réessayez.", + "s3173": "Votre fichier de réglages contient une erreur, le modèle ne démarrera donc pas tant qu’elle n’est pas corrigée.", + "s3174": "Ouvrez le fichier de réglages, corrigez les lignes ci-dessous, puis rechargez le modèle.", + "s3175": "Le fichier de réglages n’est pas du JSON valide ; regardez près de la ligne {0}. Vérifiez s’il manque une virgule entre deux entrées, s’il y a une virgule après la dernière entrée ou s’il manque un guillemet.", + "s3176": "Le fichier de réglages n’est pas du JSON valide. Vérifiez s’il manque une virgule entre deux entrées, s’il y a une virgule après la dernière entrée ou s’il manque un guillemet.", + "s3177": "Le fichier de réglages doit contenir un seul objet, { … }, avec les réglages à l’intérieur.", + "s3178": "\"{0}\" n’est pas un réglage lu par Strata, il est donc ignoré. Vouliez-vous dire \"{1}\" ?", + "s3179": "\"{0}\" n’est pas un réglage lu par Strata, il est donc ignoré.", + "s3180": "\"args\" doit être une liste d’entrées de texte entre guillemets, par exemple [\"--ple-io\", \"mmap\"]. Les nombres doivent aussi être entre guillemets.", + "s3181": "Strata gère lui-même l’adresse réseau, le port et la clé API : --host, --port et --api-key dans \"args\" ne sont donc pas pris en compte.", + "s3182": "\"env\" doit être un objet de noms STRATA_ avec des valeurs de texte entre guillemets.", + "s3183": "L’entrée \"env\" {0} doit être un texte entre guillemets, par exemple \"1\".", + "s3184": "\"sampling\" doit être un objet tel que { \"temperature\": 0.7 }.", + "s3185": "\"{0}\" doit être true ou false, pas {1}.", + "s3186": "\"{0}\" doit être un nombre de {1} à {2}, pas {3}.", + "s3187": "\"{0}\" doit être un nombre entier de {1} à {2}, pas {3}.", + "s3188": "\"{0}\" doit être l’une des valeurs {1}, pas {2}.", + "s3189": "\"{0}\" doit être un texte court, ou une liste de noms courts.", + "s3190": "Les points de \"layer_split\" doivent augmenter de 1 à 47, par exemple \"16,32\", ou valoir \"auto\".", + "s3191": "\"gpu\" doit être un numéro de carte graphique comme 0, ou une liste comme [0, 1].", + "s3192": "Ligne {0} : {1}", + "s3193": "Votre fichier de réglages contient une erreur, le modèle n’a donc pas été démarré.", + "s3194": "Ouvrez le fichier de réglages sous Réglages experts, corrigez la ligne indiquée sous Détails, puis rechargez le modèle.", + "s3195": "Mettez le moteur à jour (Paramètres, Moteur, Mettre à jour le moteur), puis réessayez.", + "s3196": "Déjà utilisé par {0}", + "s3197": "Arrêtez ou terminez la conversation qui utilise encore ce modèle, puis réessayez.", + "s3198": "Un autre modèle sur la même carte graphique n’a pas laissé de place à celui-ci.", + "s3199": "Chargez-le sur un autre GPU, ou déchargez d’abord l’autre modèle.", + "s3200": "cloudflared tourne déjà pour un autre tunnel (PID {0}).", + "s3201": "cloudflared tourne déjà pour d’autres tunnels (PID {0}).", + "s3202": "Le tunnel de Strata pour cette adresse tourne déjà (PID {0}).", + "s3203": "Le tunnel de Strata pour cette adresse tourne déjà.", + "s3204": "Arrêtez-le d’abord, ou utilisez-le tel quel, puis reconnectez-vous ici.", + "s3205": "Les modèles qui restent chargés utilisent environ {0} Go de RAM et {1} Go de la mémoire de cette carte.", + "s3206": "Activé par défaut", + "s3207": "Comprend les photos, les captures d’écran et les graphiques. Les fichiers d’images se téléchargent automatiquement. Désactivez-le pour économiser de la mémoire.", + "s3208": "Lire les images avec ce modèle", + "s3209": "(son serveur indique qu’il ne le peut pas)", + "s3210": "(activé par défaut)", + "s3211": "Les images ne peuvent être envoyées qu’aux API de modèles qui utilisent le style de conversation OpenAI. Choisissez un autre modèle, ou retirez l’image.", + "s3212": "La lecture d’images est désactivée pour ce modèle. Ouvrez Paramètres, Modèles, modifiez la connexion et activez Lire les images avec ce modèle, ou choisissez un autre modèle.", + "s3213": "Chargez d’abord un modèle qui lit les images, puis ajoutez l’image.", + "s3214": "Ce modèle a été démarré sans lecture d’images. Ouvrez Modèles, activez Lire les images et rechargez-le.", + "s3215": "Ce modèle ne peut pas lire les images. Choisissez un modèle qui lit les images, ou retirez l’image.", + "s3216": "Elle est ouverte dans l’aperçu.", + "s3217": "1 compétence utilisée : {0}", + "s3218": "{0} compétences utilisées : {1}", + "s3219": "Continuer dans une nouvelle conversation", + "s3220": "Suite de la tâche « {0} »", + "s3221": "(a exécuté {0}, terminé).", + "s3222": "(a exécuté {0}, sans terminer).", + "s3223": "Ce qu’elle a trouvé", + "s3224": "Demande votre attention", + "s3225": "Ce qu’elle a fait", + "s3226": "Fichiers", + "s3227": "Aidez-moi à reprendre à partir de là, s’il vous plaît.", + "s3228": "…et {0} étapes de plus", + "s3229": "Saisissez un nombre.", + "s3230": "Saisissez un nombre entier de {0} à {1}.", + "s3231": "Ajouter une compétence ouvre une fenêtre de dossier sur l’ordinateur qui exécute Strata. Ouvrez Strata sur cet ordinateur pour en ajouter une.", + "s3232": "Capture d’écran enregistrée", + "s3233": "Elle est dans votre dossier Téléchargements.", + "s3234": "La capture d’écran n’a pas été enregistrée", + "s3235": "Réessayez, ou faites plutôt une capture d’écran de cette fenêtre.", + "s3236": "La fenêtre de dossier ne s’est pas ouverte. Saisissez plutôt le chemin du dossier.", + "s3237": "Le fichier n’a pas été ajouté", + "s3238": "Essayez de le déposer à nouveau.", + "s3260": "NVFP4 (version de Strata)", + "s3261": "NVFP4 (version de NVIDIA)", + "s3262": "NVFP4 (NVIDIA, entraîné pour le FP4)", + "s3263": "Conversion propre à Strata. La meilleure qualité des versions NVFP4.", + "s3264": "Le checkpoint NVFP4 de NVIDIA, converti pour Strata. Même taille et même vitesse.", + "s3265": "Le checkpoint FP4 de NVIDIA, entraîné pour le FP4. Un peu plus rapide sur les prompts courts.", + "s3266": "Toutes les autres versions", + "s3267": "Plus de versions", + "s3268": "Téléchargement des fichiers du modèle · partie {0} sur {1}", + "s3269": "Téléchargement du lecteur d’images…", + "s3270": "Téléchargement du moteur pour ce PC…", + "s3271": "Préparation de {0}", + "s3272": "Parties du téléchargement", + "s3273": "Lecteur d’images", + "s3274": "Fichiers partagés", + "s3275": "Utilisés par plus d’un modèle", + "s3276": "Ces fichiers sont dans votre propre dossier, ils y restent donc. Seule l’entrée dans Strata est retirée.", + "s3277": "Le modèle en cours d’exécution sera déchargé.", + "s3278": "Local", + "s3279": "Strata n’a pas reconnu de moteur pour cet ordinateur. Le modèle va se télécharger, mais il risque de ne pas fonctionner tant que le bon moteur n’est pas installé (Paramètres → Moteur).", + "s3280": "Strata n’a pas reconnu de moteur pour cet ordinateur. Le modèle est téléchargé, mais il ne peut pas fonctionner tant que le bon moteur n’est pas installé. Ouvrez Paramètres → Moteur.", + "s7332": "Un modèle est en cours de téléchargement", + "s7333": "Votre modèle est en cours de téléchargement ({0} %). Vous pourrez discuter quand il sera terminé.", + "s7334": "Votre modèle est en cours de téléchargement. Vous pourrez discuter quand il sera terminé.", + "s7335": "Le modèle se charge", + "s7336": "Votre modèle est encore en cours de chargement. Vous pourrez discuter dans un instant.", + "s7337": "Aucun modèle n’est chargé", + "s7338": "Aucun modèle n’est chargé. Chargez-en un d’abord dans Modèles.", + "s7339": "Démarrage de l’assistant…", + "s7340": "L’assistant n’a pas pu démarrer. Réessayez dans un instant.", + "s7341": "Travail sur l’objectif…", + "s8001": "le choix pour ce PC", + "s8002": "l’autre choix", + "s7400": "L’assistant veut chercher sur le web : {0}. Les mots recherchés sont envoyés à {1}.", + "s7401": "L’assistant veut ouvrir la page web {0}. Le site de la page voit la requête.", + "s7402": "Laisser l’assistant chercher sur le web sans demander", + "s7403": "En mode Manuel, l’assistant demande une fois par conversation avant de chercher sur le web ou d’ouvrir une page web. Activez ceci pour passer cette question.", + "s7404": "DuckDuckGo, ou Bing quand DuckDuckGo est saturé", + "s8201": "moins d'1 min", + "s8202": "{0} min", + "s8203": "{0} h", + "s8204": "{0} j", + "s8205": "il y a {0}", + "s8206": "aujourd’hui {0}", + "s8207": "hier", + "s8208": "démarrée {0}", + "s8209": "en attente depuis {0}", + "s8210": "prochaine dans {0}", + "s8211": "répond maintenant", + "s8212": "arrêtée {0}", + "s8213": "Elle ne s’est pas terminée.", + "s8214": "Cette exécution a été arrêtée avant la fin.", + "s8215": "Strata s’est fermé pendant cette exécution, elle ne s’est donc pas terminée.", + "s8216": "Terminée, mais elle voulait modifier quelque chose sans pouvoir demander. Rien n’a été modifié.", + "s8217": "Arrêtée : {0} exécutions de suite n’ont pas fonctionné.", + "s8218": "Tâche planifiée", + "s8219": "Boucle · {0}", + "s8220": "Chargez d’abord un modèle", + "s8221": "Autres actions pour {0}", + "s8222": "Les cartes bougent toutes seules selon ce qui se passe. Une carte de À traiter y reste jusqu’à ce que vous vous en occupiez ou la fermiez.", + "s8223": "{0} demandent votre attention", + "s8224": "Rien n’a besoin de vous pour l’instant.", + "s8225": "{0} cartes", + "s8226": "À venir", + "s8227": "Suite de la conversation « {0} »", + "s8228": "La boucle", + "s8229": "Ce que j’ai demandé", + "s8230": "La dernière réponse", + "s8231": "Tableau des tâches", + "s8232": "À traiter", + "s8233": "Vous attendent", + "s8234": "Arrêtée sur une question à laquelle vous seul pouvez répondre.", + "s8235": "A trouvé un problème. Reste ici jusqu’à ce que vous vous en occupiez.", + "s8236": "Terminée sans problème ces 7 derniers jours.", + "s8237": "Relancer", + "s8238": "Ouvrir la tâche", + "s8239": "Ouvrir la conversation", + "s8240": "Arrêter la conversation", + "s8241": "Arrêter la boucle", + "s8242": "Voir le résultat", + "s8243": "Terminée", + "s8244": "Arrêtée par vous", + "s8245": "Arrêtée à la fermeture de Strata", + "s8246": "Terminée d’elle-même", + "s8247": "réponse {0} sur {1}", + "s8248": "réponse {0}", + "s8249": "1 auxiliaire au travail", + "s8250": "{0} auxiliaires au travail", + "s8251": "Tableau", + "s8252": "Afficher", + "s8253": "Tout ce qui tourne, attend votre réponse ou mérite un coup d’œil.", + "s8254": "Ça n’a pas fonctionné", + "s8255": "Aucune carte correspondante.", + "s8256": "Rien ici pour l’instant.", + "s8257": "toutes les {0} min", + "s8258": "Ce moteur Strata n’a pas de code pour la carte graphique qu’il a essayé d’utiliser.", + "s8259": "Choisissez une autre carte sous Exécuter sur, ou ouvrez Détails pour voir quelles cartes ont été trouvées et pour quoi le moteur est conçu.", + "s8260": "Ce réglage ne fait rien dans l’application. Les pages web de n’importe quel site peuvent déjà appeler l’API indiquée sous Serveur API. Pour n’autoriser que certains sites, ou pour utiliser le serveur propre du moteur (port 8080), ajoutez \"cors_origins\": [\"https://your.site\"] au fichier de configuration du modèle.", + "s8301": "Créer une clé API (recommandé)", + "s8302": "Sans clé API, n’importe quel appareil de ce réseau peut utiliser votre modèle.", + "s8303": "Seule l’API d’inférence est partagée. Les clients ont besoin de votre clé API quand il y en a une. Utilisez un réseau local de confiance ; cette connexion utilise HTTP.", + "s8304": "Créez une clé pour protéger votre API. Vous reviendrez ici quand elle sera prête. Vous pouvez aussi continuer sans clé, mais toute personne qui trouve le lien pourra alors utiliser votre modèle.", + "s8305": "Vous avez déjà un modèle pris en charge sur cet ordinateur ? Choisissez le dossier qui contient ses fichiers, ou l’un de ses fichiers .gguf. Strata les vérifie, prépare le modèle et le charge. Rien n’est copié ni téléchargé.", + "s8306": "Dossier contenant les fichiers GGUF, ou un fichier .gguf", + "s8307": "Chemin complet du dossier ou du fichier", + "s8308": "Sans clé API, toute personne qui peut atteindre cette adresse peut utiliser votre modèle.", + "s8309": "Strata n’a pas pu utiliser {0} pour les modèles ({1}), ils sont donc placés dans {2}. Vous pouvez choisir un autre dossier dans les Paramètres.", + "s8310": "Le port {0} est déjà utilisé. Strata est peut-être déjà en cours d’exécution ; fermez-le ou fermez l’autre programme, ou lancez Strata avec un autre port (STRATA_PORT).", + "s8311": "Windows ou un pare-feu ne laisse pas Strata utiliser le port {0}. Hyper-V, WSL et Docker se réservent des plages de ports (voir \"netsh int ipv4 show excludedportrange protocol=tcp\"). Lancez Strata avec un autre port (STRATA_PORT), par exemple 8801.", + "s8312": "{0} n’est pas une adresse de cet ordinateur, Strata ne peut donc pas y écouter. Vérifiez STRATA_BIND.", + "s8313": "Strata ne peut pas écouter sur {0}:{1} ({2}).", + "s8339": "Dossier des modèles", + "s8340": "Strata enregistre ici les gros fichiers de modèles.", + "s8341": "Changer de dossier", + "s8342": "En attente du dossier…", + "s8343": "Espace disque utilisé", + "s8344": "{0} libres", + "s8345": "sur ce disque", + "s8346": "Vos modèles utilisent {0}", + "s8347": "Terminez ou arrêtez le téléchargement pour changer de dossier.", + "s8348": "Ce dossier n’existe pas", + "s8349": "Ce dossier ne peut pas être utilisé", + "s8350": "Strata ne peut pas enregistrer de fichiers dans {0}.", + "s8351": "Strata ne trouve pas {0}.", + "s8352": "Choisissez un dossier en dehors du dossier actuel.", + "s8353": "Choisissez un dossier qui vous appartient, par exemple dans Documents ou sur un autre disque.", + "s8354": "Vérifiez que le disque est branché, puis choisissez à nouveau le dossier. Vos modèles n’ont pas été touchés.", + "s8355": "Utiliser ce dossier pour vos modèles ?", + "s8356": "Nouveau dossier", + "s8357": "{0} libres sur ce disque", + "s8358": "Vous avez choisi tout le disque {0}. Strata garde ses fichiers dans un dossier à part, vos modèles iront donc dans {1}.", + "s8359": "Les trois choix viennent ensuite.", + "s8360": "Déplacer mes modèles", + "s8361": "Utiliser les deux dossiers", + "s8362": "Repartir de zéro", + "s8363": "Déplacement de vos modèles", + "s8364": "Arrêter le déplacement", + "s8365": "{0} sur {1} Go", + "s8366": "Moins d’une minute restante", + "s8367": "Environ une minute restante", + "s8368": "Environ {0} minutes restantes", + "s8369": "Environ {0} heures restantes", + "s8370": "Gardez Strata ouvert. Vous pouvez continuer à utiliser d’autres applications. Vos modèles ne peuvent pas être chargés tant que le déplacement n’est pas terminé.", + "s8371": "Copie en cours : {0}, fichier {1} sur {2}", + "s8372": "De {0} vers {1}", + "s8373": "Déplacer mes modèles là-bas", + "s8374": "Vous n’avez aucun modèle à déplacer.", + "s8375": "Strata déplace vos {0} de modèles vers le nouveau dossier. C’est le même disque, cela prend donc un instant.", + "s8376": "Strata copie vos {0} de modèles vers le nouveau dossier, les vérifie, puis supprime les anciennes copies.", + "s8377": "Ne demande aucun espace supplémentaire.", + "s8378": "Demande {0} libres dans le nouveau dossier. Vous avez {1}.", + "s8379": "Les garder où ils sont et utiliser aussi le nouveau dossier", + "s8380": "Rien n’est copié. Vos modèles actuels continuent de fonctionner, et les nouveaux téléchargements vont dans le nouveau dossier.", + "s8381": "Ne demande pas d’espace maintenant. Les nouveaux téléchargements doivent tenir dans {1}.", + "s8382": "Ne demande pas d’espace maintenant.", + "s8383": "Strata utilise désormais le nouveau dossier et n’affiche pas vos modèles actuels. Vos anciens fichiers ne sont pas supprimés.", + "s8384": "Ne demande pas d’espace maintenant. Chaque modèle que vous téléchargerez ensuite aura besoin de son propre espace.", + "s8385": "Vos modèles ont besoin de {0}, ce disque a {1} libres.", + "s8386": "Libérez environ {0} sur ce disque, choisissez un autre dossier, ou prenez l’une des deux autres options.", + "s8387": "Ce qui doit arriver à vos modèles", + "s8388": "Un modèle en cours d’exécution est d’abord arrêté ; rechargez-le quand le déplacement est terminé.", + "s8389": "{0} seraient déplacés.", + "s8390": "L’espace libre est mesuré sur le disque qui contient {0}.", + "s8391": "Ancien dossier : {0}", + "s8392": "Strata copie un fichier à la fois et vérifie sa taille avant de supprimer l’ancien.", + "s8393": "Vous pouvez arrêter à tout moment ; les fichiers déjà déplacés restent utilisables.", + "s8394": "Le disque n’a plus d’espace", + "s8395": "Le déplacement s’est arrêté", + "s8396": "{0} s’est rempli après {1}, le déplacement s’est donc arrêté.", + "s8397": "Les modèles n’ont pas pu être déplacés.", + "s8398": "Rien n’a été perdu. Les modèles déjà déplacés sont dans le nouveau dossier, les autres sont toujours dans {0}, et le fichier à moitié copié a été supprimé. Libérez de l’espace sur {1} ou choisissez un autre dossier, puis réessayez.", + "s8399": "Rien n’a été perdu. Tous vos modèles sont toujours dans {0}, et le fichier à moitié copié a été supprimé. Libérez de l’espace sur {1} ou choisissez un autre dossier, puis réessayez.", + "s8400": "Rien n’a été perdu. Vos modèles qui n’ont pas été déplacés sont toujours dans {0}. Choisissez un autre dossier pour réessayer.", + "s8401": "Déplacement arrêté", + "s8402": "Rien n’a été perdu.", + "s8403": "{0} est dans le nouveau dossier.", + "s8404": "{0} est toujours dans l’ancien dossier.", + "s8405": "Les deux fonctionnent.", + "s8406": "Les modèles des deux dossiers sont listés normalement. Vous pourrez terminer le déplacement plus tard avec Changer de dossier.", + "s8407": "Vos modèles sont déplacés", + "s8408": "{0} sont maintenant dans {1}", + "s8409": "Les anciennes copies ont été supprimées et {0} sont de nouveau libres sur {1}.", + "s8410": "Strata utilise désormais aussi {0}. Les nouveaux téléchargements y vont, et vos modèles actuels restent où ils sont.", + "s8411": "Strata utilise désormais {0}. Vos anciens fichiers de modèles sont toujours dans {1} ; Strata ne les supprime pas.", + "s8412": "Le changement du dossier des modèles fait partie de l’application Strata.", + "s8413": "Un modèle est en cours d’exécution. Arrêtez-le d’abord, puis changez de dossier.", + "s8414": "Choisissez un dossier de modèles.", + "s8415": "Choisissez ce qu’il faut faire de vos modèles.", + "s8416": "Ce choix n’est pas possible ici.", + "s8417": "Un déplacement a été interrompu. Terminez-le ou laissez-le.", + "s8418": "Strata déplaçait vos modèles de {0} vers {1} quand il s’est arrêté. Rien n’est perdu.", + "s8419": "Terminer le déplacement", + "s8420": "Le laisser", + "s8421": "Terminer place tous vos modèles dans {1}. Le laisser les garde dans {0} et supprime les copies partielles de {1}.", + "s8422": "Les copies partielles ont été supprimées. Vos modèles sont dans {0}.", + "s8601": "Cartes graphiques", + "s8602": "Principale", + "s8603": "Auxiliaire", + "s8604": "Votre choix.", + "s8605": "Recommandé.", + "s8606": "Vous avez changé les rôles. Strata utilisera exactement ceux-ci.", + "s8607": "Recommandé : {0}", + "s8608": "Rôle de {0}", + "s8609": "{0} Go de mémoire", + "s8610": "Utilise la mémoire de votre ordinateur (graphisme intégré)", + "s8611": "Fait le travail principal", + "s8612": "Contient une partie du modèle", + "s8613": "Inutilisée", + "s8614": "Utilisée par {0}", + "s8615": "La désactiver", + "s8616": "Définir {0} comme principale", + "s8617": "{0} ne peut pas exécuter Strata.", + "s8618": "{0} est un graphisme intégré ; elle est lente comme carte principale.", + "s8619": "Les performances sont dégradées avec le CPU seul.", + "s8620": "Ce moteur a besoin d’une carte graphique pour démarrer. Activez-en une.", + "s8621": "Pas assez de mémoire pour cette configuration : environ {0} Go sont lus depuis le disque.", + "s8622": "{0} est maintenant auxiliaire.", + "s8623": "{0} est maintenant principale.", + "s8624": "La seule carte activée doit être la principale.", + "s8625": "Aucune carte graphique utilisable par Strata n’a été trouvée.", + "s8626": "Strata utilisera votre {0}.", + "s8627": "{0} est principale : {1}.", + "s8628": "les cartes se valent", + "s8629": "elle a plus de mémoire", + "s8630": "elle est plus rapide", + "s8631": "c’est la seule carte", + "s8632": "{0} aident.", + "s8633": "{0} aide.", + "s8634": "{0} démarre désactivée : {1}", + "s8635": "Strata ne peut pas l’exécuter.", + "s8636": "graphisme intégré.", + "s8637": "{0} Go ou moins.", + "s8638": "La carte qui fait les dernières étapes de chaque réponse : elle écrit les mots suivants, exécute l’étape d’anticipation et la vérifie, et garde votre conversation. Choisissez votre carte la plus rapide avec beaucoup de mémoire. Il n’y en a jamais qu’une.", + "s8639": "Contient une part du modèle et de sa mémoire rapide, pour que davantage tienne sur les cartes graphiques au lieu d’être lu depuis votre disque. Les prompts sont lus environ 20 % plus vite.", + "s8640": "Strata ne touche pas à cette carte. Pratique pour une carte que vous utilisez pour autre chose, comme un jeu ou votre écran.", + "s8641": "Le modèle a besoin d’environ {0} Go. Ces cartes et votre mémoire en offrent environ {1}. Il tient.", + "s8642": "Le modèle a besoin d’environ {0} Go. Ces cartes et votre mémoire en offrent environ {1}, donc environ {2} Go seraient lus depuis votre disque.", + "s8643": "Seuls votre processeur et votre mémoire sont utilisés.", + "s8644": "Pour les experts : le moteur démarre sur les cartes {0} (la principale en dernier).", + "s8645": "Non enregistré tant que vous gardez la recommandation : Strata choisit à nouveau si vous ajoutez ou retirez une carte.", + "s8646": "Inutilisée : {0} (une autre marque de carte graphique que celle que ce moteur pilote).", + "s9001": "Ce message fait environ {0} tokens, et ce modèle peut en lire environ {1} à la fois. Il est trop gros pour être envoyé tel quel.", + "s9002": "Joignez-le comme fichier pour que l’assistant le lise par parties, ou envoyez un aperçu raccourci.", + "s9003": "Cette conversation ne tient plus dans la fenêtre du modèle, et le résumé des anciens messages n’a pas libéré assez de place.", + "s9004": "Résumez-la maintenant et continuez, ou ouvrez une nouvelle conversation.", + "s9005": "Résumé des messages précédents…", + "s9006": "Les anciens messages ont été résumés pour faire de la place. La conversation était pleine à {0} % et l’est maintenant à {1} %.", + "s9007": "Les anciens messages ont été résumés pour faire de la place. La conversation était pleine à {0} %.", + "s9008": "Les anciens messages ont été résumés pour faire de la place.", + "s9009": "Cette conversation est pleine à {0} %, mais il n’y a rien d’ancien à résumer : c’est le dernier message qui la remplit. Ouvrez une nouvelle conversation, ou envoyez un message plus court.", + "s9010": "Il n’y a encore rien d’ancien à résumer. Tout ce qui est dans cette conversation sert encore à l’assistant.", + "s9011": "Il n’y a encore rien à résumer. Cette conversation n’a pas encore commencé avec l’assistant.", + "s9012": "Les anciens messages n’ont pas pu être résumés pour le moment. Réessayez dans un instant, ou ouvrez une nouvelle conversation.", + "s9013": "Cette conversation est encore en cours de travail. Arrêtez-la ou attendez la fin, puis réessayez.", + "s9014": "Joindre comme fichier", + "s9015": "Envoyer un aperçu raccourci", + "s9016": "Résumer et continuer", + "s9017": "Ouvrir une nouvelle conversation", + "s9018": "Le message n’a pas pu être préparé. Essayez un message plus court.", + "s9019": "La dernière session de Strata est encore en cours de fermeture.", + "s9020": "Attendez un instant et réessayez. Si le problème persiste, redémarrez l’ordinateur.", + "s9021": "Anticipation", + "s9022": "Auto (recommandé)", + "s9023": "MTP", + "s9024": "DFlash2", + "s9025": "Anticipation : MTP (DFlash2 ne tenait pas)", + "s9026": "Anticipation : MTP (DFlash2 n’est pas disponible dans ce mode)", + "s9027": "Anticipation : MTP (DFlash2 est réservé à Qwen3.8-Flash-Next)", + "s9028": "Anticipation : MTP (le module d’anticipation DFlash2 n’est pas encore téléchargé)", + "s9029": "Choisir DFlash2 télécharge aussi son module d’anticipation : environ {0} Go, une seule fois. S’il ne tient pas dans la mémoire graphique, le modèle utilise MTP à la place.", + "s9030": "Téléchargement du module d’anticipation DFlash2…", + "s9031": "Préparation du module d’anticipation DFlash2 pour le moteur…", + "s9032": "Le module d’anticipation DFlash2 est prêt.", + "s9033": "Le module d’anticipation DFlash2 n’a pas pu être téléchargé, le modèle démarre donc avec MTP. Chargement du modèle…", + "s9034": "Chargement du modèle…", + "s9035": "Ces fichiers du modèle sont manquants : {0}.", + "s9036": "Appuyez à nouveau sur Télécharger et charger pour les récupérer. Les fichiers déjà présents sont conservés. Si les mêmes fichiers sont listés à nouveau, ouvrez Détails et partagez-les quand vous demandez de l’aide.", + "s9037": "Cette mise à jour a été interrompue au redémarrage de l’application. Une mise à jour plus récente s’est terminée, il n’y a donc rien à faire." +} diff --git a/apps/host/src/locales/gh-de.json b/apps/host/src/locales/gh-de.json new file mode 100644 index 00000000..d6a54a5a --- /dev/null +++ b/apps/host/src/locales/gh-de.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energie seit dem Start", + "gh02": "Kosten seit dem Start", + "gh03": "GPU-Lüfter", + "gh04": "GPU-Takt", + "gh05": "CPU-Temperatur", + "gh06": "SSD-Temperatur", + "gh07": "Strompreis", + "gh08": "Preis einer Kilowattstunde. Der Monitor zeigt dann, was Ihre Grafikkarte seit dem Start von Strata gekostet hat. Leer lassen, um die Kosten auszublenden.", + "gh09": "Preis pro kWh", + "gh10": "Ton, wenn Arbeit fertig ist", + "gh11": "Spielt einen kurzen Ton, wenn eine Antwort oder Aufgabe, die länger gedauert hat, fertig ist oder wenn Strata im Hintergrund läuft.", + "gh12": "Ton abspielen", + "gh13": "Benachrichtigen, wenn Strata eine Antwort braucht", + "gh14": "Zeigt im manuellen Modus eine Desktop-Benachrichtigung, wenn der Assistent auf Ihre Freigabe wartet und Strata im Hintergrund läuft.", + "gh15": "Strata braucht Ihre Antwort", + "gh16": "Der Assistent möchte {0} verwenden. Öffnen Sie Strata, um zu erlauben oder abzulehnen.", + "gh17": "ein Werkzeug", + "gh18": "In den Infobereich minimieren", + "gh19": "Beim Schließen des Fensters läuft Strata im Infobereich neben der Uhr weiter. Wählen Sie im Menü des Symbols „Beenden“, um es zu stoppen. Gilt ab dem nächsten Start von Strata.", + "gh20": "App-Port", + "gh21": "Der Port, den das Fenster und die lokale Adresse von Strata verwenden. Leer lassen, damit Strata ihn wählt (47831, wenn frei). Gilt ab dem nächsten Start von Strata.", + "gh22": "Port (leer = automatisch)", + "gh23": "Aktuell wird Port {0} verwendet.", + "gh24": "Strata konnte seinen Port nicht verwenden", + "gh25": "Port {0} wird von einem anderen Programm verwendet, daher wurde Strata auf Port {1} gestartet. Unter Port {0} gespeicherte Chats und Einstellungen werden nicht angezeigt, bis Strata ihn wieder verwenden kann. Schließen Sie das andere Programm und starten Sie Strata neu.", + "gh26": "Wählen Sie einen Port zwischen 1024 und 65535 oder lassen Sie das Feld leer.", + "gh27": "Macht alle Texte, Schaltflächen und Menüs in Strata größer oder kleiner.", + "gh28": "Energie- und Temperaturwerte", + "gh29": "pro kWh, in {0}", + "gh30": "pro kWh", + "gh31": "Währung ändern", + "gh32": "Automatisch ({0})", + "gh33": "Währung", + "gh34": "weniger als {0}" +} diff --git a/apps/host/src/locales/gh-en.json b/apps/host/src/locales/gh-en.json new file mode 100644 index 00000000..e1f12476 --- /dev/null +++ b/apps/host/src/locales/gh-en.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energy since start", + "gh02": "Cost since start", + "gh03": "GPU fan", + "gh04": "GPU clock", + "gh05": "CPU temperature", + "gh06": "SSD temperature", + "gh07": "Electricity price", + "gh08": "Price of one kilowatt-hour. The Monitor then shows what your graphics card has cost since Strata started. Leave it empty to hide the cost.", + "gh09": "Price per kWh", + "gh10": "Sound when work finishes", + "gh11": "Plays a short sound when an answer or task that took a while is finished, or when Strata is in the background.", + "gh12": "Play sound", + "gh13": "Notify me when Strata needs an answer", + "gh14": "In Manual mode, shows a desktop notification when the assistant waits for your approval and Strata is in the background.", + "gh15": "Strata needs your answer", + "gh16": "The assistant wants to use {0}. Open Strata to approve or deny.", + "gh17": "a tool", + "gh18": "Minimise to tray", + "gh19": "Closing the window keeps Strata running in the tray, next to the clock. Choose Quit in the tray menu to stop it. Applies the next time Strata starts.", + "gh20": "App port", + "gh21": "The port Strata’s window and local address use. Leave it empty to let Strata choose (47831 when it is free). Applies the next time Strata starts.", + "gh22": "Port (empty = automatic)", + "gh23": "Using port {0} now.", + "gh24": "Strata could not use its port", + "gh25": "Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.", + "gh26": "Choose a port between 1024 and 65535, or leave it empty.", + "gh27": "Makes all text, buttons and menus in Strata larger or smaller.", + "gh28": "Energy and temperature readings", + "gh29": "per kWh, in {0}", + "gh30": "per kWh", + "gh31": "Change currency", + "gh32": "Automatic ({0})", + "gh33": "Currency", + "gh34": "less than {0}" +} diff --git a/apps/host/src/locales/gh-es.json b/apps/host/src/locales/gh-es.json new file mode 100644 index 00000000..82538fef --- /dev/null +++ b/apps/host/src/locales/gh-es.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energía desde el inicio", + "gh02": "Coste desde el inicio", + "gh03": "Ventilador de la GPU", + "gh04": "Reloj de la GPU", + "gh05": "Temperatura de la CPU", + "gh06": "Temperatura del SSD", + "gh07": "Precio de la electricidad", + "gh08": "Precio de un kilovatio hora. El Monitor mostrará entonces lo que ha costado tu tarjeta gráfica desde que se inició Strata. Déjalo vacío para ocultar el coste.", + "gh09": "Precio por kWh", + "gh10": "Sonido al terminar el trabajo", + "gh11": "Reproduce un sonido breve cuando termina una respuesta o tarea que tardó un rato, o cuando Strata está en segundo plano.", + "gh12": "Reproducir sonido", + "gh13": "Avisarme cuando Strata necesite una respuesta", + "gh14": "En el modo manual, muestra una notificación de escritorio cuando el asistente espera tu aprobación y Strata está en segundo plano.", + "gh15": "Strata necesita tu respuesta", + "gh16": "El asistente quiere usar {0}. Abre Strata para aprobar o denegar.", + "gh17": "una herramienta", + "gh18": "Minimizar a la bandeja", + "gh19": "Al cerrar la ventana, Strata sigue funcionando en la bandeja, junto al reloj. Elige Salir en el menú de la bandeja para detenerlo. Se aplica la próxima vez que se inicie Strata.", + "gh20": "Puerto de la aplicación", + "gh21": "El puerto que usan la ventana y la dirección local de Strata. Déjalo vacío para que Strata elija (47831 si está libre). Se aplica la próxima vez que se inicie Strata.", + "gh22": "Puerto (vacío = automático)", + "gh23": "Ahora se usa el puerto {0}.", + "gh24": "Strata no pudo usar su puerto", + "gh25": "El puerto {0} lo usa otro programa, así que Strata se inició en el puerto {1}. Los chats y ajustes guardados en el puerto {0} no se muestran hasta que Strata pueda volver a usarlo. Cierra el otro programa y reinicia Strata.", + "gh26": "Elige un puerto entre 1024 y 65535, o déjalo vacío.", + "gh27": "Hace más grandes o más pequeños todos los textos, botones y menús de Strata.", + "gh28": "Lecturas de energía y temperatura", + "gh29": "por kWh, en {0}", + "gh30": "por kWh", + "gh31": "Cambiar moneda", + "gh32": "Automática ({0})", + "gh33": "Moneda", + "gh34": "menos de {0}" +} diff --git a/apps/host/src/locales/gh-fr.json b/apps/host/src/locales/gh-fr.json new file mode 100644 index 00000000..9d556360 --- /dev/null +++ b/apps/host/src/locales/gh-fr.json @@ -0,0 +1,36 @@ +{ + "gh01": "Énergie depuis le démarrage", + "gh02": "Coût depuis le démarrage", + "gh03": "Ventilateur du GPU", + "gh04": "Fréquence du GPU", + "gh05": "Température du CPU", + "gh06": "Température du SSD", + "gh07": "Prix de l’électricité", + "gh08": "Prix d’un kilowattheure. Le Moniteur affiche alors ce que votre carte graphique a coûté depuis le démarrage de Strata. Laissez vide pour masquer le coût.", + "gh09": "Prix par kWh", + "gh10": "Son à la fin du travail", + "gh11": "Joue un court son quand une réponse ou une tâche qui a pris du temps est terminée, ou quand Strata est en arrière-plan.", + "gh12": "Jouer le son", + "gh13": "Me prévenir quand Strata a besoin d’une réponse", + "gh14": "En mode manuel, affiche une notification sur le bureau quand l’assistant attend votre accord et que Strata est en arrière-plan.", + "gh15": "Strata a besoin de votre réponse", + "gh16": "L’assistant veut utiliser {0}. Ouvrez Strata pour accepter ou refuser.", + "gh17": "un outil", + "gh18": "Réduire dans la zone de notification", + "gh19": "Fermer la fenêtre garde Strata actif dans la zone de notification, près de l’horloge. Choisissez Quitter dans le menu de l’icône pour l’arrêter. S’applique au prochain démarrage de Strata.", + "gh20": "Port de l’application", + "gh21": "Le port que la fenêtre et l’adresse locale de Strata utilisent. Laissez vide pour que Strata choisisse (47831 s’il est libre). S’applique au prochain démarrage de Strata.", + "gh22": "Port (vide = automatique)", + "gh23": "Port {0} utilisé en ce moment.", + "gh24": "Strata n’a pas pu utiliser son port", + "gh25": "Le port {0} est utilisé par un autre programme, donc Strata a démarré sur le port {1}. Les conversations et réglages enregistrés sur le port {0} ne s’affichent pas tant que Strata ne peut pas le réutiliser. Fermez l’autre programme et relancez Strata.", + "gh26": "Choisissez un port entre 1024 et 65535, ou laissez vide.", + "gh27": "Agrandit ou réduit tous les textes, boutons et menus de Strata.", + "gh28": "Relevés d’énergie et de température", + "gh29": "par kWh, en {0}", + "gh30": "par kWh", + "gh31": "Changer de devise", + "gh32": "Automatique ({0})", + "gh33": "Devise", + "gh34": "moins de {0}" +} diff --git a/apps/host/src/locales/gh-ja.json b/apps/host/src/locales/gh-ja.json new file mode 100644 index 00000000..55229a69 --- /dev/null +++ b/apps/host/src/locales/gh-ja.json @@ -0,0 +1,36 @@ +{ + "gh01": "起動後の消費電力量", + "gh02": "起動後の電気代", + "gh03": "GPU ファン", + "gh04": "GPU クロック", + "gh05": "CPU 温度", + "gh06": "SSD 温度", + "gh07": "電気料金", + "gh08": "1キロワット時あたりの料金です。モニターに、Strata の起動後にグラフィックスカードが使った電気代が表示されます。空欄のままなら電気代は表示されません。", + "gh09": "1 kWh あたりの料金", + "gh10": "作業完了時の音", + "gh11": "回答や時間のかかった作業が終わったとき、または Strata がバックグラウンドにあるときに、短い音を鳴らします。", + "gh12": "音を鳴らす", + "gh13": "Strata の返答が必要なときに通知する", + "gh14": "手動モードで、アシスタントが承認を待っていて Strata がバックグラウンドにあるときに、デスクトップ通知を表示します。", + "gh15": "Strata があなたの返答を待っています", + "gh16": "アシスタントが {0} を使おうとしています。Strata を開いて承認または拒否してください。", + "gh17": "ツール", + "gh18": "トレイに最小化", + "gh19": "ウィンドウを閉じても、Strata は時計の横のトレイで動き続けます。止めるには、トレイのメニューで「終了」を選びます。次に Strata を起動したときから有効になります。", + "gh20": "アプリのポート", + "gh21": "Strata のウィンドウとローカルアドレスが使うポートです。空欄なら Strata が選びます(空いていれば 47831)。次に Strata を起動したときから有効になります。", + "gh22": "ポート(空欄 = 自動)", + "gh23": "現在のポートは {0} です。", + "gh24": "Strata は指定のポートを使えませんでした", + "gh25": "ポート {0} は別のプログラムが使っているため、Strata はポート {1} で起動しました。ポート {0} に保存されたチャットと設定は、Strata が再びそのポートを使えるようになるまで表示されません。他のプログラムを閉じて Strata を再起動してください。", + "gh26": "1024 から 65535 の間のポートを選ぶか、空欄にしてください。", + "gh27": "Strata のすべての文字、ボタン、メニューを大きくしたり小さくしたりします。", + "gh28": "消費電力量と温度の値", + "gh29": "1 kWh あたり、通貨は {0}", + "gh30": "1 kWh あたり", + "gh31": "通貨を変更", + "gh32": "自動({0})", + "gh33": "通貨", + "gh34": "{0} 未満" +} diff --git a/apps/host/src/locales/gh-ko.json b/apps/host/src/locales/gh-ko.json new file mode 100644 index 00000000..24decc86 --- /dev/null +++ b/apps/host/src/locales/gh-ko.json @@ -0,0 +1,36 @@ +{ + "gh01": "시작 이후 에너지", + "gh02": "시작 이후 비용", + "gh03": "GPU 팬", + "gh04": "GPU 클럭", + "gh05": "CPU 온도", + "gh06": "SSD 온도", + "gh07": "전기 요금", + "gh08": "1킬로와트시의 요금입니다. 모니터에 Strata를 시작한 뒤 그래픽 카드에 든 전기 요금이 표시됩니다. 비워 두면 비용을 표시하지 않습니다.", + "gh09": "kWh당 요금", + "gh10": "작업이 끝났을 때 소리", + "gh11": "답변이나 오래 걸린 작업이 끝났을 때, 또는 Strata가 백그라운드에 있을 때 짧은 소리를 재생합니다.", + "gh12": "소리 재생", + "gh13": "Strata가 답을 필요로 할 때 알림", + "gh14": "수동 모드에서 어시스턴트가 승인을 기다리고 Strata가 백그라운드에 있을 때 데스크톱 알림을 표시합니다.", + "gh15": "Strata가 답을 기다리고 있습니다", + "gh16": "어시스턴트가 {0}을(를) 사용하려고 합니다. Strata를 열어 승인하거나 거부하세요.", + "gh17": "도구", + "gh18": "트레이로 최소화", + "gh19": "창을 닫아도 Strata는 시계 옆 트레이에서 계속 실행됩니다. 끝내려면 트레이 메뉴에서 '종료'를 선택하세요. 다음에 Strata를 시작할 때부터 적용됩니다.", + "gh20": "앱 포트", + "gh21": "Strata의 창과 로컬 주소가 사용하는 포트입니다. 비워 두면 Strata가 고릅니다(비어 있으면 47831). 다음에 Strata를 시작할 때부터 적용됩니다.", + "gh22": "포트(비움 = 자동)", + "gh23": "지금은 포트 {0}을(를) 사용 중입니다.", + "gh24": "Strata가 지정한 포트를 사용할 수 없었습니다", + "gh25": "포트 {0}을(를) 다른 프로그램이 사용 중이어서 Strata는 포트 {1}에서 시작했습니다. 포트 {0}에 저장된 채팅과 설정은 Strata가 다시 그 포트를 쓸 수 있을 때까지 표시되지 않습니다. 다른 프로그램을 닫고 Strata를 다시 시작하세요.", + "gh26": "1024에서 65535 사이의 포트를 고르거나 비워 두세요.", + "gh27": "Strata의 모든 글자, 버튼, 메뉴를 더 크게 또는 더 작게 만듭니다.", + "gh28": "에너지 및 온도 측정값", + "gh29": "kWh당, 통화 {0}", + "gh30": "kWh당", + "gh31": "통화 변경", + "gh32": "자동({0})", + "gh33": "통화", + "gh34": "{0} 미만" +} diff --git a/apps/host/src/locales/gh-pt.json b/apps/host/src/locales/gh-pt.json new file mode 100644 index 00000000..ad331c49 --- /dev/null +++ b/apps/host/src/locales/gh-pt.json @@ -0,0 +1,36 @@ +{ + "gh01": "Energia desde o início", + "gh02": "Custo desde o início", + "gh03": "Ventoinha da GPU", + "gh04": "Clock da GPU", + "gh05": "Temperatura da CPU", + "gh06": "Temperatura do SSD", + "gh07": "Preço da eletricidade", + "gh08": "Preço de um quilowatt-hora. O Monitor passa a mostrar quanto a sua placa de vídeo custou desde que o Strata iniciou. Deixe vazio para ocultar o custo.", + "gh09": "Preço por kWh", + "gh10": "Som ao terminar o trabalho", + "gh11": "Toca um som curto quando uma resposta ou tarefa que demorou termina, ou quando o Strata está em segundo plano.", + "gh12": "Tocar som", + "gh13": "Avisar quando o Strata precisar de uma resposta", + "gh14": "No modo manual, mostra uma notificação na área de trabalho quando o assistente espera sua aprovação e o Strata está em segundo plano.", + "gh15": "O Strata precisa da sua resposta", + "gh16": "O assistente quer usar {0}. Abra o Strata para aprovar ou negar.", + "gh17": "uma ferramenta", + "gh18": "Minimizar para a bandeja", + "gh19": "Ao fechar a janela, o Strata continua em execução na bandeja, ao lado do relógio. Escolha Sair no menu da bandeja para encerrá-lo. Vale a partir da próxima vez que o Strata iniciar.", + "gh20": "Porta do aplicativo", + "gh21": "A porta usada pela janela e pelo endereço local do Strata. Deixe vazio para o Strata escolher (47831 quando estiver livre). Vale a partir da próxima vez que o Strata iniciar.", + "gh22": "Porta (vazio = automático)", + "gh23": "Usando a porta {0} agora.", + "gh24": "O Strata não conseguiu usar a sua porta", + "gh25": "A porta {0} está em uso por outro programa, então o Strata iniciou na porta {1}. Os chats e as configurações salvos na porta {0} não aparecem até o Strata poder usá-la de novo. Feche o outro programa e reinicie o Strata.", + "gh26": "Escolha uma porta entre 1024 e 65535, ou deixe vazio.", + "gh27": "Deixa todos os textos, botões e menus do Strata maiores ou menores.", + "gh28": "Leituras de energia e temperatura", + "gh29": "por kWh, em {0}", + "gh30": "por kWh", + "gh31": "Alterar moeda", + "gh32": "Automática ({0})", + "gh33": "Moeda", + "gh34": "menos de {0}" +} diff --git a/apps/host/src/locales/gh-ru.json b/apps/host/src/locales/gh-ru.json new file mode 100644 index 00000000..51e56bf8 --- /dev/null +++ b/apps/host/src/locales/gh-ru.json @@ -0,0 +1,36 @@ +{ + "gh01": "Энергия с запуска", + "gh02": "Стоимость с запуска", + "gh03": "Вентилятор GPU", + "gh04": "Частота GPU", + "gh05": "Температура CPU", + "gh06": "Температура SSD", + "gh07": "Цена электричества", + "gh08": "Цена одного киловатт-часа. Тогда монитор покажет, во сколько видеокарта обошлась с запуска Strata. Оставьте поле пустым, чтобы скрыть стоимость.", + "gh09": "Цена за кВт·ч", + "gh10": "Звук по окончании работы", + "gh11": "Проигрывает короткий звук, когда закончился долгий ответ или задача, а также когда Strata работает в фоне.", + "gh12": "Проиграть звук", + "gh13": "Уведомлять, когда Strata нужен ответ", + "gh14": "В ручном режиме показывает уведомление на рабочем столе, когда помощник ждёт вашего подтверждения, а Strata работает в фоне.", + "gh15": "Strata нужен ваш ответ", + "gh16": "Помощник хочет использовать {0}. Откройте Strata, чтобы разрешить или отклонить.", + "gh17": "инструмент", + "gh18": "Сворачивать в трей", + "gh19": "При закрытии окна Strata продолжает работать в трее рядом с часами. Чтобы остановить её, выберите «Выход» в меню значка. Действует со следующего запуска Strata.", + "gh20": "Порт приложения", + "gh21": "Порт, который используют окно и локальный адрес Strata. Оставьте поле пустым, чтобы Strata выбрала сама (47831, если свободен). Действует со следующего запуска Strata.", + "gh22": "Порт (пусто = автоматически)", + "gh23": "Сейчас используется порт {0}.", + "gh24": "Strata не смогла использовать свой порт", + "gh25": "Порт {0} занят другой программой, поэтому Strata запустилась на порту {1}. Чаты и настройки, сохранённые на порту {0}, не показываются, пока Strata не сможет снова его использовать. Закройте другую программу и перезапустите Strata.", + "gh26": "Выберите порт от 1024 до 65535 или оставьте поле пустым.", + "gh27": "Увеличивает или уменьшает весь текст, кнопки и меню в Strata.", + "gh28": "Показания энергии и температуры", + "gh29": "за кВт·ч, в валюте {0}", + "gh30": "за кВт·ч", + "gh31": "Сменить валюту", + "gh32": "Автоматически ({0})", + "gh33": "Валюта", + "gh34": "меньше {0}" +} diff --git a/apps/host/src/locales/gh-zh.json b/apps/host/src/locales/gh-zh.json new file mode 100644 index 00000000..eaa5e8fc --- /dev/null +++ b/apps/host/src/locales/gh-zh.json @@ -0,0 +1,36 @@ +{ + "gh01": "启动以来的能耗", + "gh02": "启动以来的费用", + "gh03": "GPU 风扇", + "gh04": "GPU 频率", + "gh05": "CPU 温度", + "gh06": "SSD 温度", + "gh07": "电价", + "gh08": "每千瓦时的价格。监控页会据此显示 Strata 启动以来显卡用电的费用。留空则不显示费用。", + "gh09": "每千瓦时价格", + "gh10": "工作完成时的提示音", + "gh11": "回答或耗时较长的任务完成时,或 Strata 在后台时,播放一段简短的提示音。", + "gh12": "播放提示音", + "gh13": "Strata 需要您答复时通知我", + "gh14": "在手动模式下,当助手等待您批准而 Strata 在后台时,显示桌面通知。", + "gh15": "Strata 需要您的答复", + "gh16": "助手想使用 {0}。打开 Strata 以批准或拒绝。", + "gh17": "一个工具", + "gh18": "最小化到托盘", + "gh19": "关闭窗口后,Strata 会继续在托盘(时钟旁边)运行。要停止它,请在托盘菜单中选择“退出”。下次启动 Strata 时生效。", + "gh20": "应用端口", + "gh21": "Strata 窗口和本地地址使用的端口。留空则由 Strata 自行选择(空闲时为 47831)。下次启动 Strata 时生效。", + "gh22": "端口(留空 = 自动)", + "gh23": "当前使用端口 {0}。", + "gh24": "Strata 无法使用它的端口", + "gh25": "端口 {0} 已被其他程序占用,因此 Strata 改用端口 {1} 启动。在端口 {0} 上保存的聊天和设置在 Strata 能再次使用该端口之前不会显示。请关闭其他程序并重新启动 Strata。", + "gh26": "请选择 1024 到 65535 之间的端口,或留空。", + "gh27": "让 Strata 中的所有文字、按钮和菜单变大或变小。", + "gh28": "能耗和温度读数", + "gh29": "每千瓦时,币种 {0}", + "gh30": "每千瓦时", + "gh31": "更改货币", + "gh32": "自动({0})", + "gh33": "货币", + "gh34": "不足 {0}" +} diff --git a/apps/host/src/locales/tools-fr.json b/apps/host/src/locales/tools-fr.json new file mode 100644 index 00000000..5d12b6d9 --- /dev/null +++ b/apps/host/src/locales/tools-fr.json @@ -0,0 +1,6 @@ +{ + "tl01": "Utilisez un nom de serveur simple de 32 caractères maximum : lettres, chiffres, tirets ou tirets bas.", + "tl02": "Ces serveurs d’outils ont été laissés de côté car leurs noms ne sont pas autorisés : {0}. Un nom peut contenir jusqu’à 32 lettres, chiffres, tirets ou tirets bas.", + "tl03": "Ces serveurs d’outils ont été laissés de côté car ils n’ont ni programme ni adresse web : {0}.", + "tl04": "Ces serveurs d’outils ont été laissés de côté car un autre a presque le même nom : {0}." +} diff --git a/apps/host/src/locales/tune-fr.json b/apps/host/src/locales/tune-fr.json new file mode 100644 index 00000000..6f81ceb2 --- /dev/null +++ b/apps/host/src/locales/tune-fr.json @@ -0,0 +1,45 @@ +{ + "tune01": "Optimiser ce modèle", + "tune02": "Recherche des réglages les plus rapides pour votre PC…", + "tune03": "environ {0} min restantes", + "tune04": "Cela prend environ 20 minutes.", + "tune05": "Arrêté. Vos réglages n’ont pas été modifiés.", + "tune06": "L’optimisation n’est pas terminée. Vos réglages n’ont pas été modifiés.", + "tune07": "Toujours aussi rapide qu’à l’enregistrement.", + "tune08": "C’est plus lent qu’avant. Vous pouvez optimiser à nouveau.", + "tune09": "Impossible de savoir pour l’instant. Votre optimisation a été conservée.", + "tune10": "Réponses {0} % plus rapides, enregistré sous « {1} »", + "tune11": "Vos réglages actuels sont déjà les plus rapides que nous ayons trouvés.", + "tune12": "Rien n’a été modifié.", + "tune13": "Enregistré sous « {0} », il ne sera donc pas réoptimisé à la réouverture de l’application.", + "tune14": "Vitesse : {0} → {1} tok/s", + "tune15": "Les réponses sont identiques à la configuration standard.", + "tune16": "Les réponses peuvent différer légèrement de la configuration standard.", + "tune17": "Les réponses ne sont pas reproductibles d’une exécution à l’autre.", + "tune18": "Comprend un réglage de qualité qui modifie les chiffres.", + "tune19": "Optimisation enregistrée utilisée : {0}", + "tune20": "Réponses {0} % plus rapides", + "tune21": "Ce PC a changé depuis l’optimisation, ces réglages ne sont donc pas utilisés tant que vous n’optimisez pas à nouveau.", + "tune22": "Ce PC ou le moteur a changé depuis l’optimisation. Une vérification courte prend environ 2 minutes.", + "tune23": "Pas encore d’optimisation enregistrée pour ces choix.", + "tune24": "Strata essaie différents réglages sur ce PC et garde ceux qui accélèrent les réponses. Votre modèle est déchargé pendant ce temps, et l’ordinateur sera occupé.", + "tune25": "Terminez d’abord l’opération en cours.", + "tune26": "Durée à y consacrer", + "tune27": "Rapide (environ 20 minutes)", + "tune28": "Approfondie (jusqu’à 2 heures)", + "tune29": "Ce que vous faites surtout", + "tune30": "Programmation avec de longs prompts", + "tune31": "Autoriser les réglages qui changent très légèrement les réponses (même qualité)", + "tune32": "Optimisations enregistrées", + "tune33": "Utilisée", + "tune34": "Utiliser", + "tune35": "Optimiser à nouveau", + "tune36": "Lancer l’optimisation", + "tune37": "Optimisation de votre modèle", + "tune38": "Les réponses peuvent différer d’une exécution à l’autre sur ce PC même avec la configuration standard ; ce réglage n’y ajoute rien.", + "tune39": "Utilisation de votre optimisation « {0} »", + "tune40": "Désactiver", + "tune41": "Activer", + "tune42": "Votre optimisation est désactivée. Les réglages standard sont utilisés.", + "tune43": "Votre PC était occupé, les mesures n’étaient donc pas fiables. Rien n’a été modifié. Réessayez quand il est au calme." +} diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 97dc34f2..46075fab 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -40,6 +40,7 @@ import { composerCap, scrollBehavior } from '../lib/responsive'; import { relTime, cx, duration, tokens, tps } from '../lib/format'; import { createSubagentExample, pushToast, setPreviewTabClosed, branchFrom, continueLast, markRead, resolveTool, retryLast, selectSession, rewindTo, sendMessage, stopStreaming, useStore, } from '../lib/store'; import { copyText } from '../lib/clipboard'; +import { KEYS_UP, PILL_DISTANCE, distanceFromBottom, followAfterScroll, wheelLeavesBottom } from '../lib/follow-scroll'; import { getSlashCommands } from '../lib/commands'; import { useLocation } from '../lib/router'; import { composerSends } from '../lib/shortcut-bindings'; @@ -212,6 +213,9 @@ export function ChatScreen() { }, [streaming]); /** Whether the reader is following the newest message rather than reading back. */ const pinned = useRef(true); + /** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */ + const readerInput = useRef(0); + const seenMessages = useRef(0); /** * Scrolls to the newest message and stays there. * @@ -266,8 +270,13 @@ export function ChatScreen() { const el = scroller.current; if (!el || (session?.showcase && !streaming)) return; - const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 120; - if (nearBottom) + // The reader's own scrolling decides (#4014): a wheel notch is about 100 px and used to land inside a 120 px band that pulled + // the view back on every token. `pinned` is set by the scroller's wheel, touch, key and scroll handlers below. + const count = session?.messages.length ?? 0; + const sent = count > seenMessages.current && session?.messages.at(-1)?.role === 'user'; + seenMessages.current = count; + // Sending a message always brings the reader to it, as it did before; only the answer's growth waits for the reader. + if (pinned.current || sent) scrollToLatest(); }, [session?.messages.length, session?.messages.at(-1)?.content, scrollToLatest]); // Scroll position is remembered per conversation, so returning to one puts you @@ -421,9 +430,17 @@ export function ChatScreen() { // the way back is worth offering. // The threshold has to tolerate the height estimate moving under // us, or the pill flickers as turns render during a scroll. - const away = el.scrollHeight - el.scrollTop - el.clientHeight > 400; - pinned.current = !away; - setAwayFromBottom(away); + const distance = distanceFromBottom(el); + pinned.current = followAfterScroll(distance, pinned.current, Date.now() - readerInput.current); + setAwayFromBottom(distance > PILL_DISTANCE); + }} onWheel={(e) => { + readerInput.current = Date.now(); + if (wheelLeavesBottom(e.deltaY) && e.currentTarget.scrollTop > 0) + pinned.current = false; + }} onTouchMove={() => { readerInput.current = Date.now(); }} onPointerDown={() => { readerInput.current = Date.now(); }} onKeyDown={(e) => { + readerInput.current = Date.now(); + if (KEYS_UP.has(e.key) && e.target === e.currentTarget && e.currentTarget.scrollTop > 0) + pinned.current = false; }}>
diff --git a/apps/host/src/screens/Monitor.tsx b/apps/host/src/screens/Monitor.tsx index 87cd4f58..d75db79a 100644 --- a/apps/host/src/screens/Monitor.tsx +++ b/apps/host/src/screens/Monitor.tsx @@ -2,7 +2,7 @@ import {localeTag} from '../lib/i18n'; import { tr } from '../lib/i18n'; import { scopedMonitor, instanceLabel, deviceLabel } from '../lib/runtime-models'; /** The original Strata dashboard, adapted to the current shell and device inventory. */ -import { useRef, useState, type ReactNode } from 'react'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; import { flushSync } from 'react-dom'; import { SnapshotDialog } from '../components/SnapshotDialog'; import { requestSummary } from '../lib/monitor-summary'; @@ -14,6 +14,8 @@ import { Screen } from '../components/layout'; import { contextLabel, duration, tokens, tps } from '../lib/format'; import { defaultGpuSet, gpuCapacity, gpuId, gpuMetric, gpuReported, hasReading, shortGpuName } from '../lib/monitor-hardware'; import { useStore } from '../lib/store'; +import { api } from '../lib/client'; +import { useMoney } from '../lib/money'; import { useKept } from '../lib/kept-state'; import type { Hardware, MonitorState, ServeRequest } from '../lib/types'; import { useNative, nativeRouting, type NativeState } from '../lib/native'; @@ -57,12 +59,21 @@ function requestStatus(request: ServeRequest) { } export function MonitorScreen() { const native = useNative(); + // While this screen is open and visible the host reads the graphics card every 3 s; otherwise it asks only every 30 s (#4066). + useEffect(() => { + const ask = () => { if (typeof document === 'undefined' || document.visibilityState !== 'hidden') + void api.get('/api/monitor').catch(() => undefined); }; + ask(); + const timer = setInterval(ask, 10000); + return () => clearInterval(timer); + }, []); return ; } function LegacyMonitorScreen({ native }: { native: NativeState | null; }) { const storedLive = useStore(s => s.monitor), inventory = useStore(s => s.hardware); + const electricityPrice = useStore(s => s.electricityPrice), money = useMoney(); const storedRuntime = useStore(s => s.runtime), serving = useStore(s => s.serving); const [instanceSelection, setInstanceSelection] = useState('all'); const routing = native ? nativeRouting(native, inventory) : null; @@ -137,6 +148,16 @@ function LegacyMonitorScreen({ native }: { const cacheMemory = cacheKnown ? data.expertCache.memoryGb : null; const cachePercent = hasReading(cacheMemory) ? percent(cacheMemory, gpuCapacity(defaultDevices)) : cacheKnown ? percent(data.expertCache.used, data.expertCache.total) : null; const ramPct = percent(data.hardware.ramUsedGb, data.hardware.ramTotalGb); + // The readings strip under the cards: what the GPU used and cost since Strata started, the fan and clock, and the temperatures this PC can give. + const energyWh = data.hardware.energyWh, fan = gpuValue('fanPct', 'max'), clock = gpuValue('clockMhz', 'max'); + const readingsStrip = [ + hasReading(energyWh) ? { label: 'Energy since start', value: energyWh >= 1000 ? `${number(energyWh / 1000, 2)} kWh` : `${number(energyWh, 1)} Wh` } : null, + hasReading(energyWh) && electricityPrice > 0 ? { label: 'Cost since start', value: money.format(energyWh / 1000 * electricityPrice) } : null, + hasReading(fan) ? { label: 'GPU fan', value: `${number(fan)} %` } : null, + hasReading(clock) ? { label: 'GPU clock', value: `${number(clock)} MHz` } : null, + hasReading(data.hardware.cpuTempC) ? { label: 'CPU temperature', value: `${number(data.hardware.cpuTempC)} °C` } : null, + hasReading(data.hardware.ssdTempC) ? { label: 'SSD temperature', value: `${number(data.hardware.ssdTempC)} °C` } : null, + ].filter((line): line is { label: string; value: string } => line !== null); const history = data.history, timestamps = history.map(s => s.t); const historyGpu = (key: Parameters[2], fallback: 'gpuLoad' | 'vramUsedGb' | 'gpuTempC' | 'powerW' | 'pcieRxMbs', mode: Parameters[3] = 'sum') => history.map(sample => sample.gpus ? gpuMetric(selectedGpus, sample.gpus, key, mode) : (sample.gpuIds ? selectedGpus.length === sample.gpuIds.length && selectedGpus.every(gpu => sample.gpuIds!.includes(gpuId(gpu))) : gpuChoice === 'all') ? sample[fallback] : null); const historyCpu = history.map(sample => cpuChoice === 'all' ? sample.cpuLoad : sample.cpus?.find(p => p.id === cpuChoice)?.utilizationPct); @@ -175,6 +196,7 @@ function LegacyMonitorScreen({ native }: { = 1 ? data.hardware.diskReadGbs : data.hardware.diskReadGbs * 1024 : null, 1)} unit={hasReading(data.hardware.diskReadGbs) ? data.hardware.diskReadGbs >= 1 ? 'GB/s' : 'MB/s' : ''} source={hasReading(data.hardware.diskReadGbs) ? 'Measured' : 'Unavailable'} sub={hasReading(data.hardware.diskWriteMbs) ? `Write ${number(data.hardware.diskWriteMbs, 1)} MB/s` : 'Read throughput'} chart={chart('Disk read', history.map(s => hasReading(s.diskReadGbs) ? s.diskReadGbs * 1024 : null), 'MB/s', undefined, 'var(--st-info)')}/>
+ {tr(readingsStrip.length ?
{readingsStrip.map(item =>
{tr(item.label)}
{item.value}
)}
: null)}

{tr("Context fill")}

1 ? 'Select a model to see context' : 'No recorded request usage'}/>
{tr("Experts in VRAM")}{tr(cacheKnown ? `${number(data.expertCache.used)}${hasReading(cacheMemory) ? ` · ${number(cacheMemory, 1)} GB` : ''}` : '—')}
diff --git a/apps/host/src/screens/Settings.tsx b/apps/host/src/screens/Settings.tsx index a14854f2..0361d712 100644 --- a/apps/host/src/screens/Settings.tsx +++ b/apps/host/src/screens/Settings.tsx @@ -10,12 +10,15 @@ import { PrivacyNotes } from '../components/PrivacyNotes'; import { AboutVersions, SettingsUpdates } from '../components/SettingsUpdates'; import { NativeOperations } from '../components/NativeOperations'; import { FontChoice } from '../components/FontChoice'; +import { ElectricityPrice } from '../components/ElectricityPrice'; +import { ApprovalNotifySetting, DoneSoundSetting, PortSetting, TraySetting, useShellState } from '../components/ShellSettings'; import { LANGUAGES } from '../lib/i18n'; import { setLanguage } from '../lib/store'; import { CONTENT_FONT_RANGE, setContentFontSize, setDensity, setFocus, setMotion, setShortcuts, setTheme, setTransparency, setUiScale, UI_SCALES, useStore, setSettingsSection } from '../lib/store'; const PANELS = [{ name: 'Appearance', icon: 'sun', sections: ['General', 'Reading & focus'] }, { name: 'Models', icon: 'models', sections: [] }, { name: 'Tools', icon: 'tool', sections: [] }, { name: 'Storage', icon: 'disk', sections: ['Storage'] }, { name: 'Engine', icon: 'engine', sections: [] }, { name: 'About', icon: 'info', sections: ['About', 'Update', 'Privacy'] }] as const; export function SettingsScreen() { const prefs = useStore(s => s); + const [shell, saveShell] = useShellState(); const active = prefs.settingsSection; const scrollRef = useRef(null); const fields: { @@ -26,11 +29,16 @@ export function SettingsScreen() { control: ReactNode; }[] = [ { section: 'General', label: 'Language', hint: 'Choose the language used throughout Strata.', control: }, { section: 'Reading & focus', label: 'Reading size', hint: 'Conversation text size. Interface controls stay separate.', aliases: 'font text zoom', control: }, - { section: 'Reading & focus', label: 'Interface size', hint: 'Scale navigation and controls.', aliases: 'zoom scale 90% 100% 110% 125%', control: ({ value: String(v), label: `${Math.round(v * 100)}%` }))} onChange={v => setUiScale(Number(v))}/> }, { section: 'Reading & focus', label: 'Spacing', hint: 'Comfortable spacing by default.', aliases: 'density comfortable compact', control: }, { section: 'Reading & focus', label: 'Transparency', hint: 'Translucent controls or solid surfaces. Text stays opaque.', aliases: 'blur glass liquid opaque translucent', control: JSON.parse(read(`../src/locales/fix-${lang}.json`)); const words = [...SPEED_SWITCHES.flatMap(s => [s.label, s.hint]), 'On (recommended)', 'Off (recommended)']; const english = Object.values(catalog('en')); diff --git a/apps/host/tests/tools-locales.test.mjs b/apps/host/tests/tools-locales.test.mjs index 294ddb7a..fe11434e 100644 --- a/apps/host/tests/tools-locales.test.mjs +++ b/apps/host/tests/tools-locales.test.mjs @@ -5,7 +5,7 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { build } from 'esbuild'; -const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tools-${l}.json`, 'utf8'))]))); const main = JSON.parse(await readFile('src/locales/en.json', 'utf8')); const tune = JSON.parse(await readFile('src/locales/tune-en.json', 'utf8')); diff --git a/apps/host/tests/tune-locales.test.mjs b/apps/host/tests/tune-locales.test.mjs index ed52eccd..4f43a9c3 100644 --- a/apps/host/tests/tune-locales.test.mjs +++ b/apps/host/tests/tune-locales.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { build } from 'esbuild'; -const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']; +const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']; const catalogs = Object.fromEntries(await Promise.all(languages.map(async l => [l, JSON.parse(await readFile(`src/locales/tune-${l}.json`, 'utf8'))]))); const main = JSON.parse(await readFile('src/locales/en.json', 'utf8')); const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort(); diff --git a/apps/host/tests/web-ask.test.mjs b/apps/host/tests/web-ask.test.mjs index 287afdf8..d16c8abf 100644 --- a/apps/host/tests/web-ask.test.mjs +++ b/apps/host/tests/web-ask.test.mjs @@ -162,13 +162,13 @@ test('the profile names the search service in the gate\'s question, and carries // ---------------------------------------------------------------------------------------------- the words, in every language -test('the card text and the Settings switch exist in all eight languages', async () => { +test('the card text and the Settings switch exist in all nine languages', async () => { const compiled = await build({ stdin: { contents: "export * from './src/lib/i18n';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' }); const { tr, setTranslationLanguage } = await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`); const search = manualDecision(SEARCH, { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy' }).reason; const open = manualDecision(FETCH).reason; const english = [search, open, 'Let the assistant search the web without asking']; - for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko']) { + for (const language of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { setTranslationLanguage(language); for (const text of english) assert.notEqual(tr(text), text, `${language}: ${text}`); const translated = tr(search); diff --git a/chat.py b/chat.py index 124c7278..668e18a0 100644 --- a/chat.py +++ b/chat.py @@ -18,6 +18,8 @@ import sys import time import urllib.request +from highlight import StreamHighlighter + def stream(url, messages, think, max_tokens): body = {"model": "strata", "messages": messages, "stream": True, "max_tokens": max_tokens, @@ -43,6 +45,7 @@ def main() -> int: a = ap.parse_args() url = f"http://{a.host}:{a.port}/v1/chat/completions" gray, reset = ("\033[90m", "\033[0m") if sys.stdout.isatty() else ("", "") + hl = StreamHighlighter(color=sys.stdout.isatty()) messages, pending = [], [] think = "none" if a.no_think else a.think print(f"Strata chat ({url}). /image = attach a picture, /think none|low|medium|high (now: {think}), " @@ -98,11 +101,14 @@ def main() -> int: if in_think: print(reset + "\n", end="") in_think = False - print(content, end="", flush=True) + print(hl.feed(content), end="", flush=True) answer.append(content) n += 1 if in_think: print(reset, end="") + out = hl.flush() + if out: + print(out, end="") except OSError as e: print(f"\n(could not reach the server at {url}: {e})") messages.pop() diff --git a/cmake/ggml_tq_overlay_test.cmake b/cmake/ggml_tq_overlay_test.cmake index e56604c8..ca637e5f 100644 --- a/cmake/ggml_tq_overlay_test.cmake +++ b/cmake/ggml_tq_overlay_test.cmake @@ -1,6 +1,8 @@ # cmake -DLLAMA= -DOUT= -P cmake/ggml_tq_overlay_test.cmake # The trellis MMQ overlay on a pinned llama.cpp: it generates, every copied header is the pinned one except the patched # ones, and the patched ones only gain lines (TQ routing, three externs, config copies of IQ2_XS's). +# a -P script has no cmake_minimum_required, so CMake 3.x applies the OLD CMP0057 and IN_LIST below is not an operator (#3412) +cmake_policy(SET CMP0057 NEW) get_filename_component(CMAKE_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/.." ABSOLUTE) include(${CMAKE_CURRENT_LIST_DIR}/strata_ggml_tq_overlay.cmake) file(REMOVE_RECURSE "${OUT}") diff --git a/docker/build.sh b/docker/build.sh index bba83ff2..3048b8bc 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -61,14 +61,17 @@ commit=${STRATA_BUILD_COMMIT:-$(git -C "$repo" rev-parse HEAD 2>/dev/null || tru case "$commit" in *[!0-9a-f]*|"") commit="" ;; esac # 1. the Terminal's sources: exactly what packaging/package_terminal.py copies (the working tree, so local edits are in the image) +# tools/: every .py at any depth, because the bundle's DeepSeek scripts are nested (INSTALLER_SCRIPTS in package_terminal.py names dsv41/*: +# the Dockerfile's terminal stage stops at "installer tool missing: tools/dsv41/tune.py" when only the top-level modules are in the context) cd "$repo" paths="packaging bin strata.py strata_control strata_cli serve requirements.txt requirements-monitor.txt docs/MANAGEMENT_PROTOCOL.md docs/TERMINAL_LAUNCH.md data bench/prompts/standard-v1 setup.py ref/load.py CMakeLists.txt" if git rev-parse --git-dir >/dev/null 2>&1; then # shellcheck disable=SC2086 - { git ls-files -z -- $paths ':(glob)tools/*.py'; } | tar --null -T - -cf - | tar -xf - -C "$ctx/terminal-src" + { git ls-files -z -- $paths ':(glob)tools/**/*.py'; } | tar --null -T - -cf - | tar -xf - -C "$ctx/terminal-src" else + tools_py=$(find tools -name '*.py') # nested too: the bundle's dsv41 scripts live in tools/dsv41/ # shellcheck disable=SC2086 - tar -cf - --exclude='__pycache__' $paths tools/*.py | tar -xf - -C "$ctx/terminal-src" + tar -cf - --exclude='__pycache__' $paths $tools_py | tar -xf - -C "$ctx/terminal-src" fi # 2. the engine package(s): hard-linked when on the same file system (no second copy of GBs), copied otherwise diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 6b6f87cf..f5476e3a 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -10,6 +10,7 @@ # MODEL model size, e.g. IQ3_XXS, Q2_0 (empty: Strata picks one for this card and says so) # FAMILY model family when a size is offered by several (qwen, swift, coder, ...) # MODEL_PATH GGUF files you already have, a folder or one .gguf, inside the container (mount it read-only) +# ALLOW_DOWNLOAD 1: go on and download the model although model files of the older layout (/data/models) were left unread (default: stop) # CONTEXT 32k, 64k, 128k, 256k or a number of tokens # PARALLEL requests answered at the same time, 1 to 8 (empty: fit to the card) # VISION off | on | gpu | cpu (pictures; the picture reader file is downloaded with the model) @@ -38,6 +39,17 @@ warn() { printf '[!] %s\n' "$*" >&2; } die() { printf '[X] %s\n' "$*" >&2; exit "${2:-1}"; } phase() { printf '%s\n' "$1" > "$PHASE_FILE" 2>/dev/null || true; } +# Model files of the older layout that this image did not move (a folder you mounted at /data/models, or a move that failed) are not read here, and +# the start would download the model again. Say so and stop instead (#3421); ALLOW_DOWNLOAD=1 goes on, with the same text as a warning. +# $1: MODEL_PATH (when it is set the files are named and nothing is lost), $2: the older models folder. +legacy_models_guard() { + [ -n "$1" ] && return 0 + stuck=$(find "$2" -maxdepth 3 -name '*.gguf' 2>/dev/null | head -1) + [ -n "$stuck" ] || return 0 + msg="There are model files in ${stuck%/*} (the older image's place). This image keeps its models in /data/Strata-data/models and does not read them there, so it would download the model again (tens of GB). To use them: mount that folder read-only and set MODEL_PATH to the folder that holds the shards (docs/DOCKER.md, \"Files you already have\"), or put them in /data/Strata-data/models//. To download anyway: set ALLOW_DOWNLOAD=1. Nothing was downloaded." + if [ "${ALLOW_DOWNLOAD:-0}" = "1" ]; then warn "$msg Going on, because ALLOW_DOWNLOAD=1."; else die "$msg" 2; fi +} + # ---- other commands: `docker run image strata ...`, `docker run image sh` if [ "$#" -gt 0 ] && [ "$1" != "run" ] && [ "$1" != "serve" ]; then case "$1" in strata) shift; exec "$STRATA" "$@" ;; *) exec "$@" ;; esac @@ -174,6 +186,7 @@ if [ -n "$model_path" ]; then die "MODEL_PATH=$model_path holds no .gguf files. Mount the folder with the model's shards (the -0000N-of-0000M.gguf files). Nothing was downloaded." 2 fi fi +legacy_models_guard "$model_path" "${STRATA_LEGACY_MODELS:-/data/models}" [ -n "${MODEL:-}" ] && { set -- "$@" --model "$MODEL"; have=1; } [ -n "${FAMILY:-}" ] && { set -- "$@" --family "$FAMILY"; have=1; } [ -n "$model_path" ] && { set -- "$@" --model-path "$model_path"; have=1; } diff --git a/docs/A770_SPEED_SPEC.md b/docs/A770_SPEED_SPEC.md index 14ea3398..66fa7e10 100644 --- a/docs/A770_SPEED_SPEC.md +++ b/docs/A770_SPEED_SPEC.md @@ -445,10 +445,9 @@ docker run --rm -u "$(id -u):$(id -g)" -v "$PWD/..:/work" strata-sycl-dev \ cmake --build /work/strata-v0.1.40.3/build-sycl --target strata -j 8" ``` -Use the actual `cmake --build` exit status: `sycl/tools/build.sh` currently -prints `BUILD EXIT 0` but can itself return nonzero because its last failure- -search pipeline finds no failures. Do not chain tests behind that misleading -script status. +Use the actual `cmake --build` exit status. `sycl/tools/build.sh` from 0.2.7 on exits with it; older copies +printed `BUILD EXIT 0` but could return nonzero because their last failure-search pipeline found no failures. +Do not chain tests behind the status of an older script. ## Artifacts and implementation sequence diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 2ff7549e..612d9c80 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -193,6 +193,13 @@ the card's name, its architecture and the build's list. - CMake fetches the pinned llama.cpp revision. For an offline build, point `STRATA_GGML_DIR` at a checkout of that exact revision. - Linux engine packages: `VARIANT=rx6000 packaging/build_hip_linux.sh`. +- **A hand-built engine has no tuning table.** The packaged engines carry `tuning/-hipblaslt-.txt` beside the binary + ([Ready-made packages](#ready-made-packages) lists which); a build made with plain `cmake` and started + through `serve/server.py` has none, and the prompt GEMMs fall back to plain hipBLAS. On Strix Halo (gfx1151) that read prompts + 20-25% slower in one report (1,043 against 826 tok/s at 8K, hipBLASLt 1.4.1, a single run per arm, not a paired A/B). Point + `STRATA_HIPBLASLT_TUNING` at the file in `tools/hip/` (`gfx1151-hipblaslt-100401.txt` for hipBLASLt 1.4.1), or copy it into a + `tuning/` folder next to the `strata` binary. The start log then has the line `prefill gemm: hipBLASLt tuning enabled (N rows, + gfx1151, version 100401)`; without it, no table was taken. Run the registered checks with: @@ -257,6 +264,26 @@ machine then swaps or stalls, raise it. Re-check after a ROCm update. | `STRATA_DENSE_MMQ=1` | Off | Dense GGUF prompt projections through int8 MMQ kernels instead of dequantize + hipBLAS. Greedy text can diverge after a few dozen tokens (q8_1 rounding). | | `STRATA_HIP_ADAPT_KERNEL_COPY=1` | Off | Adaptive-tier swaps copied by a kernel instead of the SDMA engine; a workaround for a gfx1030 hang with MMQ prompts and adaptive swaps (untested by the reporter) | +**Why `STRATA_SH_STREAM` goes both ways.** The fork has to hide something. With experts on the CPU in the window, the shared expert forks +off only after the doorbell is published (`STRATA_SH_FORK_LATE`, `src/core/verify.cpp`), so it runs while the GPU would otherwise wait for the +CPU pool. On a 16 GB card whose cache holds only part of the experts that wait is about half of a verify window (one RX 6900 XT under Linux, +4,859 slots, `STRATA_DECODE_TIMING=1`: GPU-reach wait 20.7 of 39.1 ms per window), which is where #1272's gain comes from. When every routed +expert is on the GPU there is no wait to fill, and the fork is two cross-stream event dependencies per layer and nothing else: 7fd67dd measured +it on an R9700 with `--resident-experts` and the KV stream path running (48,067-token prompt), 43.4 tok/s with the fork against 62.9 without; +a 256-token prompt barely moved (65.4 and 62.7). Windows adds its own cost to every cross-stream dependency (#816). + +**Windows with KV streaming: leave it off.** On one RX 6900 XT under Windows 11 (the 0.2.3 `rdna2` package, engine 0.1.48, Qwen3.8-Flash-Next +IQ3_S, 64K context, `--kv int8 --kv-resident 32768 --vram-reserve-mib 1536`) the fork together with KV streaming stopped the engine on its first +request ("verify: unspecified launch failure", in other starts first reported by the MTP draft step; exit code 0xC0000409). With the fork off, or +without `--kv-resident`, the same setup answered normally. Removing the other switches one at a time (`STRATA_HIP_PROMPT_F16`, `STRATA_HC_PERSIST`, +`STRATA_HIP_ADAPT_KERNEL_COPY`, `STRATA_PREFILL_CPU_SHARE`, `STRATA_PIPED_CONCURRENT`, `STRATA_PREFILL_STREAM_MIN`, `STRATA_IO_THREADS`, a rocBLAS +table) did not clear it; removing `STRATA_SH_STREAM` did. Two RX 6900 XT under Linux (layer split, the same model, the fork and `--kv-resident +32768`) have served without the fault since 0.1.40. It is one PC and one card, and the faulting kernel was not isolated. So `--calibrate` does +not measure the fork on Windows when KV streaming is on, `strata tune` never picks it there, and a config that sets it by hand gets a warning +line at the start; nothing is refused. If you have an RX 6000 card on Windows and want to help, run it once with `STRATA_SH_STREAM=1` and +`--kv-resident` and tell us in [#3895](https://github.com/Niko1221/Strata/pull/3895) whether the first request answered, with the card and the driver. + + ## Speed switches Switches for the prompt path. A switch you set yourself, to anything, is never overridden by an architecture default. Put diff --git a/docs/BATCHING.md b/docs/BATCHING.md index bc5e3a5a..9621ae4b 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -188,6 +188,40 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - Slots are assigned so that consecutive requests land in different pipeline groups (`--batch-groups`). - A client that disconnects stops its slot (`BSTOP`); the others go on. +### Long prompts that move from solo to a batch slot + +The handoff above needs prompt-cache state. With `--prompt-cache 0`, moving a long request from the solo path into +a slot can read the whole prompt again. This minimal example enables handoff reuse without parking completed +conversations. Set these options in the model config's `args`, keeping the other arguments unchanged: + +``` +"args": [ ..., "--prompt-cache", "1", "--prompt-cache-every", "0", + "--prompt-cache-root", "0", "--conversation-cache-mib", "0" ] +``` + +`--prompt-cache 1` keeps the latest turn-boundary checkpoint so the `GEN` to `BGEN` handoff can reuse the live +prefix. `--prompt-cache-every 0` disables periodic checkpoints and `--prompt-cache-root 0` disables an extra root +checkpoint. The limit is per cache set: a slot can keep its own live state, so it is not one checkpoint shared by +every slot. `--conversation-cache-mib 0` still disables parking independent completed conversations in RAM; it does +not remove the prompt checkpoint or the state held by an active slot. +If conversation parking is already enabled, keep its existing budget instead of setting it to zero: that budget is +independent of the handoff configuration. + +This setting has RAM costs. The checkpoint and every slot's normal context state still consume memory, even with the +conversation cache off. Check the engine's free-memory report and the slot count that it actually accepts before +raising the context length or `"parallel"` value. + +It does not make independent cold prompts prefill in parallel. The server admits them one at a time; a running value +of four can mean four requests are in flight, not four slots decoding together. A slot already decoding may make +progress while the next prompt is read, but long independent prompts can finish before enough admissions overlap to +fill every configured slot. + +After changing the setting, send a long request alone and add a second request while it is decoding. In the engine +log, the first request's `GEN` to `BGEN` transfer should report a large reused prefix and only the new token(s) read. +Then check `/metrics` for the slots that were actually reading or decoding, and `/v1/status` for the effective +serving count. Treat this as handoff evidence only: it does not prove that every configured slot can stay resident or +that cold prompts have concurrent prefill. + ## Reading a prompt beside pipelined groups (experimental, opt-in) With a layer split and `--batch-groups` above 1 a prompt is read in one run: every decoding slot stops until it is @@ -363,7 +397,32 @@ between decoding windows (the prompt may hold a loan of cache slots). The `strat GPU-reach wait and pool time, and how many routed entries the VRAM tier, the PCIe share and the CPU served per window. Swaps move experts between the GPU and the CPU, which round differently, so greedy outputs can differ from run to run; `--adapt-every 1000000` keeps the tier fixed (as in the exactness settings below). The pipelined `--batch-groups` path -does not adapt. +does not adapt by default: its windows count the routing, but no round starts while groups are in flight, so the tier +moves only when the slots go back to the solo path. + +`STRATA_PIPE_ADAPT_EVERY=N` (opt-in; unset or 0 keeps the old behaviour) lets the pipelined path adapt: after N group +windows it starts no new group, lets the groups in flight finish, runs one round as the serial batch loop does (nothing +in flight reads a cache slot, and the swapped-in experts land before the next launch), and goes on. It stands still while +a prompt is read beside the slots, and does nothing with `--adapt-async 1`. The engine says so at start, and the +`strata batch (pipelined ...)` line adds the rounds, the experts swapped in and the time spent. Measured on 2x RTX 5090 +(layer split 25, Swift-Qwen3.8-Flash-Next IQ3_S, `--batch 6 --batch-groups 2`, resident experts, a profile-filled cache, +`--adapt-every 16`), six streams of 1,024 greedy tokens from `tools/serve_load.py`, the engine's rows/s of eight bursts +right after start, two fresh engines per setting: + +| `STRATA_PIPE_ADAPT_EVERY` | bursts 1-8, rows/s | mean | experts swapped before burst 8 | +| --- | --- | ---: | ---: | +| unset (stock 0.2.4.1) | 246, 257, 291, 292, 335, 338, 356, 355 | 309 | 287 | +| unset (this branch) | 249, 242, 297, 296, 333, 336, 372, 362 | 311 | 288 | +| 128 | 363, 415, 414, 420, 420, 411, 415, 420 | 410 | 6,181 | +| 128 | 359, 407, 416, 422, 419, 417, 404, 411 | 407 | 6,294 | +| 32 | 375, 405, 408, 405, 409, 390, 405, 409 | 402 | 5,957 | +| 32 | 384, 414, 404, 402, 401, 412, 406, 401 | 403 | 5,678 | + +Without it the tier swaps 96 experts every burst or two (only when a burst ends) and the engine was still speeding up +after eight bursts; with 128 it reached about 415 rows/s from the second burst, the speed an engine without the switch +showed only after thousands of swaps had come from other traffic. 32 empties the pipeline four times as often and ends a +little lower. One machine, one model and one configuration; not measured on one GPU (no pipelined path there) or with +more than two stages. With `--adapt-async 1` (needs the resident RAM mode) the round does not hold a window up: each batch window moves the round on one step (table changes and uploads on the main thread, the copies on a helper thread and the cards' refill @@ -491,6 +550,7 @@ counter-based draw (Philox(seed, position)). boundary, and not for pictures. - Admissions are one at a time: two new long prompts are read one after the other. - `--batch-groups` needs every stage on its own GPU. A pipelined slot is a conversation cache again (0.1.41): a request left alone in its slot goes back to the solo path with its drafts, as on one GPU. +- The pipelined `--batch-groups` path adapts the VRAM tier only with `STRATA_PIPE_ADAPT_EVERY` (above). - The slot sessions take VRAM (above) and, with KV streaming, pinned RAM. ## Measured diff --git a/docs/BENCHMARK_PROTOCOL.md b/docs/BENCHMARK_PROTOCOL.md index 29e9e9eb..949f9d8f 100644 --- a/docs/BENCHMARK_PROTOCOL.md +++ b/docs/BENCHMARK_PROTOCOL.md @@ -329,7 +329,12 @@ An install with neither has no commit, and the run is `nonconforming`. `engine_v from `/props` (`build_info`), or `/v1/status` when `/props` has none. `build_kind` is `source` when the folder has a `.git`, otherwise `release`. The runner cannot read build options from a server; pass `--build-options` for a source build. The drivers and the CUDA version come from `nvidia-smi` (or `rocm-smi`, or the Windows display -driver key), read on the machine that runs the engine. +driver key), read on the machine that runs the engine. ROCm 7 and newer ship `amd-smi` and no `rocm-smi`: the card's +name is that tool's `static --asic` market name, its memory is the amdgpu sysfs file of the PCI address `amd-smi list` +reports, and the `rocm` runtime entry is the version file inside the ROCm install (`amd-smi -h` prints the same +version). Where the kernel builds amdgpu in there is no driver version to read, and `gpu-driver` stays null with a +reason. When the server can only name a vendor, because the amdgpu `product_name` is empty on some cards, the card the +local probe named is kept instead. Except for typed objects, arrays, numbers and booleans identified above, identity and descriptive fields are strings (or null with a reason where unavailable). Empty configuration objects mean no relevant options; diff --git a/docs/DEEPSEEK41.md b/docs/DEEPSEEK41.md index 86a98e63..418a57e4 100644 --- a/docs/DEEPSEEK41.md +++ b/docs/DEEPSEEK41.md @@ -55,6 +55,12 @@ Measured: an RTX 5070 (12 GB) with 64 GB of RAM and a 3.6 GB/s NVMe drive answer tokens/s (4K) to 231 tokens/s (8K, layer-major path); an RTX 3060 (12 GB) with 46 GB of RAM about 8 to 10 tokens/s (code 9.9, agent work 7.8; 149 tokens/s at 8K; DSpark stays off there, `--dspark on` adds 2-13%); four R9700 about 48 tokens/s on 2.00 and 80 on 2.25 (code, with the shipped hot-expert profile). Under about 40 GB of RAM it is untested and slow; setup says so and still installs. +**RTX 40 series (sm_89).** The engine packages carry machine code for sm_86, sm_89 and sm_120 since 0.2.7 (before, an RTX 40 card ran the sm_86 code through +CUDA's same-generation rule). We have no RTX 40 card: the sm_89 build was compiled here but not run. A user's own build for sm_89 ran the 2.00 set on an +RTX 4090 48 GB with 128 GB of RAM (#3935, their numbers): decode 40.2 tokens/s (median of 5 answers of 64 tokens, `--ssd-cache 108 --dspark on --dspark-conf 0.65`), +prompts 141 tokens/s at 1.2K and 615 at 4.6K. They saw 16 to 22 tokens/s with `--dspark auto`, which decided "off" on their computer. This is one report on one +computer; other cards and RAM sizes can differ, and `--dspark auto` stays the default. + Setup downloads with resume and SHA-256, packs the model with the plain recipe (`pack_gguf.py --model SET --shards ... --engram engram-IQ4_NL.gguf --engram-meta --dspark-gguf dspark-...-Q8_0.gguf`; do not add `--skip-tensors` or `--dense-override`: that packs without an error and gives garbage text), copies the shipped hot-expert profile (`data/dsv41/profile-2.00.bin` or `-2.25.bin`) @@ -144,6 +150,28 @@ Strata checks the package before it uses it: it must be the DeepSeek engine (not Strata trusts, and every file must match the hash in the manifest. A damaged or foreign file is refused with a plain line and nothing is installed. The unpacked folder works as well as the archive. The Strata (Qwen) engine is not touched either way. +### Building the engine for your card + +The packages hold machine code for these NVIDIA cards (CUDA 13, Windows and Linux): sm_86 (RTX 30), sm_89 (RTX 40) and sm_120 (RTX 50), plus PTX for +sm_120. If your card is none of these, or you want your own build, compile `strata-dsv41` and put it where Strata looks for it. You need the CUDA toolkit +(the packages are built with 13.0), a C++ compiler, CMake, Ninja and the llama.cpp checkout Strata pins (`third_party/llama.cpp`). + +``` +cmake -S . -B build-dsv41 -G Ninja -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_DSV41=ON -DSTRATA_NATIVE_EXPERTS=ON "-DCMAKE_CUDA_ARCHITECTURES=89-real" -DSTRATA_GGML_DIR=third_party/llama.cpp +cmake --build build-dsv41 --target strata-dsv41 -j 8 +``` + +Use your card's number in `CMAKE_CUDA_ARCHITECTURES`: 86 for RTX 30, 89 for RTX 40, 120 for RTX 50, or `native` for the cards in this computer. Without the +option a DeepSeek build is made for 86, 89 and 120. On Windows, `packaginguild_dsv41_windows.bat BUILD_DIR` does the same (`DSV41_ARCH` names the cards); +on Linux, `packaging/build_dsv41_cuda.sh` (`ARCH=...`). Then copy the file into the `engine` folder of your Strata install (next to `strata`); setup finds it there and does not download an engine: + +``` +python setup.py --family deepseek41 --model IST-DAS-2.00bpw +``` + +`strata-dsv41 --version` prints the commit it was built from. A build you made yourself is not signed by Strata, which is fine for your own computer. +Please tell us how it runs on your card (the speed, and the card and RAM): we only list a card as tested after someone has run it. + ## Compressed experts (trellis), for testing `strata-dsv41` reads the routed experts in the trellis types as well as the source MXFP4: TQK6 and TQK7 (agentionai's files), and the diff --git a/docs/DETAILS.md b/docs/DETAILS.md index f60429bf..4773ed40 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -238,8 +238,12 @@ When the RAM cannot hold them beside the system (the experts plus about 10 GB), - The adaptive tier (`--adapt-every`) keeps following the conversation in the resident mode. `--adapt-async 1` (opt-in, `--serve`) moves the swaps between decode windows on a helper thread. With `--batch` slots it works between their windows too, but not with `--batch-groups` or `--peer-device`. It is not bit-exact from run to run. -- `STRATA_RAM_ADAPT=` (opt-in, `--serve`, one GPU, needs `--adapt-every`): the RAM copy also follows the conversation, - with up to `n` experts swapped per round. +- `STRATA_RAM_ADAPT=` (opt-in, `--serve`, one GPU, needs `--adapt-every`): the RAM copy also follows the conversation. + A layer swaps up to 4 pairs per window: the experts the windows keep routing to (decayed count 2 or more) take the + RAM places of unused experts of the same layer (count below 0.5), largest difference first. The incoming expert was + usually read for the window before; when its blob still sits in that read's stage buffer it is copied from there and + no file read is made. `n` caps only the pairs that need a file read (`=1` is enough in practice). The log counts how + many experts moved and how many came out of a stage buffer. - Several GPUs: setup recommends one GPU in the low-RAM mode and asks. `--gpus 0,1` shares the model across both cards ([MULTI_GPU.md](MULTI_GPU.md#using-it)). `--yes` keeps one GPU. - With a page-locked copy the GPU also takes its share of the misses over PCIe (`--pcie-frac`). `--pcie-frac 0` (or @@ -292,7 +296,9 @@ files, read time; `routing prefetch`: how many file reads had been warmed). The `GET /metrics` lists `ram_blobs`, `file_blobs`, `file_mb`, `drafts_offered` and `drafts_accepted` per recent request, with `totals` since the start. `hit_rate` is the VRAM share of the experts looked up; experts the GPU reads over PCIe (`--pcie-frac`) are not in it, so a higher `--pcie-frac` raises it even when decoding gets slower. `pcie_share` is their -share of all routed experts. The Monitor tab shows both. +share of all routed experts. The Monitor tab shows both. The request list in the Monitor tab also shows the prompt's own speed: what the cache already held is not read +again, so it is the fresh tokens (`prompt_tokens` minus `reused`) over the prompt time (`prompt_ms`), and a request that read no +new token shows no number. Profiling: start the server with `STRATA_DECODE_TIMING=1` (and `STRATA_VERIFY_PROFILE=1` for the GPU side). After each request the engine log has a `strata decode timing:` line and a `strata decode GPU stages (ms/window):` line. The GPU profile slows @@ -300,6 +306,12 @@ decoding a little: use it to compare, not to measure speed. `STRATA_LOOKAHEAD_ST prediction every 100 windows and costs CPU. `tools/replay_cache_policy.py` replays a `--dump-routing` trace through the adaptive tier's swap policy offline. +In the serial serve loop the timing line lists the wall-time parts in the order they run: `adapt wait + verify + +commit/emit + draft + adapt join + other`. `other` is the decode time minus the named parts, not a step of its own. +The times are host wall times, averaged over every decode window, and the bracketed parts of verify are already inside +verify. The pipelined decode keeps the older line (`ms/window = verify ...`) and batch slots are not covered, so a script +that reads this line must accept `ms/window = adapt wait` for a serial run. + ### Draft layer | Option | Effect | @@ -483,16 +495,31 @@ applies at the next start. Network, key, MCP and program keys are not editable t every 15 s and `GET /status` says what it is doing. Closing the connection or pressing stop in your app stops the model. - A tool call counts only when it names a tool the request declared. A namespaced tool (`mcp__filesystem.write_file`) is that call when the model writes `mcp__filesystem__write_file`, `mcp__filesystem=write_file`, `mcp__filesystem_write_file`, - or the bare member (`write_file`) and exactly one declared tool has that member. Any other call, or any call in a request - that declared no tools, comes back as the text it was written as. A call whose envelope drifted by a token (`<=NAME>`, + or the bare member (`write_file`) and exactly one declared tool has that member. A name with `__` in it (`mcp__playwright__browser_navigate`) + is also that call when the model writes every `__` as `_` (`mcp_playwright_browser_navigate`), unless two declared tools collapse to the same + spelling. Any other call, or any call in a request that declared no tools, comes back as the text it was written as. Names are never + guessed: `bash` is not `shell`, and a reordered name (`server1_label_values` for `label_values_mcp_server1`) is not the declared one. + A call whose envelope drifted by a token (`<=NAME>`, `` or `` instead of ``) is read as the call when NAME is a declared tool. +- **A call that came back as text because its name was not declared (#3796).** The text stays exactly as the model wrote it and + `finish_reason` stays `stop` (or `end_turn` on `/v1/messages`). Next to it the reply carries a list, only when there is something in it: + `"strata_rejected_tool_calls": [{"name": "bash", "reason": "undeclared"}]` (at the top level of a Chat Completions reply, in + its last streamed chunk, and in the `message_delta` event and the message of `/v1/messages`; up to five names). A client that + wants to recover can answer the model with the tool names it does have and ask again; Strata never runs or forwards a call for a + tool the request did not declare. The server window prints the same names (`N block(s) ... went back as text`), and + `/metrics/prometheus` counts the blocks in `strata:tool_calls_unread_total`. A block that is malformed (not an undeclared name) is counted + there and in the window, but has no name to list. - JSON output: `response_format: {"type":"json_object"}` or `{"type":"json_schema", ...}` on `/v1/chat/completions`. The schema must accept only JSON objects at its root (`"type":"object"`, or `anyOf`/`oneOf` of object schemas). Local `#` references work and remote ones are refused. This is schema prompting followed by server validation, not grammar-constrained decoding, with one generation per request. `jsonschema` is used when installed (`python -m pip install "jsonschema>=4.23,<5"`); without it the answer is only checked to be one JSON object. Malformed output returns **502** with `error.code: structured_output_failed`, an invalid schema **400**. JSON formats combined with tools or MCP are refused. - Streaming buffers the answer and emits content only after validation. + Streaming buffers the answer and emits content only after validation. Math answers often hold LaTeX such as `\alpha`, which is + not a valid JSON escape. Add `"repair_latex_escapes": true` to the `response_format` (or to `text.format` on `/v1/responses`) and, + only after the strict parse failed, the server doubles the backslashes that are not valid escapes and checks the answer again. + Valid output is never touched. `\b`, `\f`, `\n`, `\r`, `\t` and `\uXXXX` are valid JSON, so they stay: a `\beta` beside a `\alpha` + comes back with a backspace. Off by default. - `logit_bias` and token/bias pair lists work on CUDA and HIP engines without continuous batching ([LOGIT_BIAS.md](LOGIT_BIAS.md)). - Stop strings (`stop`, `stop_sequences`), `temperature`, `top_p`, `top_k`, `min_p` and `seed` are honored per request. `top_k` keeps at most 64 candidates. Penalties (`presence_penalty`, `frequency_penalty`, `repetition_penalty`, @@ -507,6 +534,21 @@ applies at the next start. Network, key, MCP and program keys are not editable t `STRATA_SPEC_GUMBEL=1` raise the accepted-draft rate on some machines; `STRATA_SPEC_PROB=1` is speculative rejection sampling. `STRATA_SPEC_DEPTH=1` prints acceptance by draft depth and `STRATA_SPEC_MIN_TEMP=0.9` limits sampled drafting to hotter requests. Try them on your own card before relying on them. +- **logprobs: how likely each token was (CUDA/HIP).** `"logprobs": true` with `"top_logprobs": 0..20` on + `/v1/chat/completions`, streamed or not, adds `choices[0].logprobs.content[]` to the reply (`token`, `logprob`, + `bytes`, `top_logprobs`); with thinking on, the thinking's entries come under `reasoning_content` instead. The + tokens, joined, spell the reply exactly (a character split across two tokens lands in the one that finishes it). + A reply is bounded by `max_tokens` -- or by the rest of the context when it is not sent -- and by no cap of our + own, as on OpenAI and vLLM, neither of which ties a length limit to logprobs. A reply that is not streamed, or + that answers a `json_schema` (buffered to be validated), does hold every entry until it ends, so a long one holds + a lot of them; a streamed reply hands each entry out with its chunk and keeps none. `"allowed_token_ids": [ids]` + keeps only those ids in `top_logprobs`, most likely first, renormalised to sum to 1; the chosen token is one of + them when it was named (vLLM's field, but vLLM masks generation with it, while here it filters what is reported, + so a token outside the named ids keeps its own `logprob` and an empty list). An id past the model's vocabulary is + a 400. A token whose probability could not be read gets no entry, and the reply goes on. On a server started with + `--parallel`, only a `max_tokens` 1 request gets them: it is the one a batch slot decodes through the single-token + path, which writes an LP line. A longer reply there is a 400, since the slot's `BT` lines carry none -- entries for + a prefix only, which a client cannot tell from the model's own answer. - **Non-finite logits end the request and drop the cached state (on by default).** If a verify window's logits are NaN, the window emits no tokens, the request ends, and the next request drops the live session, checkpoints and parked conversations and reads its prompt from token 0. The server retries a request that had sent nothing once, transparently. @@ -544,6 +586,8 @@ tables per token). The scaling is fixed for the whole run, because the KV cache `--host 0.0.0.0 --api-key some-long-secret`, or add `"host": "0.0.0.0"` and `"api_key": "..."` to the config. A key is recommended, not required: without one the server starts and warns that anyone who can reach the port can use the model and its tools. `--no-api-key` (or `"api_key": "none"`) says it is on purpose. The server window prints this PC's addresses. + For IPv6 use `--host ::` (or `"host": "::"`, all IPv6 interfaces) and put the address in brackets in URLs, for example + `http://[2001:db8::7]:8080/v1`. On Windows allow the port in the firewall for private networks: `New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private` (admin PowerShell). @@ -554,7 +598,10 @@ tables per token). The scaling is fixed for the whole run, because the KV cache - **Browser pages (CORS):** off by default. `"cors_origins": ["https://chat.example.com"]` lets those origins call `/v1/*`; `["*"]` lets any page and is only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools. It belongs to the engine's own server; the desktop app answers browser pages on its own API address and already allows - pages of any site there. + pages of any site there. When you share with other devices or run a tunnel, the shared address answers them too, with an + API key: the key decides, not the site. The browser's preflight (`OPTIONS`) is answered without a key, since a browser never + sends one with it; the request that follows still needs the key. Without an API key the shared address sends no CORS + headers, so a page of another site cannot read your model through it - only devices on your network can. - **Host names (DNS rebinding):** without an API key the server answers only requests whose `Host` is `localhost`, an IP address, the address it listens on, or (when it listens beyond this PC) this PC's name and `host.docker.internal`. Others get **403** naming the setting. Add a name with `"allowed_hosts": ["strata.example.com"]` or @@ -619,7 +666,7 @@ system prompt with a billing header that changes on every request; the server pi | Option | Effect | | --- | --- | | `--prompt-cache N` | Number of checkpoints (`0` = off, which also disables parking). | -| `--prompt-cache-every N`, `--prompt-cache-root N`, `--turn-token ID` | Checkpoint interval, the system-prompt checkpoint (`0` = none) and the turn token. | +| `--prompt-cache-every N`, `--prompt-cache-root N`, `--turn-token ID` | Checkpoint interval, the system-prompt checkpoint (`0` = none) and the turn token. The interval is not a piece-size setting: [what it does](PROMPT_CACHE_TAIL.md#prompt-cache-every-does-not-set-the-size-of-the-pieces-a-prompt-is-read-in). | | `--prompt-cache-spread` (opt-in) | The checkpoint that leaves is the one whose removal leaves the smallest gap, so the kept points thin out geometrically back from the end. An agent that rewrites its history a few thousand tokens back then resumes near the edit instead of at the system prompt. Same RAM. | | `"strata_checkpoint": false` (per request) | A one-shot request that no later request continues saves no checkpoints and keeps no session. | | `"strata_prefix": {"messages": 1}` (per request, opt-in) | One long document, many questions. Marks where the document ends: `{"messages": 1}`, `{"message": 0, "chars": 210000}` or `{"tokens": 12345}`. The checkpoint at the boundary is pinned, so 20 questions cost one read of the document. One pinned prefix at a time per engine; needs `--prompt-cache 3` or more; a malformed field is a 400. See [RESEARCH_RUNS.md](RESEARCH_RUNS.md). | @@ -678,6 +725,56 @@ curl -X POST "http://127.0.0.1:8080/slots/0?action=restore" -H "Content-Type: ap only for this feature. Exact token replay across restarts is not guaranteed: expert residency and CPU/GPU rounding can change later output. +### The web page (Chat, Images, Monitor, About) + +Open the server's address in a browser. Everything in it runs from the server's own files: no CDN, no outside address. Chats, +settings and the API key stay in the browser. + +**Chat settings** (the button next to the message box) holds the sampling and thinking settings and the switches below. Every +switch below is **off by default**; with all of them off the page behaves as it did before. + +- **Render math.** Equations written as `\( ... \)`, `\[ ... \]`, `$x$` or `$$ ... $$` are drawn as formulas by KaTeX 0.19.0, which + ships in `serve/web/vendor/katex` (MIT; `PROVENANCE.json` there lists the package and a hash of every file). The text of a + message is never changed: copying, the Markdown export and the next request all carry what the model wrote. Code, prices + (`$5 and $10`) and a formula still being written stay text. A formula KaTeX cannot read stays as its source. A formula can only + draw: it cannot make a link, load a picture or run anything (`\href`, `\url`, `\includegraphics` and `\htmlClass` are shown as + their own names). +- **Saved chats list.** Keeps every chat in a list on the left, with search over titles and text, rename, delete (with Undo) and + days as headings. The chats live in this browser's IndexedDB; a picture or file is kept by name only. Nothing goes to the server. + In a private window, or when the browser's storage is full, the list stays in memory and the page says so once. Turning it on + keeps the chat on the screen as the first one in the list; turning it off keeps that chat as the single chat. +- **Edit and rewind messages.** Under each message: **Regenerate** (a new answer to the same question), **Edit answer** (correct its + text; the old thinking and tool calls go and no request is sent) and **Rewind to here**. Rewind asks what you want. On your + message, **Edit and send again here** hides it and the messages after it and puts it in the box; on an answer, **Continue from + here** hides the messages after it. **Branch from here** (needs the saved chats list) starts a new chat from the messages up to + that point and leaves this chat as it is; the branch keeps a name such as "Branch of ..." and links back to the original. An + **Undo** bar above the box brings back what was hidden, until your next question, another chat or a reload. A picture or file + that was only kept by name is not sent again: the page asks you to attach it again. +- **When you send while it is answering.** *Wait* (the default): Send is off until the answer is done. *Send after*: your message + waits and goes when the answer is done. *Interrupt*: the answer stops where it is, what was written stays and is marked + interrupted, and your message goes at once; a tool that is running finishes first. Only one message waits, and **Take back** + returns it to the box. Stop keeps a waiting message for you to send yourself. + +An answer's ` ```svg ` or ` ```html ` block gets a **Preview** button. The code is drawn in a frame that is cut off from the page: +an empty sandbox (no scripts, forms, popups or downloads, and no access to the page, its storage or the server), a policy inside +the frame that allows no address at all, and a page header (`Content-Security-Policy: frame-src 'none'`) that keeps a link or a +redirect in the model's HTML from loading a web page into it. An svg is shown as a picture. For an HTML page there is also a +warning button, **Run scripts**: after you confirm, that one block runs with scripts, still with no way to the page and no network, +until you close the preview. It can still use your CPU, and it is code the model wrote. + +**Load / Unload** in the header loads the model or frees the GPU (`POST /load`, `POST /unload`). It asks before unloading and is off +while an answer is being written or an image is made. + +**Language.** About > Settings lists the page's languages: English (the default), German, Spanish, Japanese, Korean, Portuguese, +Russian and Chinese. The Chat view, its settings and the header are translated; Monitor, Images and About are still English. A +language is a file `serve/web/locales/.json`; the English text lives in the code next to its key, and +`python tools/web_i18n.py` checks every file for the same keys and placeholders (`--write` rewrites `en.json`). `/?lang=de` shows a +language for one visit. + +Tests: `serve/test_web_*.py` and `serve/test_web_*.js` (Node), and a browser run against a stand-in server with no model: +`WEBTEST_MODULES= node tools/webtest/browser_test.mjs`. `tools/webtest/shots.mjs` takes the page's +screenshots. + ### API request monitor Off by default, because it keeps prompts and answers in memory. Turn it on with `"api_monitor": true` or @@ -703,10 +800,13 @@ endpoints are refused with an error that says so. | `tools` | `function`, `namespace` and `custom` tools. Hosted tools (`web_search`, `file_search`, ...) are left out because the model cannot run them | | `tool_choice` | `"none"` hides the tools; anything else lets the model choose (it cannot be forced) | | `reasoning.effort` | `none`/`minimal`, `low`, `medium`, `high`/`xhigh`; without it the config's `reasoning_effort`, else the model's default | -| `max_output_tokens` | The output cap, thinking included. Running out ends the response `incomplete` | +| `max_output_tokens` | The output cap, thinking included. Running out ends the response `incomplete`. `0` and `-1` (or leaving it out) mean no cap, as for `max_tokens`; anything below `-1` is a 400 | | `text.format` | `json_schema` and `json_object` use the JSON formats above (checked, not constrained) | | `client_metadata["x-codex-turn-metadata"]` thread-title request | Opt-in `"codex_thread_titles": true`: answered without the engine as `{"title": ""}` so the conversation keeps the prompt cache | +The final event (`response.completed` or `response.incomplete`) and a non-streaming reply carry the same top-level `timings` object as +`/v1/chat/completions`. + The thinking comes back as a `reasoning` output item with `reasoning_text` content. The model writes no summaries, so `summary` is empty. With `"include": ["reasoning.encrypted_content"]` the item also carries an opaque string (base64, not encrypted). Send reasoning items back with the conversation, as Codex does, so the prompt matches and the cache is reused. Streaming @@ -767,8 +867,9 @@ after a change. needed for `npx` servers. An **address** (`url`, optional `headers`) uses MCP's Streamable HTTP transport (the older SSE-only transport is not supported). `"disabled": true` leaves an entry out. - Servers start with Strata. The server window says what each offers or why it did not start. The Monitor tab lists them, and - the Sampling drawer has **Use tools from MCP servers** (on by default). A server that stops later is started again at its next call. -- In the chat each call shows as a small block. The model reads the result and goes on, up to `max_rounds` calls in a row. A tool + Chat settings has **Use tools from MCP servers** (on by default). A server that stops later is started again at its next call. +- In the chat each call shows as a small block. The model reads the result and goes on, up to `max_rounds` rounds of calls (one round can hold several calls). At the limit + the model gets one final reply with no tools, using the results already found, so the answer is not cut off. A tool that fails or takes longer than `timeout_s` gives the model an `error: ...` result. Results longer than `max_result_chars` are cut with a note. Stop stops a running tool too. - Only the chat page uses them. API clients see the API exactly as before and keep their own tools. A request to @@ -901,7 +1002,7 @@ them on your own card. | `STRATA_PREFILL_EQUAL=1` | CUDA | A prompt segment is read in chunks of equal size, not full chunks and a short last one. Changes rounding. | | | `STRATA_OWNED_PRICE=exact` | CUDA | The cache sizing prices the prompt path's own buffers by their real allocation. | | | `STRATA_IQ_MT_MIN=1`, `STRATA_IQ3S_MT1=1` | CPU | See [Draft layer](#draft-layer) (reproducible output; the second gives IQ3_S the multi-token kernel for one token on Alder Lake and later without AVX-512). | | -| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended. | +| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended, except that 0.2.7 turns `STRATA_ROUTE_PRIOR=1.5` on by itself on a discrete NVIDIA card of 13 GiB or less (the owner approved the quality trade for 12 GB cards; the first 0.2.7 candidates used 2.0, see the 12 GB default in the release notes for why it is 1.5); `STRATA_ROUTE_PRIOR=0` turns it off and an explicit value wins. It is never a default on a Radeon, an integrated GPU or a bigger card. | | `STRATA_HOST_CORE=last\|sibling` (or `--host-core`) | Windows | `last` puts the host thread on the last physical core, away from the core that gets the GPU's interrupts. `sibling` keeps it on the first core's other hardware thread, so the workers keep every core. The default `first` leaves a hybrid CPU as it is. | One layer-split box went from a ±6% swing to steady and 8% faster. | | `--pool-affinity measure` | Hybrid CPUs, native packs | Times the `all` and `p-cores` layouts at start (about a second) and takes the faster. The measurement is taken once; where the E-cores' speed changes while the engine runs, `--pool-affinity p-cores` is the steady choice. | | | `STRATA_KEEP_EMPTY_TURNS=1`, `STRATA_TOPK_STREAM=0` | | See [TROUBLESHOOTING.md](TROUBLESHOOTING.md). | | @@ -921,7 +1022,8 @@ measured. "Exact" means the 10-prompt and 4K/20K identity gate with the switch o | `STRATA_B6_MMVQ_ROWS=1` | Exact multi-column MMVQ reusing the activation fragment across rows | Exact; on by default on sm_86 and sm_60 | | `STRATA_QSA_SPLIT_ATTN=1` | Decode attention split across blocks on the int8 mma path (sm_80+, int8 KV) | Rounding level | | `STRATA_HC_UPMIX=1` | Hyper-connection up projection and `gr_mix_r` in one kernel (sm_80+) | Exact | -| `STRATA_PROMPT_ATTN_IMMA=1` | Int8-KV prompt attention on INT8 tensor cores | Rounding level | +| `STRATA_PROMPT_ATTN_IMMA` | Int8-KV prompt attention on INT8 tensor cores | Rounding level. On by default since 0.2.7 on NVIDIA Ampere and newer (+1.1% to +1.8% prompt at 8K/16K on an RTX PRO 5000 and 2x RTX A4000); `=0` brings the 0.2.6 kernel back. | +| `STRATA_GR_V3` | The hyper-connection read split over two kernels | Rounding level. On by default since 0.2.7 on a discrete compute capability 12.0 card (RTX 50, RTX PRO Blackwell) with more than 13 GiB (RTX PRO 5000: +1.2% decode with identical tokens); slower on sm_86, so off there. `=0` / `=1` forces it off / on. | | `STRATA_HC_REQ8=1` | Hyper-connection projections as int8 plus a scale per 32 (more expert-cache slots) | Rounding level | | `STRATA_QUANT_GATHER=1`, `STRATA_PREFILL_GROUP_GATHER=0` | Per-row gather for the MoE input quantization; the short-prompt grouped gather off | No gain measured; keep the defaults | @@ -937,7 +1039,28 @@ that wins in both directions: `STRATA_SM75_IL`, `STRATA_SM75_EXP`, `STRATA_GR_UP `STRATA_TOPK_SPLIT`, `STRATA_TOPK_SAMPLE`, `STRATA_ATTN_V3`, `STRATA_Q2_WARP`, `STRATA_FUSE_WAIT=2`, `STRATA_QIL`, `STRATA_TC_SM75`, `STRATA_PA_V1_PREFETCH`, `STRATA_SCORES_THREAD` (a thread-per-head block scorer; `=1` works on any CUDA card). Options that change answers stay separate: `STRATA_SELECT_SIMT=1|2`, `STRATA_PA_V2T=1`, `STRATA_PF_FUSED=1 STRATA_PF_FUSED_SM75=1` -(Q2_0 pack, 7.5 card only) and `STRATA_BF16_TC=1` with `STRATA_XN_F16`. +(Q2_0 pack, 7.5 card only), `STRATA_PF_FUSED_Q2N=1` (the native Q2_0 pack's prompt experts on sm_80+, below) and +`STRATA_BF16_TC=1` with `STRATA_XN_F16`. + +### The native Q2_0 pack's prompt experts on the fused int8 kernels (`STRATA_PF_FUSED_Q2N=1`, opt-in, sm_80+) + +A PC whose CPU lacks the AVX-512 set that setup looks for gets the native Q2_0 pack. On a CUDA card of sm_80 or newer its +Q2_0 / Q2_0 layers read prompts through MMQ's Q2_0 kernel; the fused int8 kernel for that format (#2145) is set up only on a +7.5 card. `STRATA_PF_FUSED_Q2N=1` sets it up on any sm_80+ card and takes it for those layers. It has its own variable, so +`STRATA_PF_FUSED=1` keeps its bits, and `STRATA_PF_FUSED=0` or `STRATA_PF_FUSED_NATIVE=0` still turn it off. Unset, the engine +is unchanged (first-token logits byte-identical to v0.2.2 on 40 prompts of 1-5K tokens, the author's check). With the switch +the prompt arithmetic changes and the generated text can change. + +The author measured it on an RTX 5080 16 GB (sm_120, Linux, CUDA 13.0), i9-14900K, 2,100 experts in VRAM, CPU prompt share off, +against the same build unset. At the same 4,864-token chunk (4 interleaved rounds) the 4K, 16K and 23K prompts read 2-3.5% +faster (4/4 rounds each). With `--prefill auto` (5 rounds) the fused path's smaller buffers make the chunk 5,632 tokens instead of +4,864 and the 16K prompt reads 32-33% faster (2,592 -> 3,438 tok/s), the 23K one 14%, a 4K one 0-2%; so most of the gain is the +larger chunk, not the kernel. One layer (`prefill_fused_iq_test`, Q2_0 / Q2_0) runs at 1.92x / 1.37x / 1.30x the MMQ path at +2,048 / 4,864 / 8,192 tokens. First-token KL against the FP16 prompt path over 30 prompts of 1.5-4.6K tokens: 0.0110 (MMQ +0.0112), top-1 agreement 28/30 (MMQ 29/30). Not measured: a card that holds every expert, other sm_80+ cards, Windows, the +generated text. On an RTX A4000 the same kernel in #2145 stopped matching the old output and read 4K prompts 4.5% slower, so +Ampere is not verified. The ctest entry `prefill_fused_iq_test_q2n` runs the Q2_0 / Q2_0 layer with the switch alone (it skips +below sm_80 and without a card). --- @@ -1043,7 +1166,7 @@ your own prompts. The Monitor marks every request ESP or stock. ``` The engine log then says `control vector mode = project, dir = per-layer, layers 4..44 (41 steered)`. A loaded vector is on for -every request unless it says otherwise: the Sampling drawer has a switch, and the API takes `"experimental_speed_projection": false` +every request unless it says otherwise: Chat settings has a switch, and the API takes `"experimental_speed_projection": false` (config default: `"sampling": {"experimental_speed_projection": false}`). Switching drops the conversation cache once. Switched off, the output is token for token the stock model's. @@ -1071,6 +1194,8 @@ On 12.0 cards (sm_120) these also apply: - The interleaved small-batch matvec (`native_mmvq_il`, [MMVQ_IL_TABLE.md](MMVQ_IL_TABLE.md)) runs 5 to 8 tokens, with a 12.0 table and, on cards with 80 or more SMs, its own 2-4 token table. `STRATA_MMVQ_IL_WIDE=0` and `STRATA_MMVQ_IL_120=0` turn them off. + RTX 40 cards (compute capability 8.9) have their own 2-4 token tables and a one-token Q3_K row, on by default in 0.2.7 and not yet measured + on an RTX 40 card by us (same output bit for bit): `STRATA_MMVQ_IL_89=0` or `STRATA_DEFAULTS=026` turns them off. - With 80 or more SMs the native packs' prompt experts run on the fused int8 kernels (`STRATA_PF_FUSED`) for IQ2_S, IQ3_XXS, IQ3_S and IQ4_XS gate/up. IQ2_XXS and IQ2_XS keep MMQ. Smaller 12.0 cards (an RTX 5070 with 48 SMs) keep MMQ because the fused kernels were 4.7% slower on 20K prompts there. `STRATA_PF_FUSED=0` keeps MMQ. @@ -1080,7 +1205,7 @@ On 12.0 cards (sm_120) these also apply: prompt time and start-up time, which is why smaller PCs keep the SSD reads. A prompt chunk above 8192 (`--prefill auto:16384` or `auto:32768`) is not bit-exact on CUDA, so the default stays 8192 on -NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR=0.5` stays opt-in because it raises KL. +NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR` raises KL, so below 0.2.7 it was opt-in; 0.2.7 sets 1.5 by itself only on a discrete NVIDIA card of 13 GiB or less. --- @@ -1155,6 +1280,9 @@ Strata itself: [MIT](../LICENSE). The model files are not part of it; their lice [HyperQwen](https://github.com/syv-ai/HyperQwen); references in the paper. - The web app's font: [Outfit](https://github.com/Outfitio/Outfit-Fonts) (SIL Open Font License 1.1, see `serve/web/fonts/OFL.txt`). Its Monitor tab started from @code-martin's dashboard idea (PR #22). + Math is drawn by [KaTeX](https://katex.org) (MIT, vendored in `serve/web/vendor/katex`). The chat page's wide-window layout, svg/html preview, math, Load/Unload, saved + chats, edit and rewind came from PRs #3176 (@mnott), #1628 (@thoives), #2972 and #2974 (@CC-David-CC), #3550 (@sakuumomo), #1787 (@Scotty-Hudson) and + #2615 (@uppet), and the rewind choice and sending while answering from issues #3823 and #4004 (@xvcezrqpbxtpzblrt). - The experimental speed projection's vector (`data/experimental-speed-projection/`): Qwen Community License 1.0, made from the model's activations (see its README). @@ -1224,6 +1352,7 @@ which about doubled prompt speed on the measured card. | 0.2.0 | RTX PRO 5000 emulating a 12 GB card (`--expert-cache 4448`, Q2_0 GGUF in place, cgroup RAM limit), 3 interleaved pairs | Zero-copy, io prefetch and the decode gate vs 0.1.4x: 32 GB RAM decode 1.70 / 2.56 / 2.88x (story / code / doc8k; 34.0 / 28.0 / 21.7 -> 57.6 / 71.7 / 62.6 tok/s), prompts 1.54 / 1.91x; 16 GB decode 1.16 / 1.25 / 1.25x (the gate stays closed), prompts 1.63 / 1.68x. On a real RTX 3060 12 GB (32 GB cgroup) zero-copy alone gave 1.14 / 1.44 / 1.47x decode | | 0.2.1 | RTX 3060 12 GB, IQ3_XXS `experts.bin` pack (43 GB), `--mmap-experts`, cgroup RAM limit, 5 pairs | io prefetch and the gate: 32 GB decode 1.38x / 1.21x / 1.33x (story / code / doc8k), prompts 4K 1.04x, 20K 1.06x. At 16 GB decode +3..8% but the cold 4K prompt 4-6% slower, so it stays off (room 38%) | | 0.1.43 | RTX 3060 12 GB, 32 GB, Linux, IQ2_XS, 20.5 GiB experts in RAM, v0.1.43 as baseline, 47 frozen Korean requests replayed in fresh engines | `STRATA_RAM_ADAPT`: decode 43.26 -> 50.40 tok/s (+16.5%); file-tier demand reads per generated token 14.15 -> 2.67. One machine, one quantization | +| 0.2.1 (#3060) | RTX 3060 12 GB, 32 GB RAM, Linux NVMe, IQ2_XS and IQ3_XXS read in place, 20.5 GiB of experts in RAM, `--adapt-async 1`, `--spec 3`, fresh engine and dropped page cache per run, 3 interleaved runs | `STRATA_RAM_ADAPT` with the stage-buffer copy and `=1` against `=8` before it, 120 ShareGPT requests: IQ2_XS decode 48.71 -> 51.40 tok/s, prompt 137.4 -> 141.5, storage reads 408 -> 308 GB; IQ3_XXS decode 33.07 -> 38.71, prompt 97.8 -> 104.2, reads 1105 -> 717 GB (off: 37.70 and 23.24 tok/s). `standard-v1`: within noise. One machine; the author's numbers, not yet repeated here | | 0.1.45.3 | RTX 3060 12 GB, IQ2_XS, 20 GiB of experts in RAM, cgroup 34 GB, SATA emulated at 450 MB/s, 5 pairs | Prompt-chunk planner `8192 -> 3840`: 4,101 tokens 138.1 vs 138.2 tok/s (one chunk either way); 20,400 tokens 334.0 -> 822.3 tok/s (2.46x, drive read 26.1 -> 2.7 GB, decode after 25.4 -> 42.6); 28,887 tokens 418.8 -> 910.4 (2.17x). With a real NVMe and a 32 GB cap it picks 8192 again | | 2026-10-11 reports | RTX 3090 + Ryzen 5 5600X | `--adapt-async 1` on the arena: x1.07-1.11 decode, 12 of 12 prompts faster ([report](../bench/results/2026-10-11-community-rtx3090-5600x-arena-async/README.md)). `STRATA_PIN_BY_NEED=1`: prompt read +5-7% at 56K-117K tokens ([report](../bench/results/2026-10-11-community-rtx3090-5600x-arena-pin-by-need/README.md)) | | 2026-10-11 report | RTX 5090 / Ryzen 9 9950X, paired 4K three-prompt test | `STRATA_ADAPT_CALLBACK_WARMUP`: 142.82 -> 207.75 tok/s ([report](../bench/results/2026-10-11-rtx-5090-callback-affinity/README.md)) | @@ -1281,6 +1410,7 @@ with `--batch 2` at 262,144 context saw 538 MiB at the free line become 395 MiB | `STRATA_SPEC_COUPLED` / `STRATA_SPEC_PROB` (0.1.40.2) | RTX 3060 IQ3_XXS, 200-token answers, 10 pairs | Median tok/s at temperature 0.3 / 0.7 / 1.0: default 42.4 / 43.2 / 43.3, coupled 40.6 / 42.4 / 43.3, rejection sampling 41.0 / 42.6 / 42.6 | | `STRATA_STAGER_SLEEP=1` | Ryzen 9 7940HS laptop, RTX 4070, IQ3_S, 64K (issue #1101) | Prompts of 5,914 and 22,305 tokens read 5-6% slower; whole-machine CPU use 77-90% -> 21-25%. An RTX 5070 read an 8K Q2_0 prompt 1.2% faster with spinning | | Stager threads for a GGUF read in place | Big-RAM box, 124K-token Q8 prompt | 57 -> 350-410 tok/s with the 4-thread RAM profile instead of the 32-thread SSD profile (#1353) | +| `STRATA_VRAM_FREE=device` (Windows, NVIDIA, #1911) | RTX 5090 (WDDM), Core i7-13700K, 64 GB, 128K context, image encoder loaded, `--expert-cache auto` | The switch reads the free VRAM of the whole card through NVML: with 6 GiB held by another process CUDA still read 30,994 MiB free where NVML read 24,348. Default starts ended with 336 to 602 MiB free (0.1.42, three starts) and 93 MiB to 10 GiB (0.1.40.3 and 0.1.41, six starts); with the switch and `--vram-reserve-mib 1500` 973 to 1,392 MiB free over seven starts and 1,107 to 1,288 over three on 0.1.42. A run that filled the card to 0 MiB free decoded 80-115 tok/s where the same text ran at 205-230 with 900 MiB or more free. The cache can only get smaller. Not measured: AMD cards and Linux (the switch is compiled for Windows CUDA builds only). | ### Threads, sockets and sessions @@ -1334,3 +1464,47 @@ mean KL from the stock model 0.063 nats (max 4.1), perplexity +15% on code, +2.3 the original 2,682 in 46 s. Speed: 4K IQ2_XS 465 prompt / 78.7 output tokens/s against 467 / 78.3 for the original. - UD-Q4_K_XL on a 64 GB PC with a 12 GB RTX 5070: 7-8.5 tok/s, picks the same tokens as llama.cpp on the same file at 97.5-99% of the positions of short greedy answers and 90-91% after a 16K prompt ([UNSLOTH_Q4.md](UNSLOTH_Q4.md#quality-against-llamacpp-on-the-same-file)). + +## Conversation cache copies on a slow host link (CUDA, opt-in) + +Where the card sits behind a slow host link, the conversation cache's copies are on the critical path of the next request. A turn checkpoint copies the DeltaNet state (118 MB on Qwen3.8-Flash-Next) from the card to the host. Parking a conversation copies its K/V and its checkpoints before the next prompt can start. These switches move the copies card-to-card in VRAM or onto background threads. All are off unless you set them. On HIP, gfx906 and Metal `STRATA_CKPT_ASYNC`, `STRATA_CKPT_GATHER` and `STRATA_PARK_ASYNC` stay off, and so do the two slot switches that need them. The answers and the parked images are the same bytes. + +The times below were measured by the author of the change (linxuhao, PR #3779) on one CMP 170HX (GA100, sm_80) on a PCIe Gen2 x4 link. We have no sm_80 card and did not measure them. Some of their park figures were taken with other opt-in switches set. + +| Switch | What | Reporter's figure (CMP 170HX) | +|---|---|---| +| `STRATA_CKPT_ASYNC=1` | A turn checkpoint's state is copied card-to-card into a VRAM stage and moved to the host by a background thread. A reader waits only for the copy it needs. The stage is one buffer the size of the state, allocated at the first save; if the allocation fails the save copies as before. | checkpoint 104-105 -> 34-35 ms (fresh vectors), 71.4 -> 0.9 ms (reused vectors) | +| `STRATA_CKPT_VRAM_SLOTS=N` (0-16, with `STRATA_CKPT_ASYNC=1`) | The last N saved states also stay in VRAM (N x 118 MB, only while 1.5 GB stay free). A restore from one copies card-to-card. | restore 114-126 -> 28-47 ms | +| `STRATA_PARK_ASYNC=1` | A park copies the K/V card-to-card into a VRAM stage (only while 1.5 GB stay free) and moves it to the host in the background. The checkpoints the request drops move into the parked image instead of being copied. | park of a 3.3K / 13K-token conversation 212-217 / 329-334 -> 64-75 / 68 ms | +| `STRATA_CKPT_POOL_READY=N` (1-16, with `STRATA_CKPT_POOL=1`) | The checkpoint pool keeps N ready checkpoints, sized at start and topped up in the background, so a save never faults in a fresh vector. It holds N x 118 MB of host memory from start-up. `STRATA_CKPT_POOL=1` alone is unchanged: it reuses dropped checkpoints and allocates nothing ahead of time. | with `STRATA_PARK_ASYNC=1` and `STRATA_CKPT_GATHER=1`: park 21.5-40.1 / 26.9 ms | +| `STRATA_CKPT_GATHER=1` | A checkpoint's 37 small card-to-host copies are gathered into one buffer and fetched with one copy. Not tested with a layer split across cards. | (in the row above) | +| `STRATA_PARK_VRAM_MIB=N` (with `STRATA_PARK_ASYNC=1`) | A park also keeps the K/V in VRAM slots (64 MiB granules, up to N MiB, only while 1.5 GB stay free). Switching back restores it card-to-card. | second and later restores of a run 33-51 -> 7-13 ms; the first is not faster | +| `STRATA_PARK_TRACE=1` | Diagnostic: the park's joins and timers on stderr. | - | + +An independent user (bitaccesscomau, one RTX 3090 on PCIe 3.0 x16) tried the `STRATA_CKPT_ASYNC=1` commit on its own on 0.2.6: the checkpoint save went from 73.2 to 62.4 ms, the first token of a short prompt came about 13 ms of 350 ms sooner (median of 4 pairs), and the answers were byte-identical. On a fast link the gain is small. + +The serve loop's `strata trace:` lines (`STRATA_TRACE`) now end with `@`, a steady-clock timestamp. + +## CUDA opt-in decode switches measured on a CMP 170HX (sm_80; off unless you set them) + +The author of the change (linxuhao, PR #3779) measured these on one CMP 170HX (GA100, 70 SMs) with the Qwen3.8-Flash-Next IQ3_S native pack, `--spec 3`, decode after a prompt of about 3,000 words, a fresh engine per run, reference and switch runs interleaved. We have no sm_80 card and did not measure them. Both switches keep every output bit by construction (the greedy answers to 11 prompts were the same with the switch on and off, on their card). Neither does anything on HIP, gfx906 or Metal. + +| Switch | What | Answers | Reporter's figure (CMP 170HX) | +|---|---|---|---| +| `STRATA_GRAPH_PRIO=1` | The verify window graph's kernel nodes run at their capturing stream's priority (`cudaGraphInstantiateFlagUseNodePriority`): the GDN gates and the QSA indexer branch at the highest, the shared expert at the lowest. Nothing changes on a card whose priority range is 0..0. | bit-exact | decode +1.8 % with `STRATA_QIL=1` (both runs above every reference run) | +| `STRATA_MMVQ_IL_PF=1` | Hoisted-load, exact-integer kernels for the interleaved small-batch matvec where the sm_80 table picks them (Q6_K only so far, [MMVQ_IL_TABLE.md](MMVQ_IL_TABLE.md)). On a card that is not sm_80 the value 1 does nothing. `=2` to `=6` force one variant everywhere (A/B only). | bit-exact | decode +1.4 % (two reference / on / reference / on sets) | + +Two sm_80 defaults come with the same change and are on without a switch, only on a compute capability 8.0 card: the wide dense dequant kernels (`STRATA_DEQUANT_WIDE=0` turns them off) and the sm_80 rows tables of the interleaved matvec (`STRATA_MMVQ_IL_SM80=0` turns them off). Both are bitwise. The reporter's figures: prompt GPU time of a 3,259-token prompt 857 -> 792 ms for the dequant, decode +2.7..+3.2 % for the tables. + +## CUDA opt-in prompt switches for sm_80 cards (off unless you set them) + +Also from PR #3779, measured by its author on the same CMP 170HX; none of the figures was measured here. `STRATA_PF_FUSED_NT=256` and `STRATA_PF_BATCH=N` keep every output bit. `STRATA_PF_FUSED_F16=1`, `STRATA_PF_FUSED_WS=1` and `STRATA_GDN_TC=1` change the output at rounding level: the author's teacher-forced KL against the bitwise base on 20 prompts is mean 0.0062 (F16 / WS) and 0.0157 (GDN_TC), top-1 agreement 100 %. + +| Switch | What | Reporter's figure (CMP 170HX) | +|---|---|---| +| `STRATA_PF_FUSED_NT=256` | The fused prompt-expert kernels with 256 threads and two blocks a multiprocessor (bitwise). Adds device code to every CUDA build. | one MoE layer of 3,256 tokens 8.27 ms | +| `STRATA_PF_BATCH=N` | Up to N experts per launch (above 128 only with the 256-thread kernels; bitwise). | with NT=256: prompts +7.6 % (4K), +4.9 % (16K), +4.3 % (52K) | +| `STRATA_PF_FUSED_F16=1` | f16 mma instead of the int8 products in the 256-thread kernels (rounding level). | 7.90 ms for the same layer | +| `STRATA_PF_FUSED_WS=1` | Warp-specialized kernel with the same F16 products; needs about 101 KB of shared memory, so sm_80 and sm_90 only (it says "not available" elsewhere). | 7.65 ms for the same layer | +| `STRATA_GDN_TC=1` | The DeltaNet recurrence of a prompt as a chunked scan on the tensor cores; needs 122 KB of shared memory a block (sm_80, sm_90). | recurrence 105 -> 34 ms at 3.3K tokens; prompts +3.9 % (4K), +6.0 % (16K), +6.7 % (52K) | +| `STRATA_PLE_COMPACT=1`, `STRATA_PLE_COPY_STREAM=1`, `STRATA_EMBED_VRAM=1`, `STRATA_DEQUANT_SIDE=1` | The PLE rows go up raw and are dequantized on the card, on their own stream; the token-embedding table in VRAM; the dense dequant on a side stream (CUDA only). All bitwise. | prompts +2.2 % to +2.6 % for the four together | diff --git a/docs/DOCKER.md b/docs/DOCKER.md index 81672d74..d0825fd6 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -115,6 +115,7 @@ screens; leave out what you do not care about. | `MODEL` | model size: `IQ2_XS`, `IQ3_XXS`, `IQ3_S`, `Q2_0`, `UD-Q4_K_XL`, ... ([MODELS.md](MODELS.md)) | Strata picks what suits the card, and says so in the log | | `FAMILY` | `qwen`, `unsloth`, `gyro`, `coder`, `swift`, ...; use `qwen` for the original ISTA-DASLab packs | installer recommendation; may differ by hardware | | `MODEL_PATH` | GGUF files you already have: a folder or one `.gguf`, **inside the container** (mount it with `-v`, `:ro` is fine) | download | +| `ALLOW_DOWNLOAD` | `1`: go on and download the model although model files of the older layout were left unread in `/data/models` (see [From the older image](#from-the-older-image)) | stop | | `CONTEXT` | how much text it remembers at once: `32k`, `64k`, `128k`, `256k` or a number | the largest that fits | | `PARALLEL` | requests answered at the same time, 1 to 8 | fitted to the card | | `VISION` | `off`, `on` (the model reads pictures), `gpu`, `cpu`; the picture-reader file (about 0.9 GB) is downloaded with the model | `off` | @@ -276,7 +277,10 @@ package and start through `strata launch`. Mapping: A volume from the older image is picked up: the first start moves `/data/models`, `/data/packs` and `/data/mtp` into `/data/Strata-data` (a rename inside the volume: nothing is copied or downloaded again, and the prepared pack is kept). The old `/data/config` is not read; the run settings are made again from the files. A folder you mounted yourself at one of those places -is left alone: point `MODEL_PATH` at it. The container name, the volume and the port can stay as they were. +is left alone: point `MODEL_PATH` at it. If model files are still in `/data/models` when the container starts (a folder you mounted there, or +a move that failed) and `MODEL_PATH` is not set, the start **stops at once and says where the files are**: it would otherwise download the model +again, tens of GB, because this image does not read that place. Name the folder in `MODEL_PATH`, or set `ALLOW_DOWNLOAD=1` to download anyway. +The container name, the volume and the port can stay as they were. ## Build it yourself @@ -296,13 +300,14 @@ to the system or the graphics driver (`packaging/binary_deps.py`); finally it ch library inside the finished image. A package that fails any of these stops the build. Nothing is pushed anywhere. `docker/smoke-test.sh` runs the checks we ran on real cards (serves, key, chat, tool call, monitor, clean stop, memory freed, restart); see its first lines for the variables. -**From source.** `docker build -t strata:src .` in the repository compiles the CUDA 13 engine inside Docker, makes the package -and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, much faster). For a GTX 10, P100 or -V100 build the CUDA 12 variant: `docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 ---build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 .` (the build turns on the Pascal / Volta code by itself -when an architecture below 75 is listed, and names the package `cuda12` with driver 575.51). For AMD and Intel -builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result with -`packaging/package_engine.py` and use `docker/build.sh`. +**From source.** `docker build -t strata:src --build-arg STRATA_COMMIT=$(git rev-parse HEAD) .` in the repository compiles the CUDA 13 +engine inside Docker, makes the package and puts it in the same kind of image (`--build-arg CUDA_ARCHITECTURES=89` for one card only, +much faster). `.git` is not copied into the build, so the commit comes in as `STRATA_COMMIT`; without it the Terminal stage stops. +For a GTX 10, P100 or V100 build the CUDA 12 variant: `docker build -t strata:src-cuda12 --build-arg STRATA_COMMIT=$(git rev-parse HEAD) +--build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 .` +(the build turns on the Pascal / Volta code by itself when an architecture below 75 is listed, and names the package `cuda12` with +driver 575.51). For AMD and Intel builds from source see [AMD_HIP.md](AMD_HIP.md) and [INTEL.md](INTEL.md); then package the result +with `packaging/package_engine.py` and use `docker/build.sh`. ## Publishing the images (for maintainers) diff --git a/docs/INTEL.md b/docs/INTEL.md index 15615039..85b501da 100644 --- a/docs/INTEL.md +++ b/docs/INTEL.md @@ -127,9 +127,13 @@ the oneAPI runtime image with the serve pipes attached. Paths in the config's `a "sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "repetition_penalty": 1.05}} ``` -With `--stream-experts` any expert left out of VRAM is read from the SSD and computed on the CPU when routed, so the reserve -matters: on the B70 with Coder IQ1_M a 1,536 MiB reserve left the cache 128 experts short and decode fell to 5-10 tok/s, while -1,024 MiB fits all 12,288 with 2 GB of VRAM free. +A native (IQ) pack takes `--spec` 2 at the smallest: the engine refuses `--spec 0` and `--spec 1` on one (it needs `--native SHARD1`, `--spec T` +with T >= 2 and `--prefill CHUNK`), so speculative decoding cannot be turned off for these packs. + +With `--stream-experts` under `STRATA_VERIFY_NO_HOST=1` (the `strata-sycl.sh` default) there is no SSD expert tier: every expert +must be in VRAM or in the pinned RAM mirror (`STRATA_MIRROR_MIB`), and the engine refuses to start when the two do not cover the model +("REFUSED: N experts are neither in VRAM nor mirrored"). Raise the mirror or lower `--max-context`. So the reserve matters: on the B70 +with Coder IQ1_M 1,024 MiB fits all 12,288 experts with 2 GB of VRAM free. ## Things that matter on this GPU diff --git a/docs/INTEL_ARC.md b/docs/INTEL_ARC.md index 4adf07a3..a38fab0d 100644 --- a/docs/INTEL_ARC.md +++ b/docs/INTEL_ARC.md @@ -47,6 +47,9 @@ engine package. Otherwise [build the image yourself](DOCKER.md#build-it-yourself `sudo apt install docker.io git`, then `sudo usermod -aG docker,render $USER` and log in again. - VRAM: the port keeps the experts on the card (`--stream-experts`). A 32 GB card holds the Coder IQ1_M or IQ2_XS. Smaller cards mirror part of the experts in RAM and are slower. + Under the wrapper's `STRATA_VERIFY_NO_HOST=1` there is no SSD expert tier on `xe`: every expert must + be in VRAM or in the pinned RAM mirror (`STRATA_MIRROR_MIB`), and the engine refuses to start when + the two do not cover the model. Size the RAM accordingly, or lower `--max-context`. ## Build with Docker (what `setup --backend sycl` uses) diff --git a/docs/MCP_IMAGES.md b/docs/MCP_IMAGES.md new file mode 100644 index 00000000..610558fe --- /dev/null +++ b/docs/MCP_IMAGES.md @@ -0,0 +1,25 @@ +# MCP raster images in the web chat + +Enable this optional feature with `"mcp": {"image_results": true}` in the run configuration (alongside existing MCP settings). The value must be a JSON boolean (`true` or `false`); strings and numbers are rejected. It is disabled by default; text-only tool output and stream event fields remain unchanged when disabled. + +MCP image results are cached by SHA-256 next to the run configuration, in `.tool-media/`. The web chat receives small same-origin references instead of embedding base64 in chat history. PNG, JPEG and WebP are supported; SVG and arbitrary file/resource URIs are not rendered. Each call displays at most four images, each with at most 24 million base64 characters (about 18 MB decoded). If the cache cannot be written, the chat retains the text result and logs the cache error. + +`GET /tool-media/.` uses the existing server API authentication, validates the basename, and serves only cached raster files. The web client fetches images with its existing authorization headers, displays them outside collapsed tool details, and provides a blob download link. The cache persists across server restarts; if its files are removed, older image references are replaced with an image-omitted text note when preparing later turns. Disabling the feature or removing MCP configuration does the same, while preserving the tool text and allowing the conversation to continue. Malformed references are still rejected. A global disk-retention policy is not implemented yet. + +When the server has a vision encoder, tool images enter its existing image preparation path. Subsequent browser turns send `strata-tool-media:` references; the authenticated server resolves these only inside its cache. With no vision encoder, images remain visible to the user and the model receives the existing text-only fallback. This adds image transport, not a vision model. + +Search and image generation are supplied by configured MCP servers. Strata does not bundle a paid search provider or a ComfyUI installation. Machine-specific adapters and lifecycle hooks are not included in this change. + +## Validation without a GPU + +```powershell +python -m unittest serve.test_mcp serve.test_mcp_media +node --check serve/web/app.js +git diff --check +``` + +The transport tests use an existing mock engine and scripted tool response. They verify authenticated binary delivery, invalid media rejection, path traversal refusal, streaming metadata, forwarding to vision preparation and subsequent-turn cache resolution. They do not establish visual understanding or generation quality. + +## Browser layout checks + +Use a configured image MCP fixture and the mock engine; no GPU is needed for the transport or layout check. Include a long tool name and long text result, and check a running call while Stop is visible. At viewport widths 320, 390, 640, 768 and 1280 pixels, the document must not be wider than the viewport and the preview must fit its chat bubble. Also expand tool details, reload the page, and check that the preview and download link return. A missing cache may remove the picture but must not prevent the next text turn. diff --git a/docs/MMVQ_IL_TABLE.md b/docs/MMVQ_IL_TABLE.md index 1f3bae10..0d56273a 100644 --- a/docs/MMVQ_IL_TABLE.md +++ b/docs/MMVQ_IL_TABLE.md @@ -15,18 +15,20 @@ Which table a card gets: |---|---| | sm_86 (Ampere consumer) and sm_120 cards with fewer than 80 SMs (RTX 5070 and smaller) | `kIlRowsShared`, measured on an RTX 3060 and an RTX 5070 together (a cell is non-zero only if the worse of the two cards still gains 3%) | | sm_120 cards with 80 or more SMs (RTX PRO 5000 / 6000 Blackwell, RTX 5080 / 5090) | `kIlRows_120`, measured on an RTX PRO 5000 Blackwell (110 SMs); `STRATA_MMVQ_IL_120=0` gives them the shared table | -| sm_89 (Ada) and every other sm_80+ card | `kIlRowsShared` too. Nobody has measured sm_89 yet (we have no such card). | +| sm_89 (Ada) | `kIlRows_89`, ON by default on compute capability 8.9 cards only (0.2.7): the cells where an RTX 4070 (46 SMs) and an RTX 4080 (48 SMs) community run gave the same rows count, else 0 (the plain kernel); one column: Q3_K only. `STRATA_MMVQ_IL_89=0` or `STRATA_DEFAULTS=026` gives the shared table (`kIlRowsShared`) again, as in 0.2.6; an explicit `STRATA_MMVQ_IL_89=1` wins over the master switch. The output is bitwise the same either way (a table only changes how many rows a warp takes). Not measured on an Ada card by us: no sm_89 card has run `mmvq_il_parity` on this code, and the issue saw no end-to-end decode change on a 4090 or a 4080 (issue 3453), so the gain may be a microbenchmark one. The reporter tests 0.2.7 and reports back. No 5-8 column table: the 4080's changed in 10-14 of 20 entries between runs of the same card. To check a card: run `mmvq_il_parity` on it (it must end with `OK`) and an interleaved decode A/B with the variable at 1 and 0. | +| sm_80 (A100, A30, CMP 170HX) | `kIlRows_80`, `kIlRows58_80` and `kIl1Rows_80`, read off `--emit-table` by the author of PR #3779 on one CMP 170HX (not an A100: re-measure there); `STRATA_MMVQ_IL_SM80=0` or `STRATA_DEFAULTS=026` gives the card the shared table again | +| every other sm_80+ card | `kIlRowsShared` | | sm_75 and older | the path is off; the plain kernels run | | a card listed in `kIlArch` | its own table | -## Measuring sm_89 (or any other card) +## Measuring a card that has no table yet 1. Build with tests: `cmake -S . -B build -DSTRATA_BUILD_TESTS=ON` and `cmake --build build --target mmvq_il_parity`. 2. Close everything else on the GPU, then run `build/mmvq_il_parity --bench --emit-table` (a few minutes). It first checks bit-for-bit parity of every shape and every rows choice (it must end with `mmvq_il_parity: OK`), prints a `BENCH` line per shape and token count, and last a ready-to-paste block, one line per type. -3. Post the whole output on the issue. A maintainer pastes the block as `kIlRows_89[]` and adds - `{89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)}` to `kIlArch`. +3. Post the whole output on the issue. A maintainer pastes the block as `kIlRows_[]` and adds + `{, kIlRows_, sizeof(kIlRows_) / sizeof(IlRows)}` to `kIlArch`. 4. To try a table without rebuilding, set `STRATA_MMVQ_IL_ROWS="type:ncols:r0,r1,r2,r3,r4;..."`, for example `STRATA_MMVQ_IL_ROWS="23:3:0,0,2,4,4;12:2:0,1,1,1,1"` (the five numbers are the row classes below 2048, 4096, 8192, 12288 and above; each is 0, 1, 2 or 4). Then A/B the decode: same flags, `STRATA_MMVQ_IL_ROWS` set or unset, 10 @@ -34,3 +36,18 @@ Which table a card gets: The emit rule: per cell, the fastest rows count if it takes at least 3% off the plain kernel's time, else 0; shapes of one class that disagree give 0; a class with no measured shape copies its neighbour below. + +## The hoisted-load kernels (STRATA_MMVQ_IL_PF, sm_80 only so far) + +`STRATA_MMVQ_IL_PF=1` lets a second table pick, per cell, a variant of `native_mmvq_il` that issues every weight load of a +group before its dots and forms the dots as exact integers (`kIlPf_80` for 2-4 tokens and `kIlPf58_80` for 5-8, in +`src/kernels/cuda/native_mmvq.cu`; a cell is `variant << 4 | rows`, 0 = the rows table above with the plain kernel). Every +variant gives the same bits as the plain kernels. Only Q6_K has cells so far: on the CMP 170HX the variants tie the plain +kernel for Q4_K / Q5_K / IQ4_XS within the run-to-run noise. Unset or 0 keeps today's kernels; `=2` to `=6` run one variant +for every type and shape (A/B only). + +To measure a card: `build/mmvq_il_parity --bench --emit-table --pf 0,3,4` (`--emit-table` must come right after `--bench`). +Every listed variant is bit-checked against native_mmvq first, then timed interleaved per case (`--rounds N` rounds of 100 +calls, default 5; the median per variant on the `PFBENCH` lines). The last block (`variant << 4 | rows over --pf`) is in the +source form of `kIlPf_`. `il_pf_table` reads only sm_80's table today, so a new card's block also needs its lookup +there. Post the whole output on the issue. diff --git a/docs/MODELS.md b/docs/MODELS.md index 4eba8f4c..8f3fbedf 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -78,6 +78,8 @@ Tested on an RTX 3060 (Linux), an RTX 5070 (Windows), four R9700 cards (Linux) a and Strix Halo on Linux do not run it yet; on Strix Halo Windows the graphics memory is the RAM, so most of the experts are read from the SSD and an NVMe drive matters. +RTX 40 cards are covered by the engine packages since 0.2.7 (sm_89 code); we have not run one ourselves, see [DEEPSEEK41.md](DEEPSEEK41.md#the-engine-package) for a user's measurement. + **What you need:** a graphics card with 12 GB or more, 46 GB of RAM at least (64 GB is the tested comfortable size), an NVMe SSD, and the disk space above. Setup warns when disk or RAM is short and does not stop you. diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 36b35a81..37bd82aa 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -220,6 +220,14 @@ the Qwen layer split described above. On four Radeon AI PRO R9700 cards it reach An explicit `--expert-cache` on the first card is capped to leave room for them. - More cards pay off when the model's routed experts do not fit the faster ones. An extra slow card costs its own round per window and can make a good pair slower. +- **The split pays most when the CPU pool is the bottleneck.** On two identical RTX 2080 Ti 22 GB over a dual-socket Xeon E5-2696 v4 (AVX2 only, + 88 logical CPUs), a plain split moved decode from 35.2 to 51.0 tok/s (+45%) and an 11.6K-token prompt from 672 to 908 tok/s (+35%) at 180 W, + engine 0.1.49, six 300-token coding prompts. `STRATA_DECODE_TIMING=1` shows why: the window fell from 70.06 to 37.96 ms, almost entirely + because the CPU pool fell from 9.52 to 0.79 ms per window. The 5080 + 3090 measurement below, where decode with the second card is on par + with the 5080 alone, was taken over a fast CPU (Ryzen 9 9950X3D). When the CPU pool is what the window waits on, moving half the layers to a + second identical card removes that work. This is one pair of cards and one CPU, so there is no threshold, and the window breakdown from the + engine log is not the same statistic as the decode numbers beside it. Setup splits across two cards by itself; with two identical older cards + on a slow workstation CPU, compare one card against the split and tell us in [#3930](https://github.com/Niko1221/Strata/pull/3930). - For several conversations at once, `--batch N --batch-groups G --trim-stage-weights` pipelines them through the cards ([BATCHING.md](BATCHING.md)). diff --git a/docs/OLDER_GPUS.md b/docs/OLDER_GPUS.md index 92c26f9c..ace14e22 100644 --- a/docs/OLDER_GPUS.md +++ b/docs/OLDER_GPUS.md @@ -21,6 +21,7 @@ unchanged. Numbers are the reporters' own, on one machine each, unless the text | Cards | Compute capability | How it runs | What is different on it | | --- | --- | --- | --- | +| Quadro M6000, GTX 900 series (Maxwell) | 5.2 | a source build with CUDA 12.x | Opt-in, one reporter, [below](#maxwell-sm_52). No native half-precision arithmetic. Not in the ready-made CUDA 12 engine | | Tesla P100 | 6.0 | the CUDA 12 engine | `__dp4a` emulated (bit-exact); BF16 projections through fp32; seven scheduling switches on by default ([below](#tesla-p100-sm_60)); opt-in `STRATA_Q8_SM60=1` ([below](#pascal-gp100-a-q8_0-decode-kernel-opt-in)) | | Tesla P40 / P4, GTX 10 series | 6.1 | the CUDA 12 engine | BF16 projections through fp32 (cuBLAS has no BF16 GEMM there); dense weights dequantized by a wide kernel; expert mode 8 and its own interleaved-matvec table; opt-in `STRATA_DENSE_F32=1` ([below](#tesla-p40-sm_61-what-was-measured-and-changed)) | | Tesla V100, Titan V | 7.0 | the CUDA 12 engine | BF16 projections on the FP16 tensor cores; prompt attention on `mma.m8n8k4`; a leaner attention kernel. See [NVIDIA_V100.md](NVIDIA_V100.md) | @@ -41,6 +42,23 @@ too and cannot hold any of the model. | Radeon PRO V520 / Pro 5600M (RDNA1) | gfx1011 | built by hand: `-DCMAKE_HIP_ARCHITECTURES=gfx1011`; builds with 0 errors, untested on hardware | | Instinct MI50 / MI60, Radeon VII | gfx906 (wave64) | built by hand: `-DSTRATA_HIP_GFX906=ON` | +### Maxwell (sm_52) + +One reporter ran Strata v0.1.44.1 on two Quadro M6000 24 GB (Ubuntu, driver 580) with Qwen3.8-Flash-Next at IQ1 and saw about +22 tokens a second. Nobody has checked the answer text on these cards yet, and Maxwell has no native half-precision arithmetic, +so treat it as a test. The ready-made CUDA 12 engine holds no sm_52 code; build from source with a CUDA 12.x toolkit (CUDA 13 +cannot compile for Maxwell): + +``` +cmake -B build -G Ninja -DSTRATA_EXPERIMENTAL_SM60=ON -DCMAKE_CUDA_ARCHITECTURES=52 +cmake --build build -j +``` + +CMake prints a warning for sm_52 and goes on. A release build still needs sm_75 or newer, and without `STRATA_EXPERIMENTAL_SM60=ON` +the build stops as before. `setup.py` does not install an engine for a Maxwell card, because none of the ready-made engines holds +code for it. On a PC with only Maxwell cards it lists the card as not supported, prints this recipe as a warning and stops. If you +try the build, please post a short chat and one code answer from the card. + ## NVIDIA: the CUDA 12 engine CUDA 13 dropped Pascal and Volta and cannot compile for them. Setup therefore keeps a second engine, built with CUDA 12.9 and @@ -129,7 +147,7 @@ in [DETAILS.md](DETAILS.md#rtx-30-series-sm_86-and-tesla-p100-sm_60-bitwise-deco ## Pascal GP100: a Q8_0 decode kernel (opt-in) GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projections read their weights at 40-80 GB/s of about -730, decoding K- and i-quant blocks one int at a time. Two opt-in changes, both measured on a PH402 only: +730, decoding K- and i-quant blocks one int at a time. Six opt-in changes, all measured on a PH402 only: - **`STRATA_Q8_SM60=1`** packs every Q8_0 dense matrix and the head into the planes of `STRATA_Q8_PACKED` and runs them on `src/kernels/cuda/q8_sm60.cuh`: a warp per row, 16-byte weight loads, activations copied once per workgroup into shared memory, @@ -141,14 +159,91 @@ GP100 (P100, PH402) is the one Pascal chip without `__dp4a`. Its dense projectio - **`STRATA_IQ_STAGE_TABLES=1`** stages IQ3_XXS and IQ3_S codebooks in shared memory in the grouped expert kernels. Bitwise the same output. Interleaved A/Bs on a Tesla P100 showed no end-to-end change, so it is off by default. On an RTX 3090 Ti, forced on, the same layers took 3-13% longer. +- **`STRATA_DOWN_WS=1`** (compute capability 6.0 only, CUDA build with `STRATA_EXPERIMENTAL_SM60`): the verify window's IQ4_NL / Q2_0 + expert down rows (n_ff 640) take `native_down_ws_kernel`. It stages a block's rows in shared memory with 16-byte loads and then + runs expert mode 0's row dots on them, so the output is bit for bit mode 0's (and mode 8's, which equals it). The author's numbers + on one PH402 die, Swift 1.5 IQ3_S, one-token window: IQ4_NL 72.6 us (mode 8, the cc 6.0 default) and 54.5 us (mode 0) become + 42.3 us; Q2_0 53.5 / 65.4 us become 38.6 us. It replaces the down step in either expert mode. Not measured end to end on a + single card here. +- **`STRATA_PATTN_SM60=1`** (prompt reading with int8 K/V, CUDA build with `STRATA_EXPERIMENTAL_SM60`, compute capability 6.x): below + sm_70 the prompt reads each QSA layer's attention through the decode kernels, 32 queries a call, with 817 KB of partial results a + query and a merge kernel. The switch runs a score kernel and a value kernel that merges as it folds + (`src/kernels/cuda/qsa_pattn.cu`), in the same scratch and with the same arithmetic in the same order, so the output matches the + decode kernels bit for bit. If a launch fails or the shape does not fit, the usual loop runs. The author measured a 1,536-query + chunk's attention at 43.3 -> 30.8 ms per QSA layer at 26K context on one GP100 die, and 2-3% less time on 8K-150K token prompts + on four dies; we have not measured it here, and nobody has measured compute capability 6.1. `qsa_pattn_parity` (built with the + tests in this build) checks the bytes on random data. +- **`STRATA_SELECT_LONG=1`** (decode, CUDA build with `STRATA_EXPERIMENTAL_SM60`, compute capability 6.x by default): past + `STRATA_SELECT_LONG_AT` cells (default 65,536) a decode window's QSA select runs a top-k over several CTAs a query (six kernels) + and a decode block scorer without warp shuffles, in place of one CTA a query. They return the same ids and the same score bits + (`qsa_select_long_parity` checks this on random data). Each costs a few more kernels a call, which only a long context pays + back, so the verifier keeps a second set of window graphs for it: expect some more VRAM for graphs, and nothing changes below + the threshold. `STRATA_TOPK_MULTI=0` and `STRATA_SCORES_DX=0` turn one half off. The author measured, on four GP100 dies with + every expert resident and `--pipeline-windows 3`, 51.0 -> 52.5 tok/s (+2.9%) decoding 400 tokens at 115K context, and no change + below 64K; we have not measured it. A build without the sm_6x kernels ignores the switch with a warning. +- **`STRATA_MMQ_WS=1`** (prompt reading, CUDA build with `STRATA_EXPERIMENTAL_SM60`, every visible card compute capability 6.0): a + layer whose routed experts are all resident in VRAM, on this GPU alone (no peer, CPU or streamed share), runs its gate/up as one + weight-stationary launch over all its experts, one `swiglu_quant` over all its rows and its down as one launch, in place of a + gate/up, swiglu and down MMQ launch per 16-expert group. A CTA holds 128 or 256 weight rows of one expert and runs them against + up to 64 of that expert's rows, so each weight block is decoded once per pass. Gate/up for IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS and + IQ3_S, down for Q2_0 and IQ4_NL; the products keep MMQ's int8 values, scales and per-32-value epilogue order, so the results are + MMQ's bits. Every other layer keeps its path. `STRATA_WS_FAST=1` adds a down kernel for the IQ4_NL 32-token tier with fewer + instructions per pass (the same bits). The author measured, on four GP100 dies with every expert resident, prompt reads 31-37% + shorter (240 tokens 2,156 -> 1,364 ms; a fresh 26K read 41,231 -> 28,555 ms; one run per arm) and decode unchanged; we have not + measured it. A single 16 GB card that keeps experts in RAM takes the per-group path. `prefill_ws_parity_test` compares the + products with MMQ on random experts; its verdict needs a GP100. -Neither change is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default +None of these changes is measured on compute capability 6.1, which has `__dp4a`. Two practical notes for GP100 cards: the default application clock is 759 MHz and a layer split leaves each die idle most of a window, so lock the clocks (`nvidia-smi -i -ac 715,1050` as administrator). And a second engine pinned to the same logical CPUs halves this one's decode; keep two engines on different logical CPUs. `tools/q8_sm60_check.cu` checks the kernel against a CPU reference on these shapes (1-8 columns). +### Pascal GP100: 4-bit gate/up expert slots (opt-in, `STRATA_EXPERT_NIBBLE=1`) + +On a GP100 die the verify window's gate/up expert kernels wait on each block's serial chain (the weights, two codebook +lookups per four weights, the emulated dp4a, the reduction), not on memory bandwidth. IQ2_S, IQ3_XXS and IQ3_S have +only 3 or 8 magnitudes in their grids, so every weight is one of at most 16 signed values: `STRATA_EXPERT_NIBBLE=1` +keeps those layers' gate/up experts in VRAM as 16 bytes of 4-bit codes per 32 weights (one 16-byte load), with the +integer scale and the fp16 `d` of each block kept as they are, and decodes four weights in 1-4 integer instructions. The +down rows stay GGUF blocks. The host copy, the pack and its tools do not change: the conversion runs on the GPU while +the slots are filled. Only the CUDA build with `STRATA_EXPERIMENTAL_SM60` has the kernels. + +- **The answers are meant to be bit for bit the default's.** The 4-bit kernels run the production integer chain and float tail in + the production order (`native_gu_multi_kernel`'s sub-16 rows), and SwiGLU, the q8_1 step and the down projection are + the layout's own (mode 8 on a GP100). At every start each item is decoded with the production loader, encoded, + decoded from the written code and compared, and the GGUF blocks are rebuilt from every slot and compared with the + blob byte for byte; any difference refuses the start and names the layer. The prompt path's MMQ gathers the GGUF + blocks rebuilt from the slots (the copy it makes today, with the 4-bit codes read instead): the same bytes. The kernels that + existed before this change have the same SASS in the sm_60 build with and without it (446 kernels in `iq_kernels.cu` compared). + `iq_nibble_parity --synthetic-only` checks the codec, the rebuilt blocks and the expert step on random experts of every format + pair with no model file; `iq_nibble_parity ` does the same on a model's layers, against the GGUF blobs in mode 8 and + in the CUDA layout (`STRATA_SM60_TABLE=0`). Both need a GP100. +- **It needs every expert in VRAM** on the card that runs its layer: a profile that ranks every pair, room for the + larger slots (per layer of 512 experts: +175 MiB for IQ3_S, +250 MiB for IQ3_XXS, +350 MiB for IQ2_S), and a prompt + path with its own buffers, no loan of cache slots (`--no-prefill-borrow` on one GPU; a layer split's stages keep + their own when their cards have room, #340). `STRATA_EXPERT_NIBBLE_SKIP=` keeps layers in their GGUF slots; + `STRATA_EXPERT_NIBBLE_FMTS=22,18,21` picks the formats. +- **It does not start with what it cannot serve.** With the switch set, a build without `STRATA_EXPERIMENTAL_SM60`, a card other + than compute capability 6.0, `--peer-device`, `--expert-cache-device1..3`, `--kv-grow`, `--vram-elastic`, no `--expert-profile`, + `--expert-cache 0`, `STRATA_MMQ_DIRECT`, `STRATA_PREFILL_MMQ=0`, `STRATA_PF_FUSED=1`, `STRATA_FS_SLOTS`, `STRATA_EXPERT_V2=1` or + `STRATA_EXP_MODE` other than 0 or 8 make the engine say so in a warning and start with the usual GGUF slots. What is only known + later (a layer with an expert out of VRAM, a loan of cache slots, a prompt chunk other than the one the run without the switch + reads) still refuses the start with the reason. The adaptive tier is off with the switch. `STRATA_EXPERT_NIBBLE_RECHECK=1` (debug) + hashes every 4-bit slot again after each request. +- **Opt-in `STRATA_NIB_GU_PROTO=1`** (with `STRATA_EXPERT_NIBBLE=1`): the 4-bit gate/up runs `nibx_gu_kernel` + (`nib_gu_proto.cuh`), the same row dot with the group's activations staged once per two row blocks by 16-byte + loads. The author measured, on one GP100 die, a layer's gate/up at 54-57 us instead of 67-72 us at one token (x1.24-1.27) and + x1.22-1.39 at two to four tokens. +- The author measured the switch on a PH402 SKU 200 (two boards, four GP100 dies of 48 SMs and 32 GB each, clocks locked at 715 / + 1050 MHz), Windows 11, CUDA 12.9, engine 0.1.45.3, Swift 1.5 IQ3_S (abliterated) pack, layer split 12,24,36, + `--trim-stage-weights`, MTP with `--spec-min-p 0.85`, `--pipeline-windows 2`, 1M context, every expert resident: 47 of 48 layers + converted (+12.7 GiB of VRAM over the four dies, +3.1 s of start-up). Decode of eight prompts (8K, 26K and 88K-token contexts), + token-weighted: 47.3 -> 51.9 tok/s (+9.7%; each prompt +9.5..+10.9%). Prompt reading 2.3..3.0% slower (the gather rebuilds the + GGUF blocks). The replies of 15 requests, including a 260K-token read, matched the engine without the switch. We have not + measured it on this code. + ## Tesla P40 (sm_61): what was measured and changed Three things run differently on compute capability 6.1 by default and a fourth is opt-in. Each gives the same bits as what it diff --git a/docs/PROMPT_CACHE_TAIL.md b/docs/PROMPT_CACHE_TAIL.md index 836e3b9e..8e1d3cf0 100644 --- a/docs/PROMPT_CACHE_TAIL.md +++ b/docs/PROMPT_CACHE_TAIL.md @@ -31,3 +31,14 @@ This is a separate conservative alternative to the Strata-2080Ti Daily's checkpoint-grid patch. The grid changes chunk boundaries to reach exact checkpoint intervals and failed its local paired numerical gate. This option does not claim that the original grid patch has been fixed or validated. + +## `--prompt-cache-every` does not set the size of the pieces a prompt is read in + +The option can look like a piece-size dial, because a mark every N tokens sounds like a cut every N tokens. In this engine it is not one: a periodic +mark is saved at a chunk boundary of the batched prefill and the read carries on, so no piece ends at it, and changing N does not change how the prompt +is split into runs. What cuts a read into runs is the list of places where a read has to stop and start again: a re-read (`STRATA_CKPT_REREAD`), +the system-prompt root (`--prompt-cache-root`), a message boundary (`STRATA_CACHE_MESSAGE_BOUNDARY`, see +[MESSAGE_BOUNDARY_CACHE.md](MESSAGE_BOUNDARY_CACHE.md)) and the start of the last turn. So the lever for a fresh long read is those cuts, not this cadence. + +What `--prompt-cache-every 0` does: it skips the periodic marks and the near-tail one (`--prompt-cache-tail` needs `--prompt-cache-every` above 0), so a client +that rewrote a turn before the last one mounts a farther mark and reads more of it again. The root mark is controlled by `--prompt-cache-root`. diff --git a/docs/README.md b/docs/README.md index ed4ebe06..9baad441 100644 --- a/docs/README.md +++ b/docs/README.md @@ -22,7 +22,7 @@ Use the guide for your GPU and operating system. Model and feature support can d | --- | --- | | NVIDIA RTX 20 / 30 / 40 / 50 | [Install](INSTALL.md#what-you-need) | | AMD Radeon (RX and AI PRO R9700) | [AMD / HIP](AMD_HIP.md) | -| AMD Ryzen AI Max / Strix Halo | [Strix Halo](STRIX_HALO.md) | +| AMD Ryzen AI Max / Strix Halo | [Strix Halo](STRIX_HALO.md), [on Windows](STRIX_HALO_WINDOWS.md) | | Intel Arc on Linux | [Intel Arc](INTEL_ARC.md) | | Apple Silicon | [Mac / Metal](MAC.md) | | More than one GPU | [Multiple GPUs](MULTI_GPU.md) | diff --git a/docs/SAFETY.md b/docs/SAFETY.md index 6145c448..43412633 100644 --- a/docs/SAFETY.md +++ b/docs/SAFETY.md @@ -10,11 +10,13 @@ you trust can check it. Where Strata does less than you might hope, the page say outside model service, you open the server to other devices or to the internet, or the agent searches the web or opens a page (see [What the agent can do](#what-the-coding-agent-can-do-on-your-pc)). - **There is no telemetry.** Strata sends no usage data, no crash reports and no analytics, and has no account to sign in to. -- **Starting and running a model never downloads anything.** Downloads and updates are separate steps that you start. +- **Starting and running a model never downloads anything**, except that `strata launch` updates an installed DeepSeek + engine package by itself when the signed feed has a newer one (below). Other downloads and updates are steps that you start. - **The server listens on your PC only.** Reaching it from another device needs an API key. - **Once a model is downloaded, Strata runs without internet.** Starting, loading, serving and chatting need no connection. Only things you ask for use it: the agent's web search and web pages, an outside model service, the tunnel, - and installs and updates (a first model install also fetches llama.cpp's preparation scripts). + and installs and updates (a first model install also fetches llama.cpp's preparation scripts), plus the DeepSeek engine + check of `strata launch` (without a connection it gives up after at most 10 s and the launch goes on). - **Downloads are checked.** Updates come from a signed feed. Every model file has a fixed SHA-256 and size, and an install stops if the pinned version of a file is gone (the details are [below](#how-downloads-are-checked)). - **In its default mode the coding agent asks before it changes anything**, and once per chat before its first web search or web page. @@ -44,7 +46,7 @@ Like any download, each connection below shows the other side your IP address an | --- | --- | --- | | Model files, the picture reader, the speed-up layer (MTP) | huggingface.co, or the mirror in `HF_ENDPOINT` if you set one | When you install a model | | The same files from ModelScope, for PCs that cannot reach Hugging Face | modelscope.cn | Only if you ask for it (`--source modelscope`). Strata never switches to it by itself | -| Engine, Terminal and Control updates | The signed feed on GitHub Releases of Niko1221/Strata | When you install an engine, press **Update engine** or **Check for updates**, or run `strata update`. Opening **Settings, Engine** does not connect: it shows the result of your last check | +| Engine, Terminal and Control updates | The signed feed on GitHub Releases of Niko1221/Strata | When you install an engine, press **Update engine** or **Check for updates**, or run `strata update`; the DeepSeek engine also on `strata launch` (below). Opening **Settings, Engine** does not connect: it shows the result of your last check | | App updates | `latest.json` on the same GitHub Releases, through Tauri's updater | When you press **Check for updates** or **Update Strata** | | llama.cpp source code (a fixed commit) | github.com/ggml-org/llama.cpp | During a model install, if it is not on your PC yet. Strata uses only its model-preparation scripts | | Web search and web pages | DuckDuckGo, with Bing as the second source; or Exa, Perplexity or DeepSeek if you save a key for them. Any page the agent is asked to open goes to that page's site | When the agent uses its search or "open web pages" tool. In Manual mode it asks you first, once per chat | @@ -61,7 +63,11 @@ That is the full list found in the code. Some details: - **Nothing checks for updates in the background.** The app does not check when it starts, and not when you open Settings, Engine either: that screen shows the result of your last check, or nothing if you have not checked. The checks in the table run when you press a button or run a command. With no connection, the check says so and nothing else happens. The Terminal fetches an engine by itself only when none is - installed, and `strata launch` asks first. + installed, and `strata launch` asks first. One exception: `strata launch` with a DeepSeek model first checks whether the + signed feed can be reached (at most 10 s; without a connection it says nothing and goes on), then reads it, and when it has + a newer DeepSeek engine package for this PC, fetches and checks it, starts it once (`--version`), switches to it and removes + the older one. On a failure the installed one keeps running. Not when the launch is given `--dsv41-package` or + `STRATA_DSV41_EXE` is set (`strata_cli/launch/runner.py`, `upgrade_dsv41_engine`). - **Starting and serving never download.** `strata serve` and the app's load button fetch nothing. The app sets `STRATA_PACKAGED=1` and `STRATA_NO_ACQUIRE=1` for its parts (`apps/desktop/src-tauri/src/main.rs`), and the downloaders refuse to run under them (`strata_control/acquisition.py`, `apps/host/server/acquisition.mjs`). That is why the app @@ -164,7 +170,9 @@ In **Manual**: - **These ask:** writing or editing a file, any command that is not on a short list of look-only commands, and every tool you connect. In the browser tool, opening a page, clicking and typing ask. - **These do not ask:** reading files, listing and searching folders, and look-only commands such as `ls`, `cat` and - `git status`. A command with a redirect, a chain (`;`, `&&`), a variable or anything else the check does not recognise asks. + `git status`. Each of those commands runs unasked only with options that just look: `sort -o FILE`, `rg --pre PROGRAM`, + `tail -f`, `date -s` and `git grep -O` ask, as does any option the check does not know. A command with a redirect, a + chain (`;`, `&&`), a variable or anything else the check does not recognise asks. - **Web search and opening web pages ask once per chat.** The first one in a chat shows a card with the search words and the service they go to, or with the address of the page. **Approve** covers the rest of that chat. **Deny** tells the assistant you did not allow the web, and it carries on without it. Plan and Bypass do not ask. The model picks the search words and diff --git a/docs/SOURCE_INSTALL.md b/docs/SOURCE_INSTALL.md index a4996c57..e7b1270e 100644 --- a/docs/SOURCE_INSTALL.md +++ b/docs/SOURCE_INSTALL.md @@ -33,6 +33,15 @@ Choose a pack that fits your machine; Q2_0 is an example, not a universal minimu In PowerShell, prefix the wrapper with `.\`, for example `.\START-HERE.bat`. `SETUP.bat` opens setup again to add a model or change settings. The wrapper can reuse an existing install; first-start and later load times depend on the pack, disk, RAM and backend. A model can take several minutes to load. +Run again over an installed model, setup pre-selects the size that is installed and marks it "(installed)", and `--yes` takes it: a repeat run +does not move the model to the recommended size. + +When no ready-made engine fits the PC, setup compiles one. That needs the Visual Studio 2022 Build Tools with the C++ workload; +Visual Studio 2019 is too old (the sources are C++20). With a CUDA toolkit, CUDA 13.0 to 13.2 accept Visual Studio 2022 only, and +Visual Studio 2026 works from CUDA 13.3. The CPU image encoder alone (no CUDA toolkit on the PC) builds with MSVC and takes any +Visual Studio that has the C++ tools. If setup cannot find an install it could use, name the file before running it, for example +`set STRATA_VCVARS=C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat`. Setup uses that file +only if it exists; a wrong path is answered as no build tools at all. ## From source: Linux diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md index e37db19f..7e0a23c3 100644 --- a/docs/STRIX_HALO.md +++ b/docs/STRIX_HALO.md @@ -5,8 +5,9 @@ shared by the CPU and the GPU). Strata runs there through the same HIP backend a **Status: experimental.** **DeepSeek V4.1-Flash runs here on Windows** (since 0.2.7): its own engine package is built for gfx1151 and the official IST-DAS -1.75 / 2.00 / 2.25 bpw sets run through it. Measured on the 128 GB box (64 GB BIOS carve-out plus 64 GB seen by Windows) with 2.00 bpw and the default Faster mode: answers 15-17 -tokens/s on code, 10-11 on chat; a 4K prompt 87 tokens/s, an 8K prompt 125 and a 32K prompt 177. The graphics chip and the CPU share the RAM, so the +1.75 / 2.00 / 2.25 bpw sets run through it. Measured on the 128 GB box (64 GB BIOS carve-out plus 64 GB seen by Windows) with 2.00 bpw and the default Faster mode, on the +2026-10-25 build (before the DeepSeek defaults of 0.2.7): answers 15-17 tokens/s on code, 10-11 on chat; a 4K prompt 87 tokens/s, an 8K prompt 125 and a 32K prompt 177. +On the 0.2.7 build the same box reads a 4K prompt at 214-233 tokens/s; the table below says which number comes from which build. The graphics chip and the CPU share the RAM, so the engine counts it once and reads the rest of the experts from the SSD. [DeepSeek on Strix Halo](#deepseek-v41-flash) has the details, the driver it needs and the limits. @@ -32,6 +33,8 @@ change BIOS or kernel settings. The manual Linux toolchain below is for reproduc DeepSeek V4.1-Flash comes with its own engine package on Windows and needs nothing extra: pick the model and the app or `strata launch` downloads it ([DeepSeek on Strix Halo](#deepseek-v41-flash)). +On Windows, [STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md) has the speeds measured on 0.2.7 with Qwen IQ3_S and DeepSeek, how memory is used and the traps. + ## DeepSeek V4.1-Flash The model runs through its own engine, `strata-dsv41`, as on the other platforms ([DEEPSEEK41.md](DEEPSEEK41.md)); on Windows the @@ -45,7 +48,8 @@ package is the AMD one built for gfx1151 (`strata-dsv41-...-windows-x86_64-hip-r | Context | 8K default; 32K and 64K work (an 8-hour 32K soak passed) | | Disk | the sets above; keep the files on the NVMe drive, they are read while it answers | -Measured on the maintainers' box (Ryzen AI Max+ 395, 128 GB unified, Windows 11, 2.00 bpw, Faster mode, DSpark auto, engine 0.1.51): +Measured on the maintainers' box (Ryzen AI Max+ 395, 128 GB unified, Windows 11, 2.00 bpw, Faster mode, DSpark auto, engine 0.1.51) on 2026-10-25, with the +build of that day and the DeepSeek stream's own test harness (before the 0.2.7 DeepSeek defaults; the 0.2.7 numbers are in the next table): | Workload | Result | | --- | --- | @@ -57,6 +61,21 @@ Measured on the maintainers' box (Ryzen AI Max+ 395, 128 GB unified, Windows 11, | 32K prompt | about 177 tokens/s | | Stability | 100-request, 1-hour (243 requests) and 8-hour 32K (646 requests) soaks passed on the engine line this package is built from | +Measured again on 2026-10-26 on the same box with the 0.2.7 release candidate (f-027-int2 `3e468f5de`, engine 0.1.51), installed through `strata launch` from a local +signed test feed, 2.00 bpw, Faster mode, DSpark auto, the default 8K context, `tools/strata_bench.py` through the server (three fresh prompts of 4,125 +tokens, 24 new tokens; chat is the median of nine answers of up to 100 tokens). One change at a time, to see which one moved the 4K prompt: + +| Setup on the 0.2.7 candidate | 4K prompt (tok/s) | Chat decode (tok/s) | +| --- | ---: | ---: | +| what `strata launch` writes (`--prefill-chunk 16384`) | 214-226 | 12.1-13.6 | +| `--prefill-chunk 8192` | 229 (214-234) | 14.9 (12.0-18.2) | +| `--prefill-chunk 8192` and `DS4_DEFAULTS=026` (the 0.2.6 DeepSeek defaults) | 139 (133-144) | 13.7 (11.9-22.0) | +| `--prefill-chunk 1024` and `DS4_DEFAULTS=026` | 133 (129-136) | 14.2 (12.3-22.1) | + +The 0.2.7 DeepSeek defaults account for the gap between 139 and 229; the chunk size matters much less than that on this build. The 0.2.7 +candidate with the 0.2.6 defaults still reads 133-139, above the 78.7-87.2 of 2026-10-25 below. That rest is not explained: the build of that +day, the harness and the prompt were different, and only this table changes one thing at a time. Compare numbers within one table, not across. + The verify window runs synchronously on this PC: setup writes `DS4_ASYNC_T=4` in the config's env (`STRATA_DSV41_ASYNC_T=8` restores the engine's default, any other value overrides). The engine's mailbox ("async") path is sized for cards that hold most of the experts and is slower here: measured 2026-10-25 (2.00 bpw, greedy, 256 tokens): code 15.87-16.33 → 20.14-21.28 tok/s @@ -65,7 +84,7 @@ the scheduling changes, and the drafter's own single-token windows stay async. T (its experts leave no room for it) and does not change. Prompts are read in 8,192-token chunks: setup writes `--prefill-chunk 8192` on this PC (STRATA_DSV41_NO_BIG_CHUNK=1 leaves the -engine's 1,024-token default). Measured 2026-10-25: 4K 78.7 → 87.2, 8K 108.9 → 125.1, 32K 155.2 → 176.9 tok/s; decode unchanged +engine's 1,024-token default). Measured 2026-10-25 (the build of that day, before the 0.2.7 defaults): 4K 78.7 → 87.2, 8K 108.9 → 125.1, 32K 155.2 → 176.9 tok/s; decode unchanged (16.53 → 16.59), because the chunk buffers take ~5 GB from the GPU expert tier and the RAM store's hit rate rises to compensate. The chunk's summation order changes, not the model (the repo's chunk-size KL check: 1024 0.1705, 2048 0.1692, 4096 0.1688, 8192 0.1695). @@ -167,7 +186,7 @@ kernel): they change speed, not answers. Nothing here applies to CUDA or to anot | `STRATA_Q8_PACKED`, `STRATA_Q6_PACKED`, `STRATA_MMVF_ROWS`, `STRATA_ATTN_LANECELL` | Decode layouts and kernels: packed Q8_0 / Q6_K weights, 4-row BF16 GEMV, one-cell-per-thread attention scores. | | `STRATA_EXPERT_V2`, `STRATA_TSUM`, `STRATA_LFUSE` | The grouped decode experts (IQ3_S / IQ4_NL), single-butterfly warp sums, fewer launches around the shared expert and the KV append. | | `STRATA_GDN_SPLIT`, `STRATA_QFUSE`, `STRATA_PLE_BATCH` | The GDN step over four blocks per head, activation images written by their producers, the PLE key / value projections of a verify window at once. | -| `STRATA_SH_STREAM=1` | The shared expert on a second stream beside the routed experts. Off by default on other AMD cards, but it pays on gfx1151 (decode +1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL at 8K). | +| `STRATA_SH_STREAM=1` | The shared expert on a second stream beside the routed experts. Off by default on other AMD cards, but it pays on Linux gfx1151 (decode +1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL at 8K). **Off by default on Windows gfx1151 since 0.2.7:** it measured 6.9% slower there with the same token ids ([STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md)). `STRATA_SH_STREAM=1` turns it back on. | Two further defaults change bits. `STRATA_HC_Q8` reads the hyper-connection weights as 8-bit (`STRATA_HC_Q8=0` restores the BF16 read), and on Windows the prompt is read in chunks of 8192 tokens (`STRATA_GFX1151_CHUNK=0` keeps 6144). About `STRATA_HC_Q8`: it @@ -272,7 +291,7 @@ more than the differences because other jobs shared the box, so read them as unc | IQ3_XXS | 8K | 1,127 -> 1,212 (+7.6%) | 51.64 -> 50.95 (-1.3%) | | IQ3_XXS | 128K | 1,252 -> 1,250 (-0.1%) | 50.88 -> 50.22 (-1.3%) | -With the shared-expert stream (`STRATA_SH_STREAM=1`, now a default) at 8K, 4 pairs: UD-IQ4_XS output 53.1 -> 54.05 (+1.8%), +With the shared-expert stream (`STRATA_SH_STREAM=1`, a default on Linux; Windows leaves it off since 0.2.7) at 8K, 4 pairs: UD-IQ4_XS output 53.1 -> 54.05 (+1.8%), UD-Q4_K_XL 49.5 -> 52.8 (+6.7%), prompt unchanged. **Other switch measurements** (Measured on: the same Ryzen AI Max+ 395) diff --git a/docs/STRIX_HALO_WINDOWS.md b/docs/STRIX_HALO_WINDOWS.md new file mode 100644 index 00000000..65681fa9 --- /dev/null +++ b/docs/STRIX_HALO_WINDOWS.md @@ -0,0 +1,136 @@ +# Strix Halo (Ryzen AI Max, gfx1151) on Windows: install, what you get, what to know + +This page is for a Windows PC with a Ryzen AI Max "Strix Halo" chip (Radeon 8060S / 8050S, `gfx1151`). It says what Strata does there out +of the box, what speed to expect with Qwen3.8-Flash-Next IQ3_S and with DeepSeek V4.1-Flash, and the traps on this hardware. The Linux +build, the toolchain and the opt-in switches are on [STRIX_HALO.md](STRIX_HALO.md); the DeepSeek details are in +[DEEPSEEK41.md](DEEPSEEK41.md). + +The structure of this page comes from the first Windows guide for this PC, written by HaiYunChuang (pull request #3029). It measured +engines 0.1.41 to 0.1.47 with a hand-made configuration (`--mmap-experts`, a list of switches, a batch file). Since then the app and +`strata launch` have taken over most of that, so this version describes the 0.2.7 install and every number in it was measured again. + +## 1. What this PC reaches + +Measured on 2026-10-26 on a GMKtec NucBox EVO-X2 (Ryzen AI Max+ 395, 128 GB shared memory: a 64 GB BIOS carve-out for the graphics chip +and 64 GB that Windows sees; Windows 11 Pro, AMD Adrenalin 26.10.1 / driver 32.0.32015.7029). Strata was the 0.2.7 release candidate +(Terminal and engine 0.1.51 built from commit `3e468f5de`, ROCm 10.2.0a20260930). The server was started with `strata launch` and +nothing else was set by hand; the speeds come from `tools/strata_bench.py` against the running server (three runs per test, medians, +the engine's own timings; the model is loaded before the clock starts). The numbers can still move before the release is cut. + +**Qwen3.8-Flash-Next IQ3_S** (`strata launch --family qwen --model iq3_s`; 131,072 tokens of context, int8 KV, pictures on): + +| Test | Result | +| --- | --- | +| Short chat, answer speed | **44.0 tok/s** (40.6 to 59.5: code-like answers are faster than prose) | +| Short chat, time to first token | 0.60 s | +| 4K prompt, read speed | **755 tok/s** (first token after 5.4 s) | +| 16K prompt | **821 tok/s** (19.6 s) | +| 32K prompt | **792 tok/s** (40.6 s) | +| Coding-agent session, 6 turns | 69% of the prompt came from the conversation cache; answers 47 tok/s; 4.5 s to the first token per turn | + +**DeepSeek V4.1-Flash 2.00 bpw** (`strata launch --family deepseek41 --model ist-das-2.00bpw`, Faster mode, the drafter on; the 4K row is +the default 8K context, the others 64K context with `--context 64k`): + +| Test | Result | +| --- | --- | +| Short chat, answer speed | **12.1 to 13.6 tok/s** | +| 4K prompt | **214 to 226 tok/s** (about 19 s to the first token) | +| 16K prompt | **326 tok/s** (51 s) | +| 32K prompt | **342 tok/s** (97 s) | +| Coding-agent session, 6 turns | 70% from the conversation cache; answers 14.2 tok/s; 17 to 31 s to the first token per turn | + +These are speed measurements. They say nothing about answer quality, and the short-chat range depends on the text. The DeepSeek 2.25 bpw set +and the other Qwen sizes were not measured for this page. + +The DeepSeek 4K prompt here (214 to 226 tok/s) is higher than the 87 tok/s on [STRIX_HALO.md](STRIX_HALO.md), which was measured on 2026-10-25 with an +earlier build. The 0.2.7 DeepSeek defaults explain most of the gap (the same build with `DS4_DEFAULTS=026` reads 133 to 139 tok/s); the table there +changes one thing at a time. + +## 2. Memory and the BIOS + +- Allocate a **fixed carve-out** to the graphics chip in the BIOS (64 GB on the measured PC). The engine counts the carve-out and the + RAM that Windows sees as one pool and does not change any BIOS or driver setting. +- The graphics chip and the CPU share that pool. For Qwen IQ3_S the engine reads the experts into RAM, keeps them there (it does not + register the arena with the GPU driver on an integrated chip) and gives the expert cache every slot: the start log says + `expert cache auto ... -> 24576 slots` and `expert arena: NOT registered with the GPU driver (integrated GPU, UMA mode)`. The process held + about 49 GB and 10 GB of RAM stayed free. Close other large programs before you load a model this size. +- The default of four parallel slots takes 7.5 GiB of the shared pool for slot sessions (the log says `--batch: 4 slot sessions ... take + 7.54 GiB`). With IQ3_S the cache still held every expert, so there was nothing to gain from fewer slots here; with a bigger model there may be. + +## 3. Install + +1. Use the Windows app (`Strata--windows-x64-setup.exe`) or the Terminal. The engine for this chip is the `windows-x86_64-hip-rdna3` + package; the app or `strata launch` downloads it on the first start, and `strata update` keeps it current. +2. Choose the model in the app, or `strata launch --family qwen --model iq3_s`. With model files you already have, add + `--model-path ` (for IQ3_S the two shards are in one folder: shard 1 is the main model, shard 2 holds the per-layer embedding + table and must stay a separate file). +3. The first start took about 20 minutes on the measured PC with the model files already on disk: the engine package (158 MB), the + check of the 84 GB of model files, the picture reader (0.9 GB), the draft layer (about 5 GB) and the one-time pack. The next start + took under two minutes. + +What `strata launch` wrote for IQ3_S, with no switches of mine (these are the settings to copy if you drive the engine by hand): + +``` +--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5 --mtp +--max-context 131072 --kv int8 --vision --vram-reserve-mib 700 (backend hip, GPU picture reader) +``` + +and for DeepSeek 2.00 bpw: `--max-context 8192 --dspark auto --dspark-conf 0.65 --prefill-chunk 16384`, with `DS4_ASYNC_T=4` in the +environment and the package's `rocm/bin` folder on the library path. + +## 4. What is on by default + +- On `gfx1151` the engine turns on exact speed switches by itself (19 on Linux, 18 on Windows, which leaves `STRATA_SH_STREAM` out, see below; the start line lists them; `STRATA_GFX1151_DEFAULTS=0` turns them all + off, and a switch you set is kept). They are the ones that give the same answers as without. `STRATA_HC_Q8=1` is also on here (decode + about 9% faster, near-tie tokens can differ); `STRATA_HC_Q8=0` keeps the old read. +- The hipBLASLt table for `gfx1151` ships in the package and is chosen without a setting (`prefill gemm: hipBLASLt tuning enabled (32 rows, + gfx1151, version 100500)` in the log). A hand-built engine has to be pointed at it: [AMD_HIP.md](AMD_HIP.md). +- `--mmap-experts` is not needed. The first Windows guide found that without it the pinned expert arena used up the graphics memory + budget and decode fell to 28 tok/s on engine 0.1.41; the engine on this page sizes the cache from the shared pool and reaches every slot. +- DeepSeek runs in "Faster" mode here: 5 of 6 experts per word. The app and `strata launch` say so; the quality change is small. + +**`STRATA_SH_STREAM` (the shared expert on its own stream) is off by default on Windows `gfx1151` in 0.2.7, because it is slower there.** It stays +on by default on Linux `gfx1151`, where it was measured to help ([STRIX_HALO.md](STRIX_HALO.md)). The first Windows guide found the Windows +result on engine 0.1.41 (+13% decode with it off). Measured again on the 0.2.7 build as it was before this default changed (the switch was +on), with Qwen IQ3_S, three starts each, run in turn (on, off, on, off, on, off), the same quick suite after every start: + +| Start | `STRATA_SH_STREAM` | Chat decode, median of 9 answers (tok/s) | 4K prompt (tok/s) | +| --- | --- | ---: | ---: | +| 1 | 1 (the default then) | 43.9 | 742.9 | +| 2 | 0 | 48.3 | 742.9 | +| 3 | 1 | 43.6 | 746.8 | +| 4 | 0 | 46.0 | 740.8 | +| 5 | 1 | 43.2 | 745.5 | +| 6 | 0 | 46.6 | 739.4 | + +With the switch off, decode was 6.9% faster (46.6 against 43.6, the median of the three starts) and the code-like question 14% faster +(67 against 59 tok/s); all three pairs went the same way. The prompt speed did not change. + +The answers stay the same: on the same PC and build I ran five fixed greedy prompts (a short question, a code request, an explanation, a +4,091-token prompt and a 16,383-token prompt; 895 generated token ids) through the engine four times, with the switch on, off, on, off. The +token ids were identical in all four runs for every prompt. + +What 0.2.7 does: on Windows `gfx1151` the engine no longer turns the switch on by itself. To turn it back on, use `strata launch ... +--set STRATA_SH_STREAM=1` (or put `STRATA_SH_STREAM=1` in the environment of an engine you start by hand); a value you set is always kept. +`STRATA_DEFAULTS=026` brings back everything 0.2.6 did, including the switch on. This is one model, one PC and short answers; DeepSeek was +not tested with it, and Linux `gfx1151` has not been measured against it. + +## 5. Traps + +1. **Keep RAM free.** Qwen IQ3_S held 49 GB of 63.6 GB. A browser with many tabs, or a second model, is enough to push the PC into paging. +2. **Do not run two engines.** One model at a time on this PC; `strata launch --status` shows what is serving, `strata launch --stop` ends it. +3. **The graphics driver.** The 2025-03 driver failed at 32K context for DeepSeek. The measured driver is Adrenalin 26.10.1 (32.0.32015.7029). +4. **If Windows resets the driver** (screen flicker, the engine dies mid-answer), see the driver-reset entry in + [TROUBLESHOOTING.md](TROUBLESHOOTING.md#amd-cards). +5. **Other tuning from the first guide** (a longer `--prefill`, `STRATA_PF_*` switches, `--lookup-chain`): those results are for engines + 0.1.41 to 0.1.47 and a hand-made configuration. They were not repeated here, so they are not part of this page. + +## 6. Reproduce it + +``` +strata launch --family qwen --model iq3_s # then, from a source checkout: +python tools/strata_bench.py --url http://127.0.0.1:8080 --runs 3 --long +``` + +`--long` adds the 32K prompt. For DeepSeek add `--context 64k` to `strata launch` first; the default 8K context skips the 16K prompt and +the agent session. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 1c5035cb..23ca9934 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -1,6 +1,6 @@ # Troubleshooting -This page is for anyone whose install or startup fails. Find your symptom below. Each entry gives one fix. +This page is for anyone whose install or startup fails, or whose answers go wrong. Find your symptom below. Each entry gives one fix. Start from the route you installed: [desktop app or Terminal](INSTALL.md), or [source checkout](SOURCE_INSTALL.md). The normal release uses the app or `strata launch` and needs no `.bat` file. Detailed engine errors are in the [engine reference](DETAILS.md#troubleshooting). @@ -25,16 +25,25 @@ startup path for the app. For a fresh desktop install, download the one installe On Windows, open a new PowerShell window after installing. On Linux or Mac, use the full path the installer printed, normally `~/.local/bin/strata`, and add `~/.local/bin` to PATH if needed. Check `strata --version`. -**Strata could not find an engine for this computer.** -Run `strata doctor --live` and `strata update --check`. Check the selected GPU, driver and -[backend guide](INSTALL.md#what-you-need). Supported paths include Apple Silicon and Intel Arc on Linux; do not -assume every machine without an NVIDIA/AMD discrete card is unsupported. A model download can finish even when -no engine starts. Verify `strata launch --status` and `/health` before calling the installation successful. +**A warning says Strata "couldn't find an engine for this computer".** +The engine is the part that talks to your graphics card. Strata only warns and still downloads the model, and the model +files stay on your computer, but the model may not run until the right engine is installed. The usual reasons are that +no engine is installed yet and the update source has none for your card, that the engine found is for another make of +card, or that the graphics driver is too old. In the app, open Settings, then Engine. In the Terminal, the message names +the next step: run `strata update` and start again. Run `strata doctor --live` and `strata update --check` to see the +selected GPU and driver, and check the [backend guide](INSTALL.md#what-you-need). Supported paths include Apple Silicon and +Intel Arc on Linux, so do not assume every machine without an NVIDIA or AMD discrete card is unsupported. If the computer +has no graphics card Strata can use (only an Intel UHD or Iris chip, a virtual machine, or Windows on ARM), Strata says so +and there is nothing to install. Verify `strata launch --status` and `/health` before calling the installation successful. -**This model needs a newer engine.** -Unload running models, then use the app's engine update or `strata update`. Minimum engine versions vary by model and -backend. Check the model guide and the installed engine, not only the app version. If the feed has no compatible engine, -report the missing combination. +**"This model needs a newer engine." (the app), or a button called Update engine.** +Some models need an engine newer than the one installed: Gyro needs 0.1.45.1 or newer, NVFP4 needs 0.1.44, and NVFP4 +(NVIDIA, trained for FP4) needs 0.1.45. Minimum versions vary by model and backend, so check the model guide and the +installed engine, not only the app version. In the app, open Settings, then Engine, and press Update engine. It asks +first, keeps your model files and settings, and wants running models unloaded. In the Terminal: `strata update --check` +says what would change, `strata update` installs it (it switches to the new engine only after a test start). If the engine +you installed is the newest and the message stays, the update source has no newer engine for your card yet; report the +missing combination. **An update says it succeeded but `strata --version` is still old.** The Terminal switches to the updated Control on the next command, so run `strata --version` again. If it is still old, @@ -42,101 +51,323 @@ run the one-line installer once more; it keeps models and settings. The app, Con numbers; see [updating](INSTALL.md#updating) and the [release notes](https://github.com/Niko1221/Strata/releases). **A new engine misbehaves after an update.** -Stop the model, then use the app's rollback control or `strata components rollback`. Source-checkout engines use a -separate rollback workflow, `python setup.py --rollback-engine`, described in [source setup](SOURCE_INSTALL.md). +Stop the model, then use the app's rollback control or `strata components rollback`. An update keeps the engine it +replaced (one generation, about 210 MiB). Source-checkout engines use a separate rollback workflow, in `engine\.previous`: +`python setup.py --rollback-engine` puts the old one back and keeps the newer one there, so run it again to go forward +(#670). It is described in [source setup](SOURCE_INSTALL.md). -**The Mac app cannot be opened.** -Check that the download is for Apple Silicon and that macOS is 15 or newer. Follow -[Mac installation](MAC.md#the-desktop-app-and-strata-launch-on-a-mac). A warning alone does not establish that a file -is safe or intact: verify the download source and release before changing quarantine settings. Release signing and -test-build handling are described in [Mac packaging](../packaging/mac/README.md). +**On a Mac: "Strata is damaged and can't be opened", "cannot be opened", or "unidentified developer".** +Check first that the download is for Apple Silicon and that macOS is 15 or newer ([Mac installation](MAC.md#the-desktop-app-and-strata-launch-on-a-mac)). +Nothing is wrong with the file if the message is only about the developer: macOS marks everything a browser downloads, and +only lets a marked program run if Apple has checked it. Strata's release builds are checked by Apple ("notarised"): drag +Strata onto Applications and open it; the first time, macOS asks "Are you sure you want to open it?" and you press Open. A +test build that is not notarised says "damaged". Do not move it to the Trash. Open the Terminal app and remove the mark, +with the line that matches what you have (drag the file from Finder into the Terminal window to type its path): + + xattr -dr com.apple.quarantine ~/Downloads/ # the .dmg, before opening it + xattr -dr com.apple.quarantine /Applications/Strata.app # the app, after dragging it over + xattr -dr com.apple.quarantine # an unzipped Terminal folder + +Then open it again. If macOS says only "the developer cannot be verified", you can instead try to open it once, then open +System Settings > Privacy & Security and press "Open Anyway" next to the message about Strata. Only remove the mark from a +file you downloaded from the official release; a warning alone does not show that a file is safe or intact. Installs made +with `curl ... | sh` carry no mark and need none of this. To see which kind you have: `spctl -a -vv /Applications/Strata.app` +answers "accepted" and "Notarized Developer ID" for a notarised build. How the builds are signed is in +[Mac packaging](../packaging/mac/README.md). **The Linux AppImage does not open.** Make the downloaded file executable. It may need FUSE 2 (`libfuse2` on Ubuntu 22.04, `libfuse2t64` on newer Ubuntu; package names vary by distribution). Without FUSE, run the file with `--appimage-extract-and-run`. For a crash log, -run it with `--save-logs`; see the logs section below. +run it with `--save-logs`; see [Logs and bug reports](#logs-and-bug-reports). + +**Checking what is installed: `strata doctor`.** +It is a read-only check of the installed engine parts (it changes nothing): which engine and helper files a saved model +needs, and whether they are there. `strata doctor --live` also asks the computer which graphics cards it sees and compares +them with the cards the model is set to use; `--output json` prints the same as data. Put its output into a bug report. ## While installing or starting +**My PC froze, or got very slow, the first time Strata started.** +That is normal while it starts, most of all the first time. Strata loads 35-55 GB into your RAM, locks part of it for the +graphics card, and works out how much of the model fits on your GPU. The mouse can freeze for a few minutes. **Wait, and +don't close the window.** The next starts are much faster. Still frozen after 10 minutes? Restart the PC, close other +programs (browsers use a lot of RAM) and try again. If it keeps happening, pick a smaller size (Q2_0 or IQ2_XS). + **A download stopped.** Retry it in the app, or rerun the same `strata launch` command. Completed model-download steps are reused. Check free space and the error message. For an interrupted Terminal installer, rerun the install command. Only a source -checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup. +checkout uses `START-HERE.bat` / `./setup.sh` to resume source setup; it continues where it stopped. + +**Setup says the engine does not match GitHub's checksum.** +Setup checks the downloaded ready-made engine against the SHA-256 GitHub publishes. On a mismatch the file is corrupt or +was changed on the way, so setup deletes it and stops; run setup again to download it afresh. If GitHub gives no checksum +(offline, rate limited, your own mirror), setup warns and installs anyway. `STRATA_SKIP_SHA256=1` skips the check, only if +you insist. + +**The engine stops at the start with no line in its log, and the error says `the engine process ended: ...`.** +The error names how the system ended the engine process, because the engine log is silent then: for example `killed by signal 4 (SIGILL, Illegal +instruction)` on Linux and Mac, or `exit code 0xC000001D: illegal instruction` on Windows. An illegal instruction means the engine ran an instruction +the CPU cannot execute; the error lists the AVX, AVX2, FMA and F16C flags the CPU lacks, or says the CPU has them all, which is a bug in the engine. +Report it with the CPU model. **Startup takes a long time or the computer becomes slow.** Large models need time to check files, prepare packs and fill memory. A first launch can take many minutes; there is -no fixed startup time. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a +no fixed startup time. The engine reads 34-55 GB into RAM, and the second start is faster while the files are in the OS +cache. Watch progress and the engine log. If memory pressure is high, close memory-heavy programs and try a smaller model or context. DeepSeek V4.1-Flash needs 46 GB of RAM at least ([model page](MODELS.md#deepseek-v41-flash)); `strata launch --plan --family deepseek41 --model ist-das-2.00bpw` shows what your computer is missing. +Started from Task Scheduler, a start can be 24x slower: see [Running it at startup](DETAILS.md#running-it-at-startup-task-scheduler). +On Linux the engine asks the kernel to read the model files ahead (a cold start went from ~920 s to 70 s on one PC); +`STRATA_READ_AHEAD=0` turns that off. With transparent huge pages on `always`, the arena does not ask for `MADV_HUGEPAGE` +on top (a fragmented machine spent minutes compacting memory, #771); `STRATA_NO_ARENA_THP=1` skips that request on any setting. **The NVIDIA driver is too old.** Use the driver required by the engine package. CUDA 13 needs driver 580 or newer; older cards use the -[CUDA 12 route](OLDER_GPUS.md). After updating the driver and restarting if needed, open the app or rerun -`strata launch`. +[CUDA 12 route](OLDER_GPUS.md). Update it (NVIDIA App or [nvidia.com/drivers](https://www.nvidia.com/drivers)), restart the +PC if needed, then open the app or rerun `strata launch`. **Port 8080 is already in use, or I changed a running model's settings.** -Check `strata launch --status`. To replace your existing launch, rerun the intended command with `--restart`; -it stops current answers. To run beside it, choose another port, for example `--port 8081`, if memory permits. -Do not stop an unrelated program just because it holds the port. `--yes` alone does not restart a running model. +Strata may already be running: check `strata launch --status`. To replace your existing launch, rerun the intended command +with `--restart`; it stops current answers. To run beside it, choose another port, for example `--port 8081`, if memory +permits (source checkout: `START-HERE.bat --port 8081`). Only an address that is really taken says "already in use". Any +other reason (Windows keeps the port reserved, or the config's `"host"` is not an address of this PC) is printed as what +the OS said, with what to change (#769). Do not stop an unrelated program just because it holds the port. `--yes` alone +does not restart a running model. -**The engine stops on a small GPU or low-memory computer.** -Try a smaller pack or context. The draft layer also uses memory. In the app, set the model's Draft layer to Off; -in the Terminal, an explicit example is: +**The engine stops on a small GPU or low-memory computer. Can I turn the draft layer off?** +Yes. The draft layer (MTP) is what makes answers faster, and it takes about 1 GB of graphics memory (plus some RAM and a +memory copy that grows with the context). Without it the expert cache gets that memory back and answers are slower. Turn +it off for one model: in the app, the model's Drafting setting in Expert settings; in the Terminal: ```sh strata launch --family qwen --model q2_0 --context 32k --mtp off ``` -Use `--restart` if replacing an active run. Turning MTP off can slow decoding. Keep some VRAM free for the display; -setting the reserve to zero is not a general speed fix. +(older Terminals: `--set mtp=off --set spec-min-p=off`); by hand, add `"mtp": false` to the model's `strata-.json`. +The choice is kept per model and applied on every start. Use `--restart` if replacing an active run. Also try a smaller +pack or context. Keep some VRAM free for the display; setting the reserve to zero is not a general speed fix. -**Pictures do not work.** -The model, backend and installed engine package must include a compatible picture reader. Inspect the startup -error and the model guide. `--vision off` disables reading pictures; it is different from optional -[image generation](IMAGES.md). In the Terminal, use `on|off|gpu|cpu`, not source setup's `yes|no` spelling. +**I changed `strata-.json` by hand and the change came back.** +Engine options you add to `args` by hand (control vectors, `--spec`, `--vram-reserve-mib 0`, anything the app does not offer) +are kept. The file has two helper keys for this. `user_args` lists your options; every start and every setup run puts them +over the ones the app generates, and for the same option your value wins. `args_written` is a copy of `args` as the app last +wrote it, so an option you added or changed in `args` is noticed and moved into `user_args` the next time the app or setup +touches the file. To undo one, delete it from both `args` and `user_args`. A value you save in the app's Expert settings +("GPU memory for other apps") is put in `user_args` for you. Prefer the app's Expert settings or the Terminal `--set` for +supported overrides. -**Windows blocks an executable.** -Verify the official release and the component named in the message. Feed signatures and Windows code-signing are -different checks. If only the picture reader is blocked, `--vision off` may let text requests run. Do not disable -system-wide protection as the routine installation fix; include the blocked file and exact message in a bug report. +Two things the app still chooses itself: the context size, KV type, picture reading and draft layer. Set them in the Models +screen or with the matching `strata launch` flags, or `"mtp": false` (draft layer). The app keeps the earlier file as +`strata-.json.bak`. Inspect the effective config rather than assuming a saved preference was applied. + +**The app keeps more graphics memory free than I want (decode is slower than in 0.1.45).** +Without a value of yours the app keeps graphics memory free for the desktop: 1536 MiB on a card of 16 GB or less that drives +a display (1024 MiB on a larger card), more with a picture reader on the GPU (2048 MiB), and with the "Leave 20% for my work" +profile a fifth of the card (at most 1536 MiB on a card of 16 GB or less). A card that has no display attached, such as a +second GPU with the screen on the integrated one, keeps 512 MiB (700 MiB with pictures on the GPU). It reads that from the +driver (nvidia-smi `display_active`, or the Windows adapter that has the desktop); when it cannot tell, it assumes a display. +A card that shares the PC's memory (Strix Halo) does not keep a fifth. Your own value is never raised or lowered: set "GPU +memory for other apps" in Expert settings, or `--vram-reserve-mib 0` in `args`. The engine's own warning about low free +memory stays; a card that also draws the desktop can freeze or slow to a few tokens a second with a very small reserve. + +**Pictures are refused, or slow.** +"this server was started without the vision encoder": the model was set up for text only (someone chose "No", or the engine +has no picture reader). Switch pictures on in the app or on the Pictures step of `strata launch` (`--vision on|gpu|cpu`); +in a source checkout run setup again with `--vision yes` (or `--vision gpu` / `--vision cpu`). Pictures are on by default +wherever a model can read them, and `--vision off` (source setup: `--vision no`) turns them off; that is different from +optional [image generation](IMAGES.md). The reader runs on the CPU under 24 GB of graphics memory and on the card from +24 GB, on NVIDIA and AMD cards. Pictures that take several seconds (about 3 s at 300 image tokens on 8 cores, more with more +tokens) are read by the encoder on the CPU; `--vision gpu` (NVIDIA and AMD, ~1.4 GB of VRAM) makes it 0.1-0.5 s. On AMD the +card's reader is `strata-vision-hip`; if it cannot start, the server prints "the GPU picture reader did not start (...); +pictures are read on the CPU" and goes on with the CPU reader. On a Mac the reader runs on the GPU; `--vision cpu` takes +about 50 s per picture there. On Intel Arc the CPU reader is the default. The model, backend and installed engine package +must include a compatible picture reader; inspect the startup error and the model guide. + +**"Windows blocked the Strata engine (or the image encoder) ... Smart App Control".** +On a clean Windows 11, Smart App Control refuses programs that are not signed, and Strata's `strata.exe` and +`strata-vision.exe` are not signed yet (#735). Verify that the file is from the official release and that the message names +a Strata component. The choices are to turn Smart App Control off (Windows Security > App & browser control > Smart App +Control settings; it cannot be turned back on without a reset of Windows) or, if only the image encoder is blocked, to run +without pictures: `strata launch --vision off` (source checkout: `START-HERE.bat --setup --vision no`), which lets text +requests run. Do not disable system-wide protection as a routine fix, and include the blocked file and the exact message in +a bug report. Feed signatures and Windows code signing are different checks. + +**UPDATE.bat / update.sh say "git pull did not succeed", or "has no commit in common" (#1276).** +This is for a source checkout. The repository's history was cleaned up on 2026-10-06, so a clone made before that cannot +be updated with `git pull`. The scripts from 0.1.40.2 handle it: when no tracked file is edited they keep your old commits +in the branch `pre-cleanup-backup` and move the clone to the new history; otherwise they print the two commands for you. +Your models, settings and engine are untracked files and are never touched. An older UPDATE.bat / update.sh (before +0.1.40.2) cannot do this itself: back up local work, run these once in the Strata folder, then use UPDATE.bat as usual +(add `git stash` first if `git status` lists edited files): + + git fetch origin + git branch pre-cleanup-backup + git checkout -B main origin/main + +**Python or the build tools could not be installed.** +Install what it names (links are printed), then run it again. Everything already done is kept. The packaged Terminal +carries Python; a missing system Python is not a reason to install a compiler for the normal release. + +**Linux: the engine does not compile (`unsupported GNU version`, or `exception specification is incompatible` for +`cospi`/`sinpi`/`rsqrt`).** This is for a source build. Two known mismatches between the CUDA toolkit and a new Linux (#601): +- gcc newer than 14 (Ubuntu 26.04's default 15): CUDA 12.x and 13.0 refuse it. Install g++-14 and run + `CXX=g++-14 ./setup.sh` (CC, CXX and CUDAHOSTCXX name the build's compilers; setup passes them to CMake itself, + so an already-configured build folder picks them up too, #1645). +- glibc 2.43 with CUDA 12.9: the toolkit's math headers clash with glibc's, already in CMake's first test compile. + Use CUDA 12.8 or 13.x instead. Setup takes the newest toolkit it finds; `STRATA_NVCC=/usr/local/cuda-12.8/bin/nvcc + ./setup.sh` makes it use that one (only that one). ## While it answers -**It is slow and the disk stays busy.** -The chosen model may exceed available RAM/VRAM and be using the file tier. Close other programs, check memory in -the monitor, and choose a smaller model or context. Compare performance only with the same hardware and workload. +**It is slow and the disk light keeps blinking.** +Your PC is out of free RAM, or the chosen model exceeds the available RAM/VRAM and is using the file tier. Close other +programs, check memory in the monitor, and pick a smaller model or size (Q2_0 or IQ2_XS) or context. Compare performance +only with the same hardware and workload. + +**An answer stopped with "the engine stopped unexpectedly".** +Usually not enough RAM (on Linux the system then stops the engine). Just send your message again: Strata starts the +engine by itself. If it keeps happening, close other programs or pick a smaller size. + +**On Linux the engine stops with "exit code -9", but nothing ran out of RAM.** +Check system logs for an out-of-memory kill first. Then check `ulimit -R`. If it prints 0 (or any number), the desktop +session sets a real-time CPU limit: the audio system (PipeWire) does that when rtkit is not installed, and every program +started from the desktop inherits it. The kernel can then end a program with signal 9 and no message. Install `rtkit`, or +start Strata outside the session's limits, for example `systemd-run --user --collect -p LimitRTTIME=infinity -- strata serve ...`. +Strata prints a warning at start when it sees this limit. **The prompt exceeds the context.** -Start a new chat, shorten the input, or use the app's Summarize and continue action. A larger context needs more -memory. In the Terminal, restart your chosen model with an explicit `--context`, such as `64k`; preserve its family, -model and other choices. Do not look for `SETUP.bat` in an app install. +The conversation is longer than the context you chose. Start a new chat, shorten the input, or use the app's Summarize and +continue action. A larger context needs more memory. In the Terminal, restart your chosen model with an explicit +`--context`, such as `64k`; keep its family, model and other choices. In a source checkout, run `SETUP.bat` and pick more +context. Do not look for `SETUP.bat` in an app install. -**On Linux the engine exits with code -9.** -Check system logs for an out-of-memory kill. Also check `ulimit -R`: a desktop-session real-time limit can cause a -kill even when memory is available. The engine prints a warning for that condition; see the -[detailed troubleshooting table](DETAILS.md#troubleshooting) before changing system limits. +**It is slower than the tables.** +The monitor plugged into the graphics card and other GPU programs take VRAM from the expert cache; RAM running below its +rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. -**A hand-edited engine option disappears.** -The run config tracks explicit options in `user_args` and the generated baseline in `args_written`. Prefer the -app's Expert settings or Terminal `--set` for supported overrides. Context, KV, picture reading and drafting are -launch choices; set them through the app or the corresponding `strata launch` flags. Inspect the effective config -rather than assuming a saved preference was applied. +**An earlier reply that came back empty is gone from the chat history (0.1.40, #843).** +The server leaves out finished assistant turns that have no text, so the next reply does not copy the empty ones. +`STRATA_KEEP_EMPTY_TURNS=1` in the server's environment renders them as before. + +**A Turing card (RTX 20) reads prompts above ~90K tokens differently (0.1.40, #743).** +The prompt's top-k selection takes a wider kernel there, with the same ids. `STRATA_TOPK_STREAM=0` restores the old one. + +**Decode is several times slower with `--expert-cache N` than with `auto` (#781, #831).** +An explicit N is a byte budget that is not checked against the free VRAM once the slots are written. On a card it +fills (the log says `0 MiB of VRAM free with everything loaded - LOW`), Windows pages the GPU's memory and decode drops +from 100 to 14 tok/s with only a few hundred slots too many. Use `--expert-cache auto`, or a smaller N. + +**A low-RAM PC (about 32 GB) stalls with `--resident-budget-gib N` (#649).** +The budget is pinned (locked) in RAM, which leaves the OS and the CPU workers little room. `STRATA_RESIDENT_PIN=0` keeps +it pageable; a smaller budget works too. + +**Decode got slower in 0.1.40 on a 32 GB PC with `--resident-budget-gib N`, and the drive is read hard (#1194, #1116, #1085).** +The start line "the file tier reads unbuffered" means the experts outside the RAM copy are read straight from the drive. +0.1.40 chose that whenever the free RAM could not hold all of them; but the same few come back token after token, and +a cache a twentieth of their size serves most of the repeats. 0.1.40.2 asks for that much (at least 1.5 GiB beside the +4 GiB headroom) and reads through the cache otherwise, which measured 7% to 118% faster decode with a third to a sixth of +the drive traffic on a 20 to 32 GB box. On 0.1.40 / 0.1.40.1: `STRATA_UNBUFFERED_LOAD=0` does the same, `=1` forces the +unbuffered reads. + +**Linux: the start is OOM-killed while the engine allocates the page-locked expert copy (#1250).** +Page-locked pages come from the driver in one go and cannot wait for the kernel to give back file cache, so with the +model files' cache in the way (little really free RAM, much "available") the host could run out. Since 0.1.40.2 the engine +gives back the cached pages of the model files it mapped before it page-locks the copy; when the really free RAM still +does not cover it, it takes the pages in 1 GiB steps while the RAM available (cgroup limits included) stays above the +headroom, page-locks what it has, and keeps the rest resident but pageable with a warning ("only N of M GiB could be +page-locked"): the answers are the same, only the copies of the pageable part to the GPU go through the CPU. +`STRATA_PIN_GUARD=0` turns this off, `STRATA_PIN_RESERVE_GIB=N` sets the RAM that must stay free (default: +`STRATA_RESIDENT_HEADROOM_GIB`, 4 GiB). + +**The Windows display driver resets, then the PC blue-screens (0x141, then 0x116 in `nvlddmkm`) during an answer (#961).** +This is the NVIDIA driver, not Strata: the report shows the same wedge with other CUDA programs on that driver (610.88, +RTX 4080 SUPER). Try another driver (a Studio one, or an older one) and a lower power limit; if it only happens with +`--spec 4`, `--spec 0` avoids the verify window while you wait for a driver fix (a native (IQ) pack needs `--spec` 2 or +more and cannot turn speculation off). + +**An RTX 50 card (a source build with CUDA 13.2) answers with nonsense, or reads prompts wrongly (#892, #968).** +CUDA 13.2.0 and 13.2.1's compiler (nvcc 13.2.51) miscompile some of the engine's kernels for sm_120: on our RTX 5070 the IQ2_S and IQ3_S +products are wrong (relative error 0.5 to 1.0 in the tests) with 13.2 and right with 13.0. The ready-made engine is built +with 13.0. If you compile it yourself, use CUDA 13.0, 13.1 or 13.2.2 (13.2.2, nvcc build 13.2.86, fixes it; an older one can sit next to a newer: `STRATA_NVCC=`); +setup warns when it finds 13.2.0 or 13.2.1 for such a card, and takes an older 13.x when one is installed. + +## AMD cards + +**"No AMD GPU found (the amdgpu driver's KFD topology is empty)" on Linux.** +The kernel's amdgpu driver is not loaded for the card. Integrated Radeon GPUs are listed as not supported; setup +lists every card it found and whether Strata can use it. + +**The engine stops at start with the card's name, its architecture and the build's list.** +The engine was compiled for another card (for example after moving the Strata folder to another PC). Update the engine +(`strata update`), or in a source checkout run `./setup.sh --setup --backend hip`: it compiles the engine for this card's +architecture. + +**On Windows the engine exits with `0xC0000005` in `amdhip64_7.dll` before it prints anything (#654).** +Two things in your environment can cause it, and the server repairs both before it starts the engine (it says so in +the log): `HIP_PATH`, `HIP_DEVICE_LIB_PATH` or `LLVM_PATH` naming a ROCm folder that no longer exists (a deleted build), +and a `TEMP`/`TMP` folder the engine cannot create files in (AMD's runtime compiles its first kernels through temporary +files). If you start `strata.exe` by hand, fix them yourself: `set HIP_PATH=`, and point `TEMP` and `TMP` at a normal +folder such as `C:\Temp`. + +**Windows AMD: the driver resets (VIDEO_ENGINE_TIMEOUT_DETECTED / screen flicker / the engine dies mid-answer).** +Windows gives a GPU about 2 seconds to answer; when a graphics card does not, it resets the driver (a TDR): the screen +flickers, the engine dies, and the Event Viewer shows `VIDEO_ENGINE_TIMEOUT_DETECTED` (#613, with #579 and #541 on +Linux). Strata 0.1.39 and newer say "the GPU stopped responding" in the log. It was seen with KV streaming on +(`--kv-resident 32768`, which setup turns on from 64K context) while reading a long prompt on a gfx1201 card. Try these +in order, one at a time, and tell us what changed: +1. **Send us the evidence.** The last ~80 lines of the engine log (`strata-.log` in the Strata folder of a source checkout; the server window + shows the same lines), your AMD driver version (AMD Software > System), your card and Windows version, the Strata + version, and the exact steps (context size, how long the prompt was, which app sent it). If Windows wrote a + dump, the newest `.dmp` in `C:\Windows\LiveKernelReports\WATCHDOG` (or `C:\Windows\Minidump`) helps; it holds no + chats, only the driver state. +2. **Find the step that hangs:** add `"STRATA_PF_STEP_SYNC": "1"` to the `"env"` block of the model's run config (`strata-.json` + in a source checkout) and restart. The prompt path then waits for the GPU after each step and logs any step over 250 ms, so the log names + the step. It is slower; use it to diagnose, then take it out. +3. **`"STRATA_KV_HOST_DMA": "1"`** in the same `"env"` block: no GPU kernel writes the RAM copy of the K/V during a + prompt, it is copied by DMA instead. Same answers. +4. **No KV streaming:** run setup again and pick 32K context (or remove `--kv-resident` and its number from + `"args"` in the JSON, with a context that fits the VRAM). +5. **A smaller prompt chunk:** change `--prefill` in `"args"` (for example `--prefill 512`): each GPU launch then does + less work between two checks by Windows. Prompts are read more slowly. +6. **Optional, your decision: give Windows more time (`TdrDelay`).** The default is 2 seconds. In the registry, + `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers`, a DWORD `TdrDelay` of `10` (seconds) + lets a long GPU job finish before Windows resets the driver; restart the PC. It hides the symptom and does not fix + a GPU that has really hung, and a hung GPU then freezes the screen for those 10 seconds. Strata changes no Windows + setting itself; to undo it, delete the value. +7. **Driver:** use the newest AMD Software release for your card (Adrenalin, not a Windows Update driver) and restart + after installing. If it started after a driver update, tell us both versions; going back one version is a fair + test. + +**Large pinned host allocations fail on ROCm although RAM is free.** +See [AMD_HIP.md](AMD_HIP.md#model-and-serving-configuration): the mapped expert mode avoids the full pinned arena. + +**"verify: timed out at layer N" or "no progress for 60 s" on AMD (Linux), mostly with `--mmap-experts`.** +Two reports fixed it with `"GPU_PINNED_MIN_XFER_SIZE": "1048576"` (RX 6800) or `"HSA_USERPTR_FOR_PAGED_MEM": "0"` (two +R9700) in the `env` block of the server JSON, then a restart. Experimental, one machine each; on a systemd unit use +`MemoryMax`, not `MemoryHigh`. Details: [AMD_HIP.md](AMD_HIP.md#linux-verify-timeouts-while-the-kernel-reclaims-host-memory). ## Source-checkout problems Python/venv, CUDA compiler versions, ROCm builds, `UPDATE.bat`, `update.sh` and generated `run-` scripts -belong to [SOURCE_INSTALL.md](SOURCE_INSTALL.md). Use the backend guide for build prerequisites. The packaged -Terminal carries Python; a missing system Python is not a reason to install a compiler for the normal release. - -If `git pull` fails in an old clone, back up your local work and follow the recovery steps the source update script prints. -Do not overwrite local branches or edits just to make `git pull` succeed. +belong to [SOURCE_INSTALL.md](SOURCE_INSTALL.md); the entries above marked "source checkout" are the common ones. Use the +backend guide for build prerequisites. If `git pull` fails in an old clone, see the `UPDATE.bat` entry above and do not +overwrite local branches or edits just to make `git pull` succeed. ## Logs and bug reports -- **App:** Settings → Engine → Diagnostics → View logs → Save logs. The diagnostic file goes to Downloads. +**Sending logs for a bug report.** +- **App:** Settings → Engine → Diagnostics → View logs → Save logs. It writes one text file, + `strata-diagnostics-.txt`, into your Downloads folder and shows where. It holds the engine's messages, the failed + steps and the end of each model's server log. - **Terminal:** include `strata --version`, `strata doctor --live`, `strata launch --status`, and the relevant log excerpt. -- **Windows app crash:** inspect `%LOCALAPPDATA%\Strata\logs` for `desktop-crash-.log`. -- **Linux app crash:** start the AppImage with `--save-logs` to collect diagnostics. +- **Windows app crash:** if the app closes right after you start it, it shows a message with the reason and writes + `desktop-crash-.log` in `%LOCALAPPDATA%\Strata\logs`; Save logs includes it, and so can you, by hand. +- **Linux app crash:** if the window crashes or will not open, run the AppImage with `--save-logs` in a terminal; it writes + the crash log and the other logs to one file in Downloads. +- **Installer or source checkout:** `strata-.log` from the Strata folder. -Include model and quantization, OS, GPU/VRAM, RAM, driver, install route, exact command, expected result and actual -error. Remove API keys and private data before sharing. Follow [CONTRIBUTING.md](../CONTRIBUTING.md). +Look through a log before you send it, and never send an API key. Include model and quantization, OS, GPU/VRAM, RAM, +driver, install route (app, Terminal or the installer), Strata and engine versions, exact command, expected result and +actual error. Open an [issue](https://github.com/Niko1221/Strata/issues) and attach the log. Follow +[CONTRIBUTING.md](../CONTRIBUTING.md). The full table of error messages, with the older engine fixes, is in the +[details](DETAILS.md#troubleshooting). diff --git a/docs/VRAM_ELASTIC.md b/docs/VRAM_ELASTIC.md index 64ea795e..94945094 100644 --- a/docs/VRAM_ELASTIC.md +++ b/docs/VRAM_ELASTIC.md @@ -113,7 +113,9 @@ and starts the encoder with the model, as before) the GPU encoder is not started - **A picture's turn** (the same FIFO turn an encode always takes): if the encoder is not running, the engine's `VRAM` command first keeps `"elastic_mib"` (default 2048) free on top of the reserve - the last `POST /v1/vram`, or 0 when none was made - and then the encoder starts. If the cache cannot shrink (the resident low-RAM mode, an engine - without `--vram-elastic`) it starts anyway, as a non-elastic encoder would, and the log says why. + without `--vram-elastic`, a layer split) it starts anyway, as a non-elastic encoder would, and the log says why; on a + layer split the server says at start that the encoder's VRAM has to be kept free with `--vram-reserve-mib`. An + encoder that fails to start (out of VRAM) ends the request with a `503`; the next picture tries again. - **Idle** for `"elastic_idle_s"` (default 120) without a picture: a thread stops the encoder between requests and sends `VRAM` with that reserve again, so the cache grows back to the size it had (0, not the start's reserve: that would leave it a segment or more smaller). diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md new file mode 100644 index 00000000..73965645 --- /dev/null +++ b/docs/release-notes-0.2.7.md @@ -0,0 +1,131 @@ +# Strata 0.2.7 (draft): a faster Qwen3.8 on NVIDIA + +> **DRAFT for the owner.** Written by the CUDA speed work on branch `f-027-cuda`; no engine version is claimed here +> because the owner decides what else 0.2.7 carries. Every number below was measured on the borrowed boxes named in +> each line, same day, against the same build with the new default turned off. + +## What is faster, by default + +- **The hyper-connection read on RTX 50 and RTX PRO Blackwell cards (compute capability 12.0).** The model's + hyper-connection mixing runs 96 small projections per token; its "up" half now runs one warp per row instead of + eight rows per warp, which fills a modern card's SMs instead of 160 blocks on 192 of them. Measured on an RTX PRO + 5000 Blackwell 72 GB (Qwen3.8-Flash-Next IQ3_S, every expert in VRAM), five interleaved pairs of fresh engines: + **story 197.6 -> 201.3 tokens/s (+1.9%), code 243.5 -> 245.1 (+0.7%)**. The answers are unchanged - the new + kernel does the same arithmetic in the same order, the produced tokens were identical in all six pairs and the + engine's own kernel check is bitwise. + - Off switch: `STRATA_GR_UP_WIDE=0`. `STRATA_SM120_PERF=0` still turns off the whole Blackwell set. + - Other cards are untouched: the old kernel runs everywhere else. + +- **Two more kernel switches are on by default where they were measured.** Both sum in another order (about 1e-7), so a + tie between two near-equal words can flip and a reply can differ from 0.2.6 here and there. + - The prompt attention on int8 tensor cores (NVIDIA Ampere and newer): **+1.6% / +1.8% prompt at 8K / 16K on the RTX PRO 5000 + and +1.1% / +1.3% on 2x RTX A4000**, decode unchanged, five pairs each. Off switch: `STRATA_PROMPT_ATTN_IMMA=0`. + - The hyper-connection read split over two kernels (a discrete RTX 50 / RTX PRO Blackwell card with more than 13 GiB): **+1.2% + decode on the RTX PRO 5000 with identical tokens**, about +1.5% together with the switch above. On 2x RTX A4000 and the + RTX 3060 it was slower, so those cards keep the old read. Off switch: `STRATA_GR_V3=0`. + - RTX 40 cards (Ada, compute capability 8.9): new decode row tables for the interleaved matrix kernels, on by default. The output is the + same bit for bit; only how many rows a warp takes changes. **We have not measured them on an RTX 40 card**: the tables come from two + community runs (an RTX 4070 and an RTX 4080), and the report with the 4090 saw no change in decode speed. If you have an RTX 40 + card, please try 0.2.7 and post your decode numbers on issue 3453. Off switch: `STRATA_MMVQ_IL_89=0`. + - NVIDIA A100 / A30 / CMP 170HX class cards (compute capability 8.0): the wide dense dequantizer and decode row tables of PR 3779, on by default, + same output bit for bit, measured only on a CMP 170HX by the contributor. Off switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_MMVQ_IL_SM80=0`. + +## Going back to 0.2.6 + +Two switches bring back every default that 0.2.7 changed, in one step, for a test or for a PC where something looks wrong. The app's +"off" for its speed switches sends them. + +- **`DS4_DEFAULTS=026`** (DeepSeek): the staging ring, the prompt chunk rule, the attention slab (its base and its growth), the pinned + copy and the huge-page arena, the matrix-core attention, the drafter's cumulative cut, the 5-experts default on several Radeon cards, + the RAM store's spare slots and put and its settle after a prompt, the dense dequantizer, the F16 gate/up operand, the drafter's + markov head and the head's column count, and the RDNA3 dense GEMM all go back to what 0.2.6 did. +- **`STRATA_DEFAULTS=026`** (Qwen): the residency-biased routing, the wide and the stream-split hyper-connection reads, the int8 + prompt attention, the RTX 40 (sm_89) and sm_80 decode tables and sm_80 dense dequantizer, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). + Long prompts on the approximate read (`STRATA_KVA`) are off by default and stay as `STRATA_KVA` says. + +A variable or flag you set yourself (`DS4_ATTN_SLAB=N`, `STRATA_ROUTE_PRIOR=2`, `--experts 5`, `--prefill-chunk N`, `--pcie-frac`, +`--ple-io`) still wins over the switch. The older single switches (`DS4_FAST_ATTN=0`, `DS4_ATTN_SLAB=0`, `DS4_COPY_PIN=0`, +`DS4_COPY_HUGETLB=0`, `DS4_STORE_SPARE=0`, `DS4_STORE_PUT=0`, `STRATA_ROUTE_PRIOR=0`, ...) work as before. + +- **Strix Halo (`gfx1151`) on Windows: the shared expert no longer runs on its own stream.** `STRATA_SH_STREAM` was on by default on + `gfx1151`; on a Windows PC it is slower. Qwen3.8-Flash-Next IQ3_S, three interleaved pairs: chat decode **43.6 -> 46.6 tokens/s (+6.9%)** + with it off, prompts unchanged. The answers are the same: five fixed greedy prompts (up to 16,383 tokens) gave identical token ids with + the switch on and off, in four runs. Linux `gfx1151` keeps it on, other cards are untouched. Turn it back on with + `STRATA_SH_STREAM=1`; `STRATA_DEFAULTS=026` restores the 0.2.6 behaviour. Details and the other numbers of that PC: + [docs/STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md). + +## What is faster if your PC is set up for it + +These need no engine change; they are settings. Each was measured on the same boxes. + +- **`--ple-io ram`** - the 28.8 GB n-gram table in RAM instead of read from the SSD row by row. On the 72 GB card + (251 GB RAM): prompt **+16.5% at 1K, +30.6% at 4K, +16.8% at 8K**, -2.6% at 16K. Setup chooses it on a Linux PC + with RAM to spare - check `setup --plan` on yours before trusting that. +- **`--mtp-draft-vocab draft_vocab_en.bin`** - the helper that guesses the next words considers 162 KB of the + vocabulary instead of 425 KB, so it reads less per guess: **+2.7..3.1% story and +2.2..3.0% code** decode on both + big boxes. The big model checks every guess, so the answers are unchanged (identical tokens in every run where + the machine is deterministic). A CJK or Cyrillic user should keep the wider subset. +- **`--slots 2`** - when the engine serves more than one conversation at a time (an agent with several sessions), decoding two + requests together returns **+10% aggregate throughput on the RTX PRO 5000 and +12% on the RTX 3060**, for a slightly higher + latency per token. Three and four slots add nothing measurable (+8.4% and +11.7%): the gain is all in the second slot, and + more slots cost KV memory. A single conversation gains nothing from it. +- **`--prefill-pipe `** - on a two-card layer split, plan the prompt's chunks for the pipeline: **+15.4% at 4K, + +22.5% at 8K, +2.7% at 16K** prompt on 2x RTX A4000 (5 interleaved pairs). `R` is the PC's own ratio; `setup --calibrate` measures it + (1,500 on that box). +- **`--kv q4_0` on a 12 GB card** - the KV cache at 4 bits leaves room for ~1,000 more experts. On the RTX 3060 + 12 GB (IQ3_XXS) the gain did **not** reproduce: +12.0% story over three pairs, -2.9% over five, with that box's + own baseline moving 41.6 -> 49.0 tok/s between sessions, so no speed claim is made for it. It costs KV precision + on long documents (document perplexity +8% at 1K, +12% at 8K in `bench/results/2026-09-27-kv-q4`), so it is a + choice, not a default. + +## The 12 GB default: residency-biased routing + +**On by default at 1.5 on a discrete NVIDIA card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off, an explicit value wins; +not a default on a Radeon, a Strix Halo or any integrated GPU, where it was not measured). The router prefers +experts that are already resident, so a window stops waiting on a page-in that the next window would need again. The first +0.2.7 candidates used a bonus of 2.0, and the table below was measured at 2.0 on the RTX 3060 12 GB (IQ3_XXS), five interleaved +pairs of fresh engines. The default was lowered to 1.5 by the owner on 26 October after the copy and code check on that card +(IQ3_XXS) found real defects in the answers at 2.0 and **no defect in 19 tasks at 1.5** (or at 1.0). 1.5 keeps most of the speed: +story **+15%** and code **+37%** against the routing off. That is 19 tasks, not a proof; a longer 61-task check of 0, 1.5 and 2.0 +is still running, and if it shows defects at 1.5 the default falls back to 1.0. The 2.0 measurements: + +| axis | before | after | +|---|---|---| +| decode story | 45.9 | **61.6 (+34.1%)** | +| decode code | 43.6 | **73.1 (+67.6%)** | +| prompt | **not claimed** - this box's prompt read swings between 218 and 466 tok/s across runs, and a repeat of the same five-pair A/B read +254% and -20.5% where the first read +35% and +17% | +| decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | + +It holds where it matters most: with **two conversations in flight** the whole recipe reads **31.2 -> 62.0 tok/s aggregate +(+99%)** on that card and +22% on the 2x A4000, both answers arriving in half the wall time on the 12 GB box, and the routing +default alone is **+67% aggregate** there (59.7 against 35.6 tok/s) - +and on content the tuning was never fitted to it **+29.0%** (43.5 -> 55.0 tok/s on a +document prompt), and the whole recipe - routing, a workload-fitted expert profile, `--adapt-every 0`, `--vram-reserve-mib +896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. + +It works by choosing a slightly different set of experts, so replies change: the owner approved that trade for 12 GB cards. +**Do not raise the bonus to 2.0 or more.** 2.0 showed defects in the copy and code check; 3.0 measures +17.7% / +24.0% on the test +prompts but **-4.5% on held-out content**, and 4.0 breaks outright. `STRATA_ROUTE_PRIOR=2` still works if you want the old value. + +## What was tried and did not make it + +Recorded so nobody repeats it: deeper or wider MTP windows, `STRATA_QFUSE`, `STRATA_STAGE_TRIM`, `STRATA_HC_Q8`, +DFlash2 as the drafter, 4-bit draft copies, `pcie_frac` changes on the 3060, `--pipeline-windows` on a two-card +split, the K-split and the shared-memory-free variants of the hyper-connection down projection, `--prefill` chunks +above 8K, and every Blackwell default switch turned off one at a time. The numbers are in +`CUDA Plan/RESULTS.md` outside this repository. + +## Updating + +- The engine package that carries this is chosen by the owner; the app and the Terminal keep their own versions. +- From 0.2.6: the usual update path for the part that changed. + +--- + +Strata is free and open source. If it runs well on your PC, a coffee keeps the work on it going: + +Buy Me A Coffee + + + + diff --git a/highlight.py b/highlight.py new file mode 100644 index 00000000..7f276adb --- /dev/null +++ b/highlight.py @@ -0,0 +1,138 @@ +"""Syntax highlighting for chat.py's streamed output: fenced code blocks get colored (tags, strings, comments, +keywords, numbers), everything else passes through unchanged. Standard library only, no dependency. + + from highlight import StreamHighlighter + hl = StreamHighlighter(color=True) + out = hl.feed(streamed_chunk) # complete lines, highlighted; a partial last line is held back + out += hl.flush() # the held-back tail (unclosed fence included) +""" +from __future__ import annotations + +import re + + +# ANSI colors; a disabled colorer returns the text unchanged +class _Palette: + def __init__(self, color: bool): + self.on = color + + def paint(self, text: str, code: str) -> str: + return f"\033[{code}m{text}\033[0m" if self.on else text + + +# one regex per language family; the first matching family paints the line +_PY_KEYWORDS = ("False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", + "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield") +_JS_KEYWORDS = ("async", "await", "break", "case", "catch", "class", "const", "continue", "default", "delete", + "do", "else", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", + "instanceof", "let", "new", "null", "return", "static", "super", "switch", "this", "throw", "true", + "try", "typeof", "undefined", "var", "void", "while", "yield") +_C_KEYWORDS = ("alignas", "auto", "bool", "break", "case", "catch", "char", "class", "const", "constexpr", + "continue", "default", "delete", "do", "double", "else", "enum", "explicit", "extern", "false", + "float", "for", "friend", "if", "inline", "int", "long", "namespace", "new", "noexcept", "nullptr", + "private", "protected", "public", "return", "short", "signed", "sizeof", "static", "struct", + "switch", "template", "this", "throw", "true", "try", "typedef", "typename", "union", "unsigned", + "using", "virtual", "void", "while") +_SHELL_KEYWORDS = ("case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "in", "then", + "until", "while") +_JSON_KEYS = ("false", "null", "true") + +_STR = r"(\"(?:[^\"\\]|\\.)*\")" # "..." with escapes +_SQ_STR = r"('(?:[^'\\]|\\.)*')" +_COMMENT = r"(#.*$)" +_SLASH_COMMENT = r"(//.*$)" +_NUM = r"\b(\d[\w.]*)\b" + +_FAMILIES = { + "markup": ({"html", "htm", "xml", "svg", "vue", "jsx", "tsx"}, + re.compile(r"()|(<[A-Za-z][\w:.-]*/?>?)|()|([A-Za-z-]+)(?==)"), + {1: "36;1", 2: "96", 3: "96", 4: "94"}), + "python": ({"py", "python"}, + re.compile(rf"{_COMMENT}|{_SQ_STR}|{_STR}|\b({'|'.join(_PY_KEYWORDS)})\b|{_NUM}"), + {1: "90", 2: "33", 3: "33", 4: "35;1", 5: "34"}), + "c-like": ({"c", "cc", "cpp", "c++", "h", "hpp", "cu", "hip", "java", "kt", "rs", "go", "cs"}, + re.compile(rf"{_SLASH_COMMENT}|{_STR}|\b({'|'.join(_C_KEYWORDS)})\b|\b(0x[0-9a-fA-F]+|\d[\w.]*)\b"), + {1: "90", 2: "33", 3: "35;1", 4: "34"}), + "js-like": ({"js", "javascript", "ts", "typescript", "mjs"}, + re.compile(rf"{_SLASH_COMMENT}|{_STR}|{_SQ_STR}|(`[^`]*`)|\b({'|'.join(_JS_KEYWORDS)})\b|{_NUM}"), + {1: "90", 2: "33", 3: "33", 4: "33", 5: "35;1", 6: "34"}), + "shell": ({"sh", "bash", "zsh", "shell", "console", "bat", "cmd", "powershell", "ps1"}, + re.compile(rf"{_COMMENT}|{_SQ_STR}|{_STR}|\b({'|'.join(_SHELL_KEYWORDS)})\b|(^\s*\$)"), + {1: "90", 2: "33", 3: "33", 4: "35;1", 5: "90"}), + "json": ({"json", "jsonc", "json5"}, + re.compile(rf"{_SLASH_COMMENT}|{_STR}(?=\s*:)|\b({'|'.join(_JSON_KEYS)})\b|\b(-?\d[\w.]*)\b"), + {1: "90", 2: "94", 3: "35;1", 4: "34"}), + "css": ({"css", "scss", "less"}, + re.compile(r"(/\*.*?\*/)|([.#][\w-]+)|([\w-]+)(?=\s*:)|\b(\d[\w.%]*)\b"), + {1: "90", 2: "96", 3: "94", 4: "34"}), + "sql": ({"sql"}, + re.compile(r"(--.*$)|('[^']*')|\b(select|from|where|insert|into|update|set|delete|join|left|right|inner|" + r"outer|on|group|by|order|having|limit|create|table|alter|drop|and|or|not|null|as)\b", + re.IGNORECASE), + {1: "90", 2: "33", 3: "35;1"}), + "diff": ({"diff", "patch"}, + re.compile(r"^(\+[^+]*)|^(-.*)|^(@@.*@@)"), + {1: "32", 2: "31", 3: "36"}), +} + +_FENCE_RE = re.compile(r"^\s*(```|~~~)\s*([\w+#-]*)") +_LANG_ALIAS = {"c++": "c-like", "javascript": "js-like", "typescript": "js-like", "python": "python", + "py": "python", "shell": "shell", "bash": "shell", "console": "shell"} + + +def _family(lang: str): + lang = _LANG_ALIAS.get(lang.lower(), lang.lower()) + for exts, rx, colors in _FAMILIES.values(): + if lang in exts: + return rx, colors + return None, None + + +class StreamHighlighter: + """Line-buffered highlighter for streamed text. feed() returns complete lines (highlighted inside fenced code + blocks); flush() returns the held-back tail. Outside code fences the text is returned unchanged (color on or + off), so prose never gets painted. All characters other than the added ANSI escapes pass through unchanged.""" + + def __init__(self, color: bool = True): + self.color = color + self._pal = _Palette(color) + self._buf = "" # held-back partial line + self._in_fence = False + self._rx = None + self._colors = None + + def feed(self, chunk: str) -> str: + self._buf += chunk + out = [] + while "\n" in self._buf: + line, self._buf = self._buf.split("\n", 1) + out.append(self._line(line)) + out.append("\n") + return "".join(out) + + def flush(self) -> str: + tail, self._buf = self._buf, "" + return self._line(tail) if tail else "" + + def _line(self, line: str) -> str: + fence = _FENCE_RE.match(line) + if fence: + marker, lang = fence.group(1), fence.group(2) + if self._in_fence: + self._in_fence, self._rx, self._colors = False, None, None + return self._pal.paint(line, "90") + self._in_fence = True + self._rx, self._colors = _family(lang) + if not self._rx: + return self._pal.paint(line, "90") + return self._pal.paint(marker, "90") + self._pal.paint(lang, "94") + line[fence.end():] + if not self._in_fence or not self._rx: + return line + return self._rx.sub(self._sub, line) + + def _sub(self, m: re.Match) -> str: + for gi, code in self._colors.items(): + if m.group(gi) is not None: + return self._pal.paint(m.group(gi), code) + return m.group(0) diff --git a/include/strata/core/arch_defaults.hpp b/include/strata/core/arch_defaults.hpp index 969e4cee..2025af48 100644 --- a/include/strata/core/arch_defaults.hpp +++ b/include/strata/core/arch_defaults.hpp @@ -18,7 +18,13 @@ namespace strata::core { /// The environment settings that are the defaults of `gcn_arch` (hipDeviceProp_t::gcnArchName; "gfx1151" or -/// "gfx1151:sramecc-:xnack-"): empty for every other architecture. +/// "gfx1151:sramecc-:xnack-"): empty for every other architecture. `defaults026` (STRATA_DEFAULTS=026, defaults_026.hpp): the gfx12 table of +/// v0.2.6 (the five prompt switches only, without the four 0.2.7 decode switches); the one-argument form asks the environment. +std::vector> arch_default_env(const char* gcn_arch, bool defaults026); +/// The same with the platform given instead of read from the build (a pure rule, so a test can check both). 0.2.7: on Windows the gfx1151 +/// table leaves STRATA_SH_STREAM out (the fork is off, +6.9% decode on a Strix Halo Windows PC, same ids); Linux gfx1151 and every +/// other architecture are unchanged; `defaults026` keeps it in on both. An explicit STRATA_SH_STREAM=1 turns the fork on anywhere. +std::vector> arch_default_env(const char* gcn_arch, bool defaults026, bool windows); std::vector> arch_default_env(const char* gcn_arch); /// The integrated Radeons (Phoenix / Hawk Point 780M gfx1103, Strix Point 890M / 880M gfx1150, Strix Halo gfx1151) whose diff --git a/include/strata/core/conversation_buffer.hpp b/include/strata/core/conversation_buffer.hpp index d8a45177..2ba8aaa6 100644 --- a/include/strata/core/conversation_buffer.hpp +++ b/include/strata/core/conversation_buffer.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -61,7 +62,8 @@ public: (count > SIZE_MAX / sizeof(Segment) || !add(total, count * sizeof(Segment)))) return SIZE_MAX; return total; } - void resize(size_t n, uint8_t value = 0) { + void resize(size_t n, uint8_t value = 0) { resize_impl(n, &value); } + void resize_impl(size_t n, const uint8_t* value) { if (n > size_) { const size_t held = size_; const bool growing = held != 0; @@ -70,7 +72,8 @@ public: const size_t extra = n - size_ - extend; segments_.reserve(segments_.size() + extra / segment_bytes + (extra % segment_bytes != 0)); if (extend) { - segments_.back().resize(segments_.back().size() + extend, value); + if (value) segments_.back().resize(segments_.back().size() + extend, *value); + else segments_.back().resize(segments_.back().size() + extend); size_ += extend; } while (size_ < n) { @@ -78,7 +81,8 @@ public: const size_t previous = segments_.empty() ? 0 : segments_.back().capacity(); Segment segment; segment.reserve(segment_capacity(count, previous, growing, held)); - segment.resize(count, value); + if (value) segment.resize(count, *value); + else segment.resize(count); segments_.push_back(std::move(segment)); size_ += count; progress_beat(); // #2049: zero-filling 16 MiB of fresh pages is slow when the host is paging @@ -93,6 +97,9 @@ public: } } void pop_back() { resize(size_ - 1); } + // resize() without the zero fill of what it adds (the fresh pages are not touched here): only for a caller that + // writes every added byte before anything reads it (STRATA_PARK_ASYNC's background copy) + void resize_for_overwrite(size_t n) { resize_impl(n, nullptr); } // fn(pointer, count, absolute_offset); false aborts a transfer immediately. template bool visit(size_t offset, size_t count, Fn fn) { @@ -123,7 +130,15 @@ public: } private: - using Segment = std::vector; + // value-initializes only when asked (resize's explicit fill value): resize_for_overwrite leaves the bytes alone + template struct DefaultInit : std::allocator { + template struct rebind { using other = DefaultInit; }; + DefaultInit() = default; + template DefaultInit(const DefaultInit&) noexcept {} + template void construct(U* p) { ::new ((void*) p) U; } + template void construct(U* p, A&&... a) { ::new ((void*) p) U(std::forward(a)...); } + }; + using Segment = std::vector>; // A fresh capture allocates exactly its payload. Later appends reserve // geometrically growing segments, bounded by 16 MiB. Small chat turns then // extend the final allocation instead of adding one transfer per turn. diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 973b2593..34898345 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -25,6 +26,9 @@ struct ConversationCheckpoint { std::vector imgs; std::vector gdn, ple, tails, dead, block_pos; uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention + // STRATA_CKPT_VRAM_SLOTS: the tag of the device copy of `gdn` (0: none). Set by conversation_checkpoint_save, the + // only writer of a checkpoint's GDN bytes besides a whole copy (which keeps them equal, so it keeps the tag). + uint64_t dev_tag = 0; // A shared-prefix pin (the request key pin=N): this checkpoint is the read-only prefix many suffix queries branch // from, so retention never evicts it (conv_cache.hpp) and a parked conversation holding it stays parked. A run-time // mark only: it is not in the session file, a request that pins the same prefix again sets it. @@ -58,6 +62,14 @@ struct ConversationKv { int format = 0; int64_t cells = 0, heads = 0, head_dim = 0, page_size = 0, pooled_rows = 0, idx_dim = 0; ConversationBuffer k, v, k_scale, v_scale, pooled; + // STRATA_PARK_VRAM_MIB: the tag this layer's parts were recorded under in the park's VRAM slot (0: none). Set by + // conversation_kv_save; a restore that finds the slot copies from it instead of from the buffers above. + uint64_t dev_tag = 0; + // STRATA_PARK_VRAM_MIB: set while a background copy fills the buffers above from the slot; its deleter waits for + // that copy and releases the slot. This layer's own token (not shared): the layers outlive their image when they + // are retained for the next park (ConversationCache::retain), and go in any order. Last member: it goes before + // any buffer. + std::shared_ptr pending; size_t bytes() const { return k.bytes() + v.bytes() + k_scale.bytes() + v_scale.bytes() + pooled.bytes(); } @@ -170,6 +182,11 @@ struct SavedConversation { bool cvec = true; // with a layer split, the later stages' own images, one per stage, in stage order std::vector stage_images; + // STRATA_PARK_ASYNC: set while a background copy fills this image's K/V; its deleter waits for that copy, and as + // one of the last members it runs before any buffer is freed (whichever copy of the image goes last) + std::shared_ptr pending; + // STRATA_CKPT_ASYNC: the same for the background copy that fills `live.gdn` (the park's running state) + std::shared_ptr live_pending; /// Holds a pinned shared prefix (see ConversationCheckpoint::pinned): the parked-conversation budget keeps it. bool pinned() const { @@ -187,6 +204,24 @@ struct SavedConversation { } }; +/// `c` holds the state `ids` (with `images`) describes, or a continuation of it: its tokens start with `ids` and +/// its pictures below ids.size() are exactly `images`. What an idle batch slot holds is then parked already (or +/// a longer continuation is), so the slot need not park it again before an admission overwrites it. +template +bool conversation_covers(const ConversationCheckpoint& c, const std::vector& ids, + const std::vector& images) { + const size_t n = ids.size(); + if (n == 0 || c.ids.size() < n) return false; + for (size_t i = 0; i < n; ++i) + if ((int64_t) c.ids[i] != (int64_t) ids[i]) return false; + size_t j = 0; + for (const auto& image : c.imgs) { + if (image.start >= (int64_t) n) continue; + if (j == images.size() || !(images[j++] == image)) return false; + } + return j == images.size(); +} + template int64_t conversation_prefix(const ConversationCheckpoint& c, const std::vector& prompt, const std::vector& images) { @@ -285,6 +320,19 @@ public: return best; } + /// A parked conversation holds this state already (its live tokens or one of its checkpoints start with `ids`, + /// same pictures, same steering): see conversation_covers. Read-only; no LRU effect. + template + bool holds(const std::vector& ids, const std::vector& images, bool cvec) const { + for (const auto& e : entries_) { + if (e.cvec != cvec) continue; + if (conversation_covers(e.live, ids, images)) return true; + for (const auto& c : e.checkpoints) + if (conversation_covers(c, ids, images)) return true; + } + return false; + } + SavedConversation take(size_t index) { SavedConversation out = std::move(entries_.at(index)); bytes_ -= out.bytes(); diff --git a/include/strata/core/conversation_snapshot.hpp b/include/strata/core/conversation_snapshot.hpp index dcee29fa..28071715 100644 --- a/include/strata/core/conversation_snapshot.hpp +++ b/include/strata/core/conversation_snapshot.hpp @@ -70,6 +70,41 @@ bool conversation_checkpoint_validate(const ConversationCheckpoint& checkpoint, const ModelGeometry& g, std::string& error); bool conversation_checkpoint_save(ConversationCheckpoint& checkpoint, const SessionState& session, const ModelGeometry& g, std::string& error); +/// STRATA_CKPT_ASYNC=1 (CUDA, opt-in): conversation_checkpoint_save copies the GDN state into a device staging buffer +/// and moves it into the checkpoint's host vector on a background thread (the PCIe copy overlaps what follows: the +/// rest of the prompt, the reply). This waits for that copy; every reader of a checkpoint's bytes calls it first +/// (restore, snapshot save / restore, the parked copies, the session file, the serve loop at each request). No-op +/// when nothing is in flight. +/// `only` (non-null): wait only when the copy in flight is into that checkpoint's GDN bytes. +void conversation_checkpoint_join(const void* only = nullptr); +/// STRATA_PARK_ASYNC: waits until the last parked image's K/V has landed in its host buffers (no-op otherwise); the +/// readers of a parked image's K/V call it first, and the image itself before it frees them (SavedConversation::pending). +void conversation_park_join(); +/// STRATA_PARK_ASYNC=1 (CUDA, opt-in): between begin and launch, conversation_kv_save copies the device K/V device to +/// device into a VRAM stage (only while 1.5 GB of VRAM stays free beside it; else as before) and records where it +/// goes; launch moves the stage into the host buffers on a background thread (4 MiB pieces through two pinned +/// buffers), so the next prompt starts at once. conversation_park_join (above) waits for it. +/// begin: false when it is off (the saves then copy as before); `need` is the K/V bytes the saves will copy. +bool conversation_park_async_begin(size_t need); +/// The recorded copies start (the device copies into the stage have landed when it returns); false: a copy failed. +bool conversation_park_async_launch(std::string& error); +/// Abandons a begun park that was not launched (the error paths): nothing was queued to the background. +void conversation_park_async_abandon(); +/// STRATA_PARK_VRAM_MIB=N (with STRATA_PARK_ASYNC): a park also keeps the whole K/V of its image in VRAM, in a slot +/// of its own taken at begin while the slots' total stays within N MiB (and 1.5 GB of VRAM stays free), so a restore +/// of that image copies device to device from the slot (conversation_kv_restore / _prefix) instead of host to +/// device, and does not wait for the background copy. The slot lives as long as the image and its K/V layers +/// (SavedConversation::pending, ConversationKv::pending). Default 0: off. +/// The tag of the begun park's slot (0: none); kept until the next begin, for the tokens. +uint64_t conversation_park_slot_tag(); +/// Frees the slot under `tag` (no-op for 0 or a slot already gone); the caller joined the copy that reads it. +void conversation_park_slot_release(uint64_t tag); +/// VRAM pressure: joins the background copy, then frees every slot and the stage. Returns the bytes freed (0, and +/// nothing is touched, while STRATA_PARK_VRAM_MIB is unset). +size_t conversation_park_vram_release_all(); +/// conversation_park_join, unless every K/V layer of `image` has its slot (the restore then reads no host buffer +/// the background copy could still be filling; a layer that falls back to the host joins for itself). +void conversation_park_join_for(const SavedConversation& image); bool conversation_checkpoint_restore(const ConversationCheckpoint& checkpoint, SessionState& session, const ModelGeometry& g, std::string& error); // conversation_checkpoint_save(from) + conversation_checkpoint_restore(to) of `ids` without a host image, for two @@ -128,9 +163,15 @@ bool conversation_snapshot_bytes(const ConversationView& view, const SessionStat bool conversation_snapshot_capture_bytes(const ConversationKvReuse& reuse, const ConversationView& view, const SessionState& session, const ModelGeometry& g, const QsaState* draft, size_t& bytes, std::string& error); +// `storage` (optional, STRATA_CKPT_POOL): dropped checkpoints whose vectors the image's running state and checkpoint +// copies go into (their pages are in: no fresh pages to fault); the ones not used are left in it. +// `moved` (optional): checkpoints the caller drops after this, moved into the image after the copies of the view's +// (the image holds the same checkpoints as with all of them in the view; nothing is copied for these) bool conversation_snapshot_save(SavedConversation& image, const ConversationView& view, const SessionState& session, const ModelGeometry& g, const QsaState* draft, std::string& error, - ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr); + ConversationKvReuse reuse = {}, size_t* reused_bytes = nullptr, + std::vector* storage = nullptr, + std::vector* moved = nullptr); bool conversation_snapshot_validate(const SavedConversation& image, const SessionState& session, const ModelGeometry& g, const QsaState* draft, std::string& error); ConversationRestore conversation_snapshot_restore(const SavedConversation& image, SessionState& session, diff --git a/include/strata/core/defaults_026.hpp b/include/strata/core/defaults_026.hpp new file mode 100644 index 00000000..84221a54 --- /dev/null +++ b/include/strata/core/defaults_026.hpp @@ -0,0 +1,39 @@ +// include/strata/core/defaults_026.hpp - STRATA_DEFAULTS=026: the master switch of the Qwen engine's 0.2.7 defaults. +// +// Every default the Qwen engine (`strata`) changed since v0.2.6 goes back to what v0.2.6 did when STRATA_DEFAULTS=026 is in the +// environment (the app's "off" for its speed switches sends it): the residency-biased routing (STRATA_ROUTE_PRIOR), the wide +// hyper-connection up read (STRATA_GR_UP_WIDE), the stream-split hyper-connection read (STRATA_GR_V3), the int8 prompt attention +// (STRATA_PROMPT_ATTN_IMMA), the four gfx12 decode switches of the arch table, the PLE residency policy (STRATA_PLE_AUTO_RAM), and the +// gfx12 decode miss split of 0.15 (back to 0.55). KVA is off by default in 0.2.7 and stays whatever STRATA_KVA says. +// An explicit per-feature variable (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, STRATA_PLE_AUTO_RAM=1, ...) or flag (--pcie-frac, --ple-io) +// still wins over the master switch. Each rule is a pure function that takes the answer of qwen_defaults_026() as its `v026` +// argument, so a test can check both settings without touching the environment (src/core/arch_defaults_test.cpp, +// src/core/ple_residency_test.cpp). +#pragma once + +#include +#include + +namespace strata { + +/// "026", "0.2.6" and "v0.2.6" name version 0.2.6; anything else (unset, "", "0", "027") does not. +inline bool is_026_token(const char* v) { + return v != nullptr && (std::strcmp(v, "026") == 0 || std::strcmp(v, "0.2.6") == 0 || std::strcmp(v, "v0.2.6") == 0); +} + +/// STRATA_DEFAULTS=026 (read once). +inline bool qwen_defaults_026() { + static const bool on = is_026_token(std::getenv("STRATA_DEFAULTS")); + return on; +} + +/// The decode miss split's start value (the share of a native pack's missing experts the CPU pool takes) when --pcie-frac is not given: +/// NVFP4 packs 0.25, other native packs 0.55 (the x16 share), and 0.15 on gfx12 (0.2.7) unless STRATA_PCIE_FRAC_DEFAULT=old or the master +/// switch is 026; a canonical pack 0.2. +inline double pcie_start_frac(bool nvfp4_pack, bool native_pack, bool gfx12_default, bool pf_old, bool v026 = false) { + if (nvfp4_pack) return 0.25; + if (!native_pack) return 0.2; + return gfx12_default && !pf_old && !v026 ? 0.15 : 0.55; +} + +} // namespace strata diff --git a/include/strata/core/expert_cache.hpp b/include/strata/core/expert_cache.hpp index 9685aa4d..238c8594 100644 --- a/include/strata/core/expert_cache.hpp +++ b/include/strata/core/expert_cache.hpp @@ -75,7 +75,9 @@ bool write_expert_profile(const std::string& path, int64_t n_layers, int64_t n_e /// Free device memory for the expert cache. On a unified memory system - one memory for the CPU and the GPU, such as /// the DGX Spark (GB10); CUDA reports it as cudaDevAttrIntegrated - cudaMemGetInfo counts only MemFree, not the page cache - which, with the experts read from the GGUF in place, is mostly those /// files' clean pages and gives way to a device allocation. There the figure is MemAvailable less 6 GiB for the OS -/// and the engine's host side (STRATA_UMA_HEADROOM_GIB). Elsewhere it is cudaMemGetInfo's. +/// and the engine's host side (STRATA_UMA_HEADROOM_GIB). Elsewhere it is cudaMemGetInfo's. On Windows with an NVIDIA +/// card STRATA_VRAM_FREE=device (opt-in) takes the smaller of that and NVML's figure for the whole card: under WDDM +/// cudaMemGetInfo does not count what other processes hold. It can only make the figure smaller. size_t device_free_bytes(); /// One piece of an expert blob that lives contiguously in a source's own memory: `n` bytes at `p`, to land `at` bytes into the blob. @@ -217,6 +219,14 @@ public: /// Slots filled so far, for the startup report. int64_t fills() const { return fills_; } + /// STRATA_EXPERT_NIBBLE=1 (strata/core/expert_nibble.hpp): called once the startup fill has written every slot + /// (some of them as 4-bit codes, not GGUF blocks) and checked them. From then on no slot may be written through + /// this class: the fill_slot calls stop the engine (they would write GGUF bytes, possibly into a 4-bit slot, and a + /// wrong expert gives a plausible token, never an error), and `admit` claims nothing. Never called with the switch + /// off: an unsealed cache is the one above. + void seal() { sealed_ = true; } + bool sealed() const { return sealed_; } + /// The elastic K/V (--kv-grow): the arena in a VMM range (vmm.hpp) instead of one cudaMalloc, so the K/V can take /// single chunks of it and give them back. Applies to the next `open`; ignored where VMM is not available. static void set_vmm(bool enabled); @@ -266,6 +276,7 @@ private: std::vector layer_next_; ///< [n_layers] -> that layer's next free slot std::vector off_; ///< plan v0.3 P6: slot offsets (slots + 1 entries) when sized int64_t admitted_ = 0; + bool sealed_ = false; ///< STRATA_EXPERT_NIBBLE: `seal` was called (no slot is written after it) }; } // namespace strata::core diff --git a/include/strata/core/expert_nibble.hpp b/include/strata/core/expert_nibble.hpp new file mode 100644 index 00000000..92001956 --- /dev/null +++ b/include/strata/core/expert_nibble.hpp @@ -0,0 +1,457 @@ +// include/strata/core/expert_nibble.hpp - STRATA_EXPERT_NIBBLE=1 (opt-in, default off): the gate/up experts of +// IQ2_S / IQ3_XXS / IQ3_S layers kept as 4-bit codes in their VRAM slots, for Pascal GP100 (sm_60). +// +// **WHY.** On a GP100 the decode window's gate/up expert kernels are not held by memory bandwidth: they use a small +// part of it and wait on each block's serial chain (the weights, the codebook lookups, the emulated dp4a, the +// reduction). Re-encoding each 32-weight item of these three formats as sixteen bytes of 4-bit codes (one aligned +// 16-byte load) and keeping the integer scale and the fp16 d as they are makes the slot 1.25-1.68x the GGUF bytes and +// the decode of four weights 1-4 integer instructions instead of two codebook lookups. +// +// **WHY IT IS LOSSLESS.** Their grids have only 3 (IQ2_S) or 8 (IQ3_XXS, IQ3_S) magnitudes, so each int8 weight the +// production `Split::load` decodes is one of at most 16 signed values. At every start the transcoder decodes every +// item of every converted slot with the production load, encodes it, decodes the written code again and compares; and +// the GGUF blocks are rebuilt from every slot and compared with the blob byte for byte (`check_gguf`). The decode +// kernels run the production integer chain and float tail in the production order: every gate / up value is the +// production kernel's, bit for bit. The prompt path's MMQ reads the GGUF blocks rebuilt from the slot (`gather_gguf`, +// in place of the copy it does today): the same bytes, so the same bits. +// +// **OFF IS TODAY.** Unset or 0: no layer is converted, `slot_bytes(l)` is `expert_layout().blob_bytes(l)`, nothing is +// transcoded, sealed or hashed, and none of the new branches is entered. Only a CUDA build with +// STRATA_EXPERIMENTAL_SM60 has the kernels (STRATA_EXPERT_NIBBLE_BUILT); every other build refuses the switch at start. +#pragma once + +#include "strata/kernels/cpu/expert_layout.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \ + !defined(STRATA_GPU_METAL) +#define STRATA_EXPERT_NIBBLE_BUILT 1 +#else +#define STRATA_EXPERT_NIBBLE_BUILT 0 +#endif + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_NIB_HD __host__ __device__ +#else +#define STRATA_NIB_HD +#endif + +namespace strata::core::nibble { + +// ------------------------------------------------------------------------------------------------ the slot layout +// +// A converted layer's expert slot, in order (the host arena and the pack keep the GGUF blocks): +// +// codes kRows x kItems x 16 B row r, item k at (r * kItems + k) * 16; rows 0..kNFf-1 gate, kNFf..kRows-1 up +// scales kRows x kItems x 1 B row r, item k at kScOff + r * kItems + k (the production scale step's input) +// d kRows x kSuper x 2 B row r, superblock s at kDOff + (r * kSuper + s) * 2: the block's fp16 d, bit for bit +// ------ kGuBytes = 1,766,400 B (6900 x 256: the down part starts 256-aligned) +// down the GGUF down rows, copied verbatim from the raw blob's [down_off, bytes) +// ------ slot_bytes = round_up(kGuBytes + down bytes, kSlotAlign) +// +// One item = 32 weights of a row, one 16-byte code (four 32-bit words, see `encode_item`). Only the expert shape +// n_embd 2560, n_ff 640 is converted: every other layer keeps its GGUF blob and its kernels. + +inline constexpr int64_t kNEmbd = 2560; ///< the gate/up rows' width (the activation) +inline constexpr int64_t kNFf = 640; ///< gate rows = up rows = n_ff +inline constexpr int64_t kRows = 2 * kNFf; ///< 1280: gate, then up +inline constexpr int64_t kItems = kNEmbd / 32; ///< 80 items of 32 weights per row +inline constexpr int64_t kSuper = kNEmbd / 256; ///< 10 superblocks (one fp16 d each) per row +inline constexpr uint64_t kItemBytes = 16; ///< one item's code: four words, one 16-byte load + +inline constexpr uint64_t kCodesOff = 0; +inline constexpr uint64_t kUpCodesOff = (uint64_t) kNFf * kItems * kItemBytes; ///< 819,200: row kNFf +inline constexpr uint64_t kScOff = (uint64_t) kRows * kItems * kItemBytes; ///< 1,638,400 +inline constexpr uint64_t kDOff = kScOff + (uint64_t) kRows * kItems; ///< 1,740,800 +inline constexpr uint64_t kGuBytes = kDOff + (uint64_t) kRows * kSuper * 2; ///< 1,766,400 +inline constexpr uint64_t kDownOff = kGuBytes; ///< the down rows +inline constexpr uint64_t kSlotAlign = 256; ///< every slot's size + +static_assert(kGuBytes == 1766400, "the slot layout above"); +static_assert(kGuBytes % kSlotAlign == 0, "the down part starts 256-aligned"); +static_assert(kScOff % 16 == 0 && kDOff % 16 == 0, "each region starts 16-aligned"); + +/// Byte offset of row `row` (0..kRows-1; up rows are kNFf + r) item `k`'s code inside the slot. +STRATA_NIB_HD constexpr uint64_t code_off(int64_t row, int64_t k) { + return kCodesOff + ((uint64_t) row * kItems + (uint64_t) k) * kItemBytes; +} +/// Byte offset of row `row` item `k`'s scale byte. +STRATA_NIB_HD constexpr uint64_t scale_off(int64_t row, int64_t k) { return kScOff + (uint64_t) row * kItems + (uint64_t) k; } +/// Byte offset of row `row` superblock `s`'s fp16 d (s = k / 8 for item k). +STRATA_NIB_HD constexpr uint64_t d_off(int64_t row, int64_t s) { return kDOff + ((uint64_t) row * kSuper + (uint64_t) s) * 2; } +/// A converted slot's size for a raw blob whose down rows are `down_bytes` long. +STRATA_NIB_HD constexpr uint64_t slot_bytes_for(uint64_t down_bytes) { + return (kGuBytes + down_bytes + kSlotAlign - 1) / kSlotAlign * kSlotAlign; +} + +// ------------------------------------------------------------------------------------------------ the formats + +inline constexpr int kIQ3_XXS = 18; +inline constexpr int kIQ3_S = 21; +inline constexpr int kIQ2_S = 22; + +/// Whether `gu_type` is converted (the three formats whose weights take at most 16 values). +STRATA_NIB_HD constexpr bool fmt_built(int gu_type) { return gu_type == kIQ2_S || gu_type == kIQ3_XXS || gu_type == kIQ3_S; } +/// The GGUF gate/up row bytes of `gu_type` at kNEmbd (a converted layer's raw blob must agree; 0 = not a format here). +STRATA_NIB_HD constexpr uint64_t raw_gu_row(int gu_type) { + return gu_type == kIQ2_S ? 820 : gu_type == kIQ3_XXS ? 980 : gu_type == kIQ3_S ? 1100 : 0; +} +inline const char* fmt_name(int gu_type) { + switch (gu_type) { + case kIQ3_XXS: return "IQ3_XXS"; + case kIQ3_S: return "IQ3_S"; + case kIQ2_S: return "IQ2_S"; + default: return "?"; + } +} + +// ------------------------------------------------------------------------------------------------ the item code +// +// `g[32]` below is one item as the production `Split::load` leaves it: g[4 * j + b] is byte b of W.g[j] +// (j = 0..7, the dp4a order against the q8_1 block's qs words). Word m (0..3) of the 16-byte code holds W.g[2m] +// and W.g[2m + 1]: +// +// IQ2_S bits 4b..4b+3 = c(g[8m + b]), bits 16+4b.. = c(g[8m + 4 + b]), b = 0..3 +// c = magnitude index of {8, 25, 43} | sign << 2: the PRMT selector into {8,25,43,0} {-8,-25,-43,0} +// IQ3_XXS same nibble positions; c = index of {4, 12, 20, 28, 36, 44, 52, 62} | sign << 3 +// IQ3_S byte b = u(g[8m + b]) | u(g[8m + 4 + b]) << 4, u = (v + 15) / 2 (v odd, -15..15); v = 2u - 15 +// +// The scale byte keeps the production integer scale step's input: +// IQ2_S the block's scales byte for the item: ls0 | ls1 << 4 (W.ls0, W.ls1) +// IQ3_XXS aux32 >> 28 (0..15, W.ls) +// IQ3_S 1 + 2 * nibble (1..31, W.ls) + +/// Encodes one item; false when a weight is outside the format's code set (the conversion then refuses to start). +inline bool encode_item(int gu_type, const int8_t g[32], uint32_t q[4]) { + bool ok = true; + auto code = [&](int8_t v) -> uint32_t { + const int a = v < 0 ? -(int) v : (int) v; + if (gu_type == kIQ3_S) { + if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; } + return (uint32_t) (((int) v + 15) / 2); + } + if (gu_type == kIQ3_XXS) { + static constexpr int mag[8] = { 4, 12, 20, 28, 36, 44, 52, 62 }; + for (uint32_t i = 0; i < 8; ++i) + if (a == mag[i]) return i | (v < 0 ? 8u : 0u); + ok = false; + return 0; + } + const uint32_t m = a == 8 ? 0u : a == 25 ? 1u : a == 43 ? 2u : 3u; // IQ2_S + if (m == 3u) { ok = false; return 0; } + return m | (v < 0 ? 4u : 0u); + }; + for (int m = 0; m < 4; ++m) { + uint32_t w = 0; + for (int b = 0; b < 4; ++b) { + const uint32_t c0 = code(g[8 * m + b]), c1 = code(g[8 * m + 4 + b]); + if (gu_type == kIQ3_S) w |= (c0 | c1 << 4) << (8 * b); + else w |= c0 << (4 * b) | c1 << (16 + 4 * b); + } + q[m] = w; + } + return ok; +} + +/// Decodes one item's code back to the production W.g bytes (the host reference the parity program compares with; +/// the device decoders give the same bytes). Codes outside the set decode as the PRMT does: IQ2_S index 3 -> 0. +inline void decode_item(int gu_type, const uint32_t q[4], int8_t g[32]) { + static constexpr int8_t iq2[8] = { 8, 25, 43, 0, -8, -25, -43, 0 }; + static constexpr int8_t iq3[8] = { 4, 12, 20, 28, 36, 44, 52, 62 }; + for (int m = 0; m < 4; ++m) + for (int b = 0; b < 4; ++b) { + uint32_t c0, c1; + if (gu_type == kIQ3_S) { + c0 = q[m] >> (8 * b) & 15u; + c1 = q[m] >> (8 * b + 4) & 15u; + } else { + c0 = q[m] >> (4 * b) & 15u; + c1 = q[m] >> (16 + 4 * b) & 15u; + } + auto val = [&](uint32_t c) -> int8_t { + if (gu_type == kIQ3_S) return (int8_t) (2 * (int) c - 15); + if (gu_type == kIQ3_XXS) return (int8_t) ((c & 8u) ? -iq3[c & 7u] : iq3[c & 7u]); + return iq2[c & 7u]; + }; + g[8 * m + b] = val(c0); + g[8 * m + 4 + b] = val(c1); + } +} + +// ------------------------------------------------------------------------------------------------ the slot hash +// +// STRATA_EXPERT_NIBBLE_RECHECK's fingerprint of a slot: over the slot's first `hashed` bytes (kGuBytes plus the down +// rows; the alignment tail is not written and not hashed) as little-endian 32-bit words w_i, the last one +// zero-extended, H = sum_i (uint64) (w_i ^ i) * kHashMul mod 2^64. A sum, so the device's order of adding does not +// change it; the index term makes a moved word count. + +inline constexpr uint64_t kHashMul = 0x9E3779B97F4A7C15ull; + +/// The host reference of the slot hash (the device hash gives the same value for the same bytes). +inline uint64_t hash_host(const void* p, uint64_t bytes) { + const uint8_t* s = (const uint8_t*) p; + uint64_t h = 0; + const uint64_t n = (bytes + 3) / 4; + for (uint64_t i = 0; i < n; ++i) { + uint32_t w = 0; + const uint64_t at = 4 * i, take = bytes - at < 4 ? bytes - at : 4; + std::memcpy(&w, s + at, (size_t) take); // little-endian hosts only + h += (uint64_t) (w ^ (uint32_t) i) * kHashMul; + } + return h; +} + +// ------------------------------------------------------------------------------------------------ the switches + +struct Config { + bool on = false; ///< STRATA_EXPERT_NIBBLE=1 + bool recheck = false; ///< STRATA_EXPERT_NIBBLE_RECHECK=1 (debug: every slot's hash per request) + std::vector fmts{ kIQ2_S, kIQ3_XXS, kIQ3_S }; ///< STRATA_EXPERT_NIBBLE_FMTS (default 22,18,21) + std::vector skip; ///< STRATA_EXPERT_NIBBLE_SKIP: layers kept in their GGUF blocks + std::string error; ///< non-empty: a malformed value - the start is refused +}; + +namespace detail { +/// "a,b,c" -> integers; false on anything else (empty = an empty list). +inline bool parse_list(const char* s, std::vector& out) { + out.clear(); + while (s != nullptr && *s != '\0') { + char* end = nullptr; + const long long v = std::strtoll(s, &end, 10); + if (end == s) return false; + out.push_back((int64_t) v); + s = end; + if (*s == ',') ++s; + else if (*s != '\0') return false; + } + return true; +} +} // namespace detail + +/// The switches, read once (generate.cpp reads them before anything is allocated). +inline const Config& config() { + static const Config c = [] { + Config r; + const char* e = std::getenv("STRATA_EXPERT_NIBBLE"); + if (e != nullptr && e[0] != '\0' && std::strcmp(e, "0") != 0) { + if (std::strcmp(e, "1") == 0) r.on = true; + else r.error = std::string("STRATA_EXPERT_NIBBLE=") + e + ": expected 0 or 1"; + } + const char* rc = std::getenv("STRATA_EXPERT_NIBBLE_RECHECK"); + r.recheck = rc != nullptr && std::strcmp(rc, "1") == 0; + std::vector v; + if (const char* f = std::getenv("STRATA_EXPERT_NIBBLE_FMTS"); f != nullptr && f[0] != '\0') { + if (!detail::parse_list(f, v)) { + if (r.error.empty()) r.error = std::string("STRATA_EXPERT_NIBBLE_FMTS=") + f + ": expected ggml types, e.g. 22,18,21"; + } else { + r.fmts.clear(); + for (const int64_t t : v) { + if (!fmt_built((int) t) && r.error.empty()) + r.error = "STRATA_EXPERT_NIBBLE_FMTS: type " + std::to_string(t) + + " is not converted (22 IQ2_S, 18 IQ3_XXS, 21 IQ3_S)"; + r.fmts.push_back((int) t); + } + } + } + if (const char* k = std::getenv("STRATA_EXPERT_NIBBLE_SKIP"); k != nullptr && k[0] != '\0') { + if (!detail::parse_list(k, r.skip) && r.error.empty()) + r.error = std::string("STRATA_EXPERT_NIBBLE_SKIP=") + k + ": expected layer numbers, e.g. 40,44"; + } + return r; + }(); + return c; +} + +/// With the switch on, the first environment setting it refuses, as a message (empty = none): the paths that would +/// read a converted slot as GGUF blocks, write GGUF bytes into one, or run other kernels for the converted layers +/// than the ones the 4-bit kernels are bit for bit. The command-line half (--peer-device, remote expert caches, +/// --kv-grow, --vram-elastic), the cc 6.0 check, full residency and no loan are generate.cpp's checks; the prompt +/// path's own (MMQ on every converted layer) is Prefill::nibble_prompt_check. +inline std::string env_conflicts() { + auto set = [](const char* n) -> const char* { + const char* v = std::getenv(n); + return v != nullptr && v[0] != '\0' ? v : nullptr; + }; + const char* v = set("STRATA_MMQ_DIRECT"); + if (v != nullptr && std::atoi(v) != 0) + return "STRATA_MMQ_DIRECT (the prompt MMQ would read a converted slot in place as GGUF blocks)"; + v = set("STRATA_PREFILL_MMQ"); + if (v != nullptr && std::atoi(v) == 0) return "STRATA_PREFILL_MMQ=0 (the FP16 prompt path reads GGUF blocks)"; + v = set("STRATA_PF_FUSED"); + if (v != nullptr && v[0] == '1') return "STRATA_PF_FUSED=1 (the fused prompt kernels read GGUF blocks)"; + v = set("STRATA_FS_SLOTS"); + if (v != nullptr && std::atoi(v) > 0) return "STRATA_FS_SLOTS (Foresight swaps GGUF blobs into slots)"; + v = set("STRATA_EXPERT_V2"); + if (v != nullptr && v[0] == '1') return "STRATA_EXPERT_V2=1 (the S26 kernels, not the CUDA layout, on IQ3_S)"; + v = set("STRATA_KV_GROW"); + if (v != nullptr && v[0] != '0') return "STRATA_KV_GROW (the elastic K/V moves slots at their GGUF size)"; + v = set("STRATA_EXP_MODE"); + if (v != nullptr && std::atoi(v) != 0 && std::atoi(v) != 8) + return "STRATA_EXP_MODE other than 0 or 8 (another layout's gate/up kernels)"; + return {}; +} + +// ------------------------------------------------------------------------------------------------ the VRAM table + +/// One layer's slots. `on` false: the GGUF blob, `slot_bytes == raw_bytes`, the production kernels. +struct LayerVram { + bool on = false; + int gu_type = -1, d_type = -1; + uint64_t down_off = 0; ///< in the slot: kDownOff when on, else the raw blob's down_off + uint64_t down_bytes = 0; ///< the down rows (raw_bytes - raw_down_off) + uint64_t hashed = 0; ///< bytes the slot hash covers: kGuBytes + down_bytes when on, else 0 + uint64_t slot_bytes = 0; ///< what the expert cache allocates per slot (`open_sized`, every estimate) + // the raw blob as the arena and the pack hold it (expert_layout().fmt[l]); the transcoder reads these + uint64_t raw_bytes = 0, raw_gu_row = 0, raw_up_off = 0, raw_down_off = 0; +}; + +/// One layer's entry from its GGUF format and the switches (pure; `plan_layers` calls it per layer). +inline LayerVram plan_layer(int64_t l, const strata::kernels::cpu::NativeFmt& f, const Config& c) { + LayerVram v; + v.gu_type = f.gu_type; + v.d_type = f.d_type; + v.raw_bytes = f.bytes; + v.raw_gu_row = f.gu_row; + v.raw_up_off = f.up_off; + v.raw_down_off = f.down_off; + v.down_bytes = f.bytes - f.down_off; + v.down_off = f.down_off; + v.slot_bytes = f.bytes; + bool listed = false, skipped = false; + for (const int t : c.fmts) listed = listed || t == f.gu_type; + for (const int64_t s : c.skip) skipped = skipped || s == l; + // [gate | up | down] exactly, no NVFP4 tail, the down rows a whole number of 16-byte words (the gathers copy them so) + const bool shape = f.n_embd == kNEmbd && f.n_ff == kNFf && f.gu_row == raw_gu_row(f.gu_type) && + f.up_off == (uint64_t) kNFf * f.gu_row && f.down_off == 2 * f.up_off && f.bytes > f.down_off && + f.tail_off == 0 && (f.bytes - f.down_off) % 16 == 0; + if (c.on && c.error.empty() && listed && !skipped && fmt_built(f.gu_type) && shape) { + v.on = true; + v.down_off = kDownOff; + v.hashed = kGuBytes + v.down_bytes; + v.slot_bytes = slot_bytes_for(v.down_bytes); + } + return v; +} + +/// Every layer's entry for this pack (all off for a Q2_0 pack or with the switch off). `err`: a SKIP layer out of +/// range, or the switch on with a Q2_0 pack. +inline std::vector plan_layers(const strata::kernels::cpu::ExpertLayout& lay, std::string& err) { + const Config& c = config(); + std::vector out((size_t) (lay.n_layers > 0 ? lay.n_layers : 0)); + for (int64_t l = 0; l < (int64_t) out.size(); ++l) { + if (lay.native && (size_t) l < lay.fmt.size()) out[(size_t) l] = plan_layer(l, lay.fmt[(size_t) l], c); + else out[(size_t) l].slot_bytes = out[(size_t) l].raw_bytes = lay.blob_bytes(l); + } + if (c.on && !lay.native) err = "STRATA_EXPERT_NIBBLE needs a native pack (native_experts.txt)"; + for (const int64_t s : c.skip) + if (c.on && (s < 0 || s >= lay.n_layers) && err.empty()) + err = "STRATA_EXPERT_NIBBLE_SKIP: layer " + std::to_string(s) + " is not in the model"; + return out; +} + +namespace detail { +inline std::vector& table() { + static std::vector t; + return t; +} +} // namespace detail + +/// generate.cpp only: the table, once, after `expert_layout_load` and BEFORE the first slot estimate (placement +/// search, can_start, the cache's auto size, every `open_sized`). Not thread-safe: set before any other thread. +inline void set_layers(std::vector v) { detail::table() = std::move(v); } + +/// Layer `l`'s entry (an off entry when the table is not set or `l` is outside it). Read-only after `set_layers`. +inline const LayerVram& layer(int64_t l) { + static const LayerVram off; + const auto& t = detail::table(); + return l >= 0 && (size_t) l < t.size() ? t[(size_t) l] : off; +} + +/// Whether any layer is converted (the switch on and the table set). +inline bool any_on() { + for (const LayerVram& v : detail::table()) + if (v.on) return true; + return false; +} + +/// Bytes of one of layer `l`'s VRAM slots: the converted size for a converted layer, else the layout's blob bytes +/// (exactly `expert_layout().blob_bytes(l)`: with the switch off every caller sizes what it sized before). +inline uint64_t slot_bytes(int64_t l) { + const auto& t = detail::table(); + if (l >= 0 && (size_t) l < t.size()) return t[(size_t) l].slot_bytes; + return strata::kernels::cpu::expert_layout().blob_bytes(l); +} + +// ------------------------------------------------------------------------------------------------ fatal paths + +/// A converted layer reached a path that would compute or copy it as GGUF blocks: say where and stop. Never a +/// silent wrong answer. +[[noreturn]] inline void fatal(int64_t l, const char* where, const char* why) { + std::fprintf(stderr, "strata: STRATA_EXPERT_NIBBLE: layer %lld (%s, 4-bit slots) reached %s: %s - stopping\n", + (long long) l, fmt_name(layer(l).gu_type), where != nullptr ? where : "?", why != nullptr ? why : ""); + std::fflush(stderr); + std::abort(); +} + +/// Before each raw slot copy that bypasses the ExpertCache API (the adaptive tier's copies, the elastic K/V's slot +/// moves): fatal when `l` is a converted layer. The startup refusals keep these paths off; this is the backstop +/// (with `ExpertCache::seal()` for the API's own fills). +inline void guard_raw(int64_t l, const char* where) { + if (layer(l).on) fatal(l, where, "a raw slot copy at the GGUF size"); +} + +// ------------------------------------------------------------------------------------------------ the decode kernels +// +// Two skeletons in the shape of native_gu_multi_kernel (16 lanes a row, a group's entries GRP_NC at a time), both bit +// for bit the production gate/up: S stages the entries' q8_1 blocks in shared memory and decodes each item where it +// is used (IQ3_S: v = 2u - 15 restored per byte, then the production apply); P loads the lane's codes, scales and d +// before staging the qs words as 16-byte rows (IQ3_S: sum = 2 dot(u, x) - 15 sum(x), the same int32). Per format the +// faster one on 4x GP100 at T = 1..6 (native_expert_bench --nibble): IQ2_S P, IQ3_XXS S, IQ3_S S. + +inline constexpr int kSkelS = 0, kSkelP = 1; +STRATA_NIB_HD constexpr int gu_skeleton(int gu_type) { return gu_type == kIQ2_S ? kSkelP : kSkelS; } + +// ------------------------------------------------------------------------------------------------ iq_kernels.cu +// +// Device addresses are `unsigned long long` (as native_expert_grouped's grp_ptr), streams `void*`; each returns the +// CUDA error code (0 = success) so the caller can name the layer. A build without STRATA_EXPERT_NIBBLE_BUILT +// returns cudaErrorInvalidValue (1) from each. + +/// The reverse codebooks (grid magnitudes -> GGUF grid index) `check_gguf` and `gather_gguf` use, built on the CURRENT +/// device (once per device; call it at load, before any capture). Non-zero also when a grid entry is not unique. +int prepare(void* stream); + +/// Converts `n` raw blobs of layer `L` (device `staging`, `L.raw_bytes` apart, as the host arena holds them) into +/// the converted slots at `slot_ptrs[0..n)` (a device array): codes, scales, d. The down rows are not touched (the +/// caller copies them to `slot + kDownOff`). Every item is decoded with the production `Split::load`, encoded, +/// decoded from the written code again and compared with W.g[0..7], the scale and d; each item that differs or holds +/// a weight outside the code set adds 1 to `*bad` (device). L.on must be true. +int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream); + +/// The GGUF gate/up blocks rebuilt from each of the `n` (<= 64) converted slots at `slot_ptrs` and its down rows, +/// compared with the raw blobs in `staging` (`L.raw_bytes` apart) byte for byte: each 32-bit word that differs adds 1 +/// to `*bad`. `prepare` first. +int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs, + unsigned long long* bad, void* stream); + +/// The prompt path's gather of a converted layer's experts (prefill.cpp, MMQ): for q in [first, n) (n <= 16), the +/// GGUF [gate | up] blocks rebuilt from slot `slots[q]` (host array of device addresses) into gu_dst + q * gu_stride - +/// the bytes the raw blob holds, byte for byte - and its down rows copied to d_dst + q * d_stride; `zero_bytes` zeroed +/// after expert n - 1's gate/up and down (MMQ's tail). Every address, stride and size 16-byte aligned. `prepare` +/// on this device first. +int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride, + void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream); + +/// The slot hash (`hash_host`'s value) of the `L.hashed` bytes at each `slot_ptrs[i]`, into device `out[0..n)`. +int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out, + void* stream); + +} // namespace strata::core::nibble diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 3ab77dc2..2ca36784 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -819,7 +819,11 @@ public: /// windows, with no adaptive round in flight. A failed read leaves the copy as it was. Not with /// STRATA_EXCHANGE_ROTATE (false, nothing changes). bool replace_resident(int64_t layer, int64_t in, int64_t out); + /// STRATA_RAM_ADAPT: the same move as replace_resident, but `in` is copied out of the finished stage buffer + /// a demand read left it in (no file read). False, nothing changed, when `in` is not staged or still filling. + bool replace_resident_staged(int64_t layer, int64_t in, int64_t out); int64_t ram_adapts() const { return ram_adapts_; } + int64_t ram_staged() const { return ram_staged_; } ///< of ram_adapts(): copied out of a stage buffer // ---- 149-prefetch (STRATA_RAM_ADAPT2): the same promotion, staged. `ram_stage` queues the read of `in` on an I/O thread // (false: already queued, the queue is full, or no compact copy); `ram_install` - called by the decode thread at a window // boundary, when no window reads the RAM copy - puts every read that has landed into `out`'s place, unless the GPU tier @@ -1106,7 +1110,8 @@ private: std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; - int64_t ram_adapts_ = 0; ///< replace_resident: experts moved from the file into the compact copy + int64_t ram_adapts_ = 0; ///< replace_resident(_staged): experts moved into the compact copy + int64_t ram_staged_ = 0; ///< replace_resident_staged: of those, copied out of a stage buffer std::vector ram_adapt_buf_; ///< ...one blob, read here before it replaces another // 149-prefetch: the staged promotions (ram_stage / ram_install) struct RamJob { int64_t layer, in, out; std::vector buf; int state; }; ///< state 0 queued, 1 reading, 2 landed, 3 failed diff --git a/include/strata/core/native_head.hpp b/include/strata/core/native_head.hpp index 501f6ec2..29fe9d37 100644 --- a/include/strata/core/native_head.hpp +++ b/include/strata/core/native_head.hpp @@ -43,7 +43,8 @@ private: /// Plan v0.3 P6: `token_embd.weight` in its GGUF form (the IQ model files), in mapped pinned host memory: a row /// is read over PCIe per token, so the table costs no VRAM. `embed_row`, the verify window and the MTP drafter -/// use it instead of the canonical table when it is set (`set_native_embed`). +/// use it instead of the canonical table when it is set (`set_native_embed`). `STRATA_EMBED_VRAM=1` places the +/// same bytes in VRAM instead (slow PCIe links); the gathers read `dev_` either way. class NativeEmbed { public: NativeEmbed() = default; @@ -57,6 +58,8 @@ public: void gather_one(int64_t token, float* out, void* stream) const; uint64_t bytes() const { return bytes_; } int type() const { return type_; } + /// The table was placed in VRAM (STRATA_EMBED_VRAM=1, or the pinned / alias fallbacks) rather than mapped. + bool in_vram() const { return dev_ != nullptr && host_ == nullptr; } private: void* host_ = nullptr; diff --git a/include/strata/core/ple_residency.hpp b/include/strata/core/ple_residency.hpp index 1135b89e..b9e3829e 100644 --- a/include/strata/core/ple_residency.hpp +++ b/include/strata/core/ple_residency.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include "strata/core/conversation_memory.hpp" @@ -26,4 +27,11 @@ inline bool ple_resident_admit(std::optional available, uint64_t table return conversation_memory_admit(available, table_bytes + experts_ram_bytes, headroom_bytes); } +/// May the residency policy run at all? STRATA_PLE_AUTO_RAM when it is set (0 off, anything else on: an explicit value wins), otherwise on +/// except under STRATA_DEFAULTS=026 (`v026`: v0.2.6 had no such policy, the direct reads stayed). +inline bool ple_auto_ram_allowed(const char* env_value, bool v026) { + if (env_value != nullptr) return std::atoi(env_value) != 0; + return !v026; +} + } // namespace strata::core diff --git a/include/strata/core/sm120_series.hpp b/include/strata/core/sm120_series.hpp index 7dad43d7..e116e0ff 100644 --- a/include/strata/core/sm120_series.hpp +++ b/include/strata/core/sm120_series.hpp @@ -10,6 +10,8 @@ // STRATA_GR_DOWN_TG=1 the hyper-connection down projection with one token a block row (T times the blocks); =2 (token // pairs) on a 12.0 card with fewer than 80 SMs // STRATA_GU_SWIGLU=1 gate/up, SwiGLU and the q8_1 blocks of the routed experts in one launch +// STRATA_GR_UP_WIDE=1 the hyper-connection up projection with one warp a row (1,280 blocks instead of 160; +1.9% +// story / +0.7% code decode on the RTX PRO 5000, 5 pairs, token ids identical; bitwise) // and one that rounds differently (KL-checked, the AMD gfx12 rule): STRATA_PF_FUSED (the native packs' prompt experts on the // fused int8 kernels, IQ2_S / IQ3_XXS / IQ3_S / IQ4_XS gate/up only, 12.0 cards with 80+ SMs only; =0 keeps MMQ, =1 takes every // covered format on any card). @@ -40,4 +42,60 @@ inline bool is_sm120(int major, int minor) { return cc_major_of(major) == 12 && /// the default of a bitwise switch of the set: on for a 12.0 card unless STRATA_SM120_PERF=0 inline bool sm120_default(int major, int minor) { return is_sm120(major, minor) && sm120_series(); } +// ---- 0.2.7 defaults of the CUDA speed work (pure rules; the engine reads the device and calls these; tests in arch_defaults_test) +// `hip`: a HIP build, where a gfx1200 / gfx1201 reports compute capability 12.0 as well and none of these is measured or wanted. +// `v026`: STRATA_DEFAULTS=026 (defaults_026.hpp qwen_defaults_026()): every one of these is then off, as in v0.2.6. An explicit variable +// (STRATA_ROUTE_PRIOR=2, STRATA_GR_V3=1, ...) is decided by the caller before it asks the rule, so it still wins. +// `total_bytes`: the card's memory (cudaDeviceProp::totalGlobalMem); `integrated`: a GPU that shares the PC's memory. +constexpr double kSmallCardGiB = 13.0; // "a 12 GB card": 12 GB cards report 11.6 - 12.0 GiB, 16 GB ones 15.6 - 16.0 + +/// The residency-bias bonus a discrete CUDA card of 13 GiB or less gets when the user set nothing: THE one place the value lives. 1.5 since the +/// owner decision of 2026-10-26 (it was 2.0 in the first 0.2.7 candidates): on the RTX 3060 12 GB with IQ3_XXS the copy and code check found real +/// defects at 2.0 and none in 19 tasks at 1.5 or 1.0, and 1.5 keeps the speed (story +15%, code +37% against off). A longer 61-task check of +/// 0 / 1.5 / 2.0 is still running; if it shows defects at 1.5 this falls back to 1.0. +constexpr float kRoutePriorSmallCard = 1.5f; + +/// STRATA_ROUTE_PRIOR when the user set nothing: kRoutePriorSmallCard (residency-biased routing, changes which experts run; owner-approved for 12 GB +/// cards) on a discrete CUDA card of 13 GiB or less, 0 everywhere else. Measured on an RTX 3060 12 GB only. +inline float route_prior_default(bool hip, bool integrated, double total_bytes, bool v026 = false) { + return !v026 && !hip && !integrated && total_bytes > 0.0 && total_bytes / 1073741824.0 <= kSmallCardGiB ? kRoutePriorSmallCard : 0.0f; +} + +/// STRATA_GR_V3 (the stream-split hyper-connection read, another summation order) when the user set nothing: ON for a discrete compute capability +/// 12.0 card (STRATA_SM120_PERF=0 turns the set off) with more than 13 GiB, CUDA builds only. Measured: RTX PRO 5000 72 GB +1.2% decode clean, +/// -3.0% / -5.9% on 2x RTX A4000 (sm_86), +1.0% / -3.4% on an RTX 3060 (sm_86): so not those; a 12 GB sm_120 card is unmeasured. +inline bool gr_v3_default(bool hip, int major, int minor, bool integrated, double total_bytes, bool v026 = false) { + return !v026 && !hip && !integrated && sm120_default(major, minor) && total_bytes / 1073741824.0 > kSmallCardGiB; +} + +/// STRATA_PROMPT_ATTN_IMMA (the prompt attention on int8 tensor cores, another summation order) when the user set nothing: ON for every CUDA card of +/// compute capability 8.0 or newer (the int8 m16n8k32 MMA), not Turing / Volta / Pascal, not HIP. `cc` = 10 * major + minor as the engine +/// resolves it (an emulated or forced Turing counts as 75). Measured on sm_120 (RTX PRO 5000) and sm_86 (2x RTX A4000): +1.1 .. +1.8% prompt. +inline bool prompt_attn_imma_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc >= 80; } + +/// STRATA_MMVQ_IL_89 (#3453: the decode kernel row tables of an Ada card, the cells where an RTX 4070 and an RTX 4080 agreed; bitwise the same +/// output, only the rows-a-warp split differs) when the user set nothing: ON for compute capability 8.9 only (owner decision, 26 October: not yet +/// measured on an Ada card by us), off under STRATA_DEFAULTS=026 and in HIP builds. `cc` = 10 * major + minor as the engine resolves it. +inline bool mmvq_il_89_default(bool hip, int cc, bool v026 = false) { return !v026 && !hip && cc == 89; } + +/// The two sm_80-only defaults of 0.2.7 (#3779: the wide dense dequant and the MMVQ-IL sm_80 tables, both bitwise the old output, measured on a +/// CMP 170HX only) given the text of their variable (nullptr = unset): "1" on and "0" off win, unset is on unless STRATA_DEFAULTS=026. +inline bool sm80_default_on(const char* env, bool v026 = false) { + if (env != nullptr && env[0] == '1') return true; + if (env != nullptr && env[0] == '0') return false; + return !v026; +} + +/// The answer for STRATA_MMVQ_IL_89 given the variable's text (nullptr = unset): "1" on and "0" off win over everything, anything else (unset, +/// empty, other text) is the rule above. +inline bool mmvq_il_89_resolve(const char* env, bool hip, int cc, bool v026 = false) { + if (env != nullptr && env[0] == '1') return true; + if (env != nullptr && env[0] == '0') return false; + return mmvq_il_89_default(hip, cc, v026); +} + +/// STRATA_GR_UP_WIDE (the hyper-connection up projection, one warp a row; bitwise the old kernel) when the user set nothing: ON for a compute +/// capability 12.0 card (STRATA_SM120_PERF=0 turns the set off), CUDA builds only. +inline bool gr_up_wide_default(bool hip, int major, int minor, bool v026 = false) { return !v026 && !hip && sm120_default(major, minor); } + } // namespace strata diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index e878b9ed..c0e67b51 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -453,10 +453,20 @@ private: /// whose graph does not fit used to end the engine ("verify: instantiate: out of memory"); a freed size is captured /// again when it is next used. bool instantiate_evicting(cudaGraphExec_t& ex, cudaGraph_t graph, const std::vector& key, const char* what, - std::string& err, int keep_t = -1); + std::string& err, int keep_t = -1, unsigned long long flags = 0); /// Free the graph of the largest window size other than `keep_t` (and the prelaunched one); `evicted`: there was one. bool evict_window_graph(int keep_t, bool& evicted, std::string& err); bool no_window_eviction_ = false; ///< capture_all wants every size at once: it must not free one to capture another + // STRATA_GRAPH_PRIO (record_window / capture): the captured tails of the priority streams at their joins and the + // main stream's tails at their forks, so that a capture that dropped the stream priorities can be repaired per + // node (apply_node_priorities walks each tail back to its fork) +#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // (the three methods are no-ops there) + std::vector prio_forks_; + std::vector> prio_tails_; +#endif + void note_prio_fork(cudaStream_t from); + void note_prio_tail(cudaStream_t on, int prio); + void apply_node_priorities(cudaGraph_t graph, int T); void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_ void accumulate_profile(const unsigned long long* stamps); void accumulate_profile_inner(const unsigned long long* stamps); ///< one window's stamps (host copy) into prof_sum_ @@ -577,9 +587,12 @@ private: cudaStream_t df_side_[2] = {}; cudaEvent_t df_fork_ = nullptr; cudaEvent_t df_join_[2] = {}; - cudaGraphExec_t exec_[9] = {}; - cudaGraphExec_t exec_nr_[9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise - bool launched_[9] = {}, launched_nr_[9] = {}; ///< this graph has been launched once (early_ple_flag: a cold first launch raises the PLE flag first) + // [sel_long_][T]: 1 is the long-context QSA select (STRATA_SELECT_LONG=1: multi-CTA top-k, shuffle-free decode + // scores; see run()); without it only [0] is ever captured + cudaGraphExec_t exec_[2][9] = {}; + cudaGraphExec_t exec_nr_[2][9] = {}; // #871: the doorbell variant of a stage that is all-resident otherwise + bool launched_[2][9] = {}, launched_nr_[2][9] = {}; ///< this graph has been launched once (early_ple_flag: a cold first launch raises the PLE flag first) + int sel_long_ = 0; // fork 34a35db (STRATA_SIDE_MIXER=1): the GDN gates and the QSA indexer on a branch of the window's graph beside the // mixer's projections, joined before the recurrence / the attention cudaStream_t side_ = nullptr; @@ -663,6 +676,7 @@ private: float *qidx_ = nullptr, *scores_ = nullptr, *attn_ = nullptr, *attn32_ = nullptr, *attn_scratch_ = nullptr; float* tail_snap_ = nullptr; // per QSA layer int32_t* sel_ = nullptr; + int32_t* topk_scratch_ = nullptr; // qsa_block_topk_long's multi-CTA exchange (STRATA_SELECT_LONG=1 only) float *logits_ = nullptr, *w_ = nullptr, *shared_ = nullptr, *parts_ = nullptr, *hit_out_ = nullptr; int32_t *ids_ = nullptr, *hit_slot_ = nullptr, *hit_dst_ = nullptr, *hit_count_ = nullptr; int32_t* plan_ = nullptr; // device copy of the plan block diff --git a/include/strata/dsv41/exl3.hpp b/include/strata/dsv41/exl3.hpp index b080a597..a5455b75 100644 --- a/include/strata/dsv41/exl3.hpp +++ b/include/strata/dsv41/exl3.hpp @@ -154,6 +154,10 @@ struct SetArgs { int max_rows = 0; // the most rows one expert of the set has int n_embd = 4096, n_ff = 2048; float limit = 0.0f; + // gate / up: the caller's F16 copy of the activations (row_idx picks the rows). The tiles round F32 to F16 for + // their shared-memory tile anyway, so the same values come out; this only saves the F32 read of the same rows by + // every column block of an expert (18-36 reads of 1.8-3.7 MB on a prompt) - MarLin's "small operand cheap". + const uint16_t* x16 = nullptr; }; /// h[local row] = FP16 clamped swiglu of gate and up over x[row_idx[local row]] (F32 rows, ldx floats apart). void set_gate_up(const SetArgs& a, const float* x, int ldx, const int* row_idx, uint16_t* h16, int ldh, cudaStream_t s); diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index ce06a9fe..b1f5ae5a 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -51,9 +51,16 @@ struct NativeExpertLayout { // APR (prism.hadamard): the down weights are Hadamard-folded, so native_expert_grouped rotates h before // quantizing it (hadamard_rows). had_block 0 = none; d_signs is a DEVICE vector of n_ff signs or nullptr. int had_block = 0; + bool gu_nib = false; // STRATA_EXPERT_NIBBLE: gate/up as 4-bit codes (strata/core/expert_nibble.hpp's + // slot); set only by native_expert_layout_nib const float* d_signs = nullptr; }; NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +/// STRATA_EXPERT_NIBBLE: a converted VRAM slot - gate/up as 4-bit codes, scales and d (expert_nibble.hpp's layout: +/// up_off = the up rows' codes, down_off = kGuBytes, bytes = the slot), the GGUF down rows after them. IQ2_S / +/// IQ3_XXS / IQ3_S at n_embd 2560, n_ff 640 only, and only in a build with the kernels (`native_expert_nib_supported`). +NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff); +bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; /// Whether `native_expert_grouped` has kernels for this gate/up and down type pair at these dimensions, and the /// prompt path's dequantizer takes both (checked for every layer at startup, before anything is allocated). bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept; @@ -83,9 +90,15 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long /// per possible group, SwiGLU and the q8_1 quantization as two kernels over all cap_entries. Bitwise the same results /// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs. void native_grouped_set_v1(bool v1); +/// The bench / parity only: the 4-bit gate/up kernel of every format (-1 = expert_nibble.hpp's gu_skeleton, the +/// default; 0 = the S skeleton; 1 = the P skeleton). Bitwise the same results; set before graph capture. +void native_expert_nib_set_variant(int v); +/// gu-proto (nib_gu_proto.cuh): variant v's registers, local bytes and resident 256-thread blocks per SM for gu_type; +/// false when v is not a gu-proto id (>= 10) or the type has none. +bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm); /// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase -/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down). +/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down, 3 gate/up only). void native_expert_set_mode(int mode, int phase); /// APR (prism.hadamard): y = H_block (signs * x) per block of `block` values of each of `rows` rows of `width` diff --git a/include/strata/kernels/native_mmvq.hpp b/include/strata/kernels/native_mmvq.hpp index ce11095c..7bdd468a 100644 --- a/include/strata/kernels/native_mmvq.hpp +++ b/include/strata/kernels/native_mmvq.hpp @@ -110,8 +110,15 @@ void native_q8_0_packed_register(const void* gguf_weights, const void* packed, i void native_q8_0_packed_unregister(const void* gguf_weights); /// STRATA_Q8_SM60=1 (opt-in, Pascal GP100): every Q8_0 dense matrix is packed as above whatever its shape, and the /// Q8_0 decode GEMVs run a kernel written for compute capability 6.0 (q8_sm60.cuh; not bitwise the exact kernels). -/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release. +/// native_q8_0_sm60_pack packs a device matrix here (the head) and owns the copy until native_q8_0_sm60_release; +/// native_q8_0_sm60_pack_quiet is the same with no line for a success (the caller sums several up). bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what); +bool native_q8_0_sm60_pack_quiet(const void* weights, int n_in, int n_out, const char* what); +/// The same for a matrix that nothing but native_mmvq reads (the MTP drafter's draft head subset): where every column +/// count takes the Pascal kernel and the planes stay 16-byte aligned, they replace the GGUF blocks in the matrix's own +/// allocation (the same byte count, staged through the host: no second copy); otherwise a packed copy as +/// native_q8_0_sm60_pack makes. Either way native_q8_0_sm60_release must run before the caller frees the matrix. +bool native_q8_0_sm60_pack_in_place(void* weights, int n_in, int n_out, const char* what); void native_q8_0_sm60_release(const void* weights); /// STRATA_Q6_PACKED=1 (opt-in): a packed copy of a Q6_K matrix (the output heads) - the same bytes as ql / qh / @@ -166,5 +173,8 @@ void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, cons int native_mmvq_il_rows_for(int cc, int ggml_type, int ncols, int n_out); // Tests and benchmarks: every native_mmvq_il call takes `rows` a warp (0: the table). void native_mmvq_il_tune(int rows); +// Tests and benchmarks: the P1 / P2 kernel variant for every native_mmvq_il call (0: today's kernel, 2-6 as +// STRATA_MMVQ_IL_PF; -1: the environment). +void native_mmvq_il_pf(int pf); } // namespace strata::kernels diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp index d25a1eee..9954a0f3 100644 --- a/include/strata/kernels/ngram.hpp +++ b/include/strata/kernels/ngram.hpp @@ -187,6 +187,10 @@ public: /// as ONE reader request - page dedupe and sort across the whole batch, the reader's full queue depth. Not /// while a single-token `issue` is pending. The mapped mode gathers row by row. bool gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err); + /// STRATA_PLE_COMPACT: the same rows as their raw IQ4_NL bytes (n_tokens x 16 rows of PLE_ROW_BYTES; a row past the + /// table: scale 0 and code 8 everywhere, which decode to the +0.0f gather_batch writes) for ple_iq4nl_dequant on the device. False (nothing + /// written) unless the table is in memory (--ple-io ram / mmap) and IQ4_NL. + bool gather_raw_iq4nl(const uint32_t* rows, size_t n_tokens, uint8_t* out) const; /// Fault injection (Direct mode): every row read completes no earlier than `us` after issue. void set_injected_delay_us(double us); diff --git a/include/strata/kernels/ple.hpp b/include/strata/kernels/ple.hpp index 98bfc388..a558e1e2 100644 --- a/include/strata/kernels/ple.hpp +++ b/include/strata/kernels/ple.hpp @@ -125,4 +125,8 @@ void ple_history_advance(float* hist, const float* normalized, void* stream); /// Whether the CUDA path is available. The host hash and the table read work without it; the block does not. bool ple_block_available(); +/// STRATA_PLE_COMPACT: `rows` raw IQ4_NL PLE rows (PleTable::gather_raw_iq4nl, PLE_ROW_BYTES each) to 160 floats each, +/// the floats iq4nl_dequant_row writes (d times the code's value, one multiply), on `stream`. +void ple_iq4nl_dequant(const uint8_t* raw, int64_t rows, float* out, void* stream); + } // namespace strata::kernels diff --git a/include/strata/kernels/qsa_pattn.hpp b/include/strata/kernels/qsa_pattn.hpp new file mode 100644 index 00000000..3fd8de0b --- /dev/null +++ b/include/strata/kernels/qsa_pattn.hpp @@ -0,0 +1,46 @@ +// include/strata/kernels/qsa_pattn.hpp - STRATA_PATTN_SM60: the prompt path's QSA attention on sm_6x, bit for bit +// what prefill.cpp gets today from qsa_decode_attn_batch (attn_chunk_kernel_pre75<1, 2> + attn_merge_kernel or +// attn_merge_v2_kernel, 32 queries a call) with int8 K/V. +// +// On sm_6x qsa_prompt_attn_batch returns false (no tensor cores) and the prompt reads every QSA layer's attention +// through the decode kernels: one CTA per (64-cell chunk, KV head, query), the partials of all 33 chunks written to +// scratch (817 KB a query) and merged by a second kernel. The kernels here keep every operation of that path in its +// order - each lane's 8-dimension products, warp_sum's tree over the 32 lanes, the chunk softmax (warp_max / __expf / +// warp_sum pairs), the ascending fmaf value fold, the merge's chunk order (fmaxf, __expf(m - M), fmaf(l, w, L), +// fmaf(acc, w, acc), acc / L) - and change only where operands live and which thread does what: +// - ps_score_x_kernel, one CTA per (chunk, KV head, query): q in registers (loaded once in a per-lane slot order), +// the chunk's K staged with 16-byte loads, two cells at a time through one reduce-scatter whose 24 sums are +// warp_sum's tree without reduce12's selects; writes the chunk's probabilities, rows, m and l to the scratch; +// - ps_value_d4_kernel, one CTA per (KV head, query): four dims x 12 heads a thread, V four bytes a load, the chunks +// in ascending order, each merged into the output as the merge kernel does (no partial accumulators, no merge +// kernel). +// The caller's attention scratch holds the blocks of ~100 queries; a prompt chunk runs in batches of that size. +// +// Off unless STRATA_PATTN_SM60=1, and compiled only in the CUDA build with STRATA_EXPERIMENTAL_SM60 (every other build +// links stubs that answer false, so the usual attention runs). +#pragma once + +#include "strata/kernels/qsa.hpp" +#include "strata/kernels/qsa_decode_attn.hpp" + +#include + +namespace strata::kernels { + +/// STRATA_PATTN_SM60: 0 off (default, and in a build without the sm_6x kernels); 1 on. +int pattn_mode(); + +/// qsa_decode_attn_batch for all `n_q` queries of a prompt chunk in one call (int8 K/V, sm_6x, experimental build). +/// `scratch` / `scratch_floats`: the caller's attention scratch (prefill.cpp: attn_batch x qsa_decode_attn_scratch_floats). +/// False: not applicable or a launch failed (nothing the caller can rely on was written; it runs the usual loop). +bool qsa_pattn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, int64_t cap, + const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, int64_t n_q, + void* stream); + +/// The same without the compute-capability test, for src/kernels/qsa_pattn_parity.cpp (it runs the kernels on any card +/// to compare them with the decode kernels' output). False in a build without the sm_6x kernels. +bool qsa_pattn_batch_any_arch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, uint64_t scratch_floats, float* attn, + int64_t n_q, void* stream); + +} // namespace strata::kernels diff --git a/include/strata/kernels/qsa_select.hpp b/include/strata/kernels/qsa_select.hpp index e8beacce..35ee7a58 100644 --- a/include/strata/kernels/qsa_select.hpp +++ b/include/strata/kernels/qsa_select.hpp @@ -78,4 +78,20 @@ bool qsa_block_topk_cluster(const float* scores, const int32_t* steps, int64_t n void qsa_block_topk_ref(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, const QsaShapes& s, int32_t* ids, void* stream); +/// The long-context decode select (the verifier's STRATA_SELECT_LONG=1 windows; CUDA builds with +/// STRATA_EXPERIMENTAL_SM60, elsewhere the plain calls). qsa_block_topk_long: qsa_block_topk's ids; a call with +/// `multi_scratch` (qsa_topk_multi_scratch_ints(nq) device ints, one call at a time per scratch, no initial value), no +/// active count and <= 16 queries runs several CTAs per query (block_topk_multi_*: STRATA_TOPK_MULTI=0 off, =1 on any +/// card, default compute capability 6.x past the register kernel's reach); otherwise it is qsa_block_topk. +/// qsa_block_scores_long: qsa_block_scores's bits; a call of <= 8 queries with no active count runs +/// block_scores_dx_kernel (STRATA_SCORES_DX=0 off, =1 on any card, default compute capability 6.x); otherwise it is +/// qsa_block_scores. +void qsa_block_topk_long(const float* scores, const int32_t* steps, int64_t nq, int64_t max_blocks, int64_t cap, + const QsaShapes& s, int32_t* ids, void* stream, int64_t active_blocks, int32_t* multi_scratch); +void qsa_block_scores_long(const float* pooled, const float* dead, const float* q_idx, const int32_t* steps, int64_t nq, + int64_t max_blocks, const QsaShapes& s, float* scores, void* stream, int64_t active_blocks); +/// Device ints a qsa_block_topk_long call of `nq` queries may use as multi_scratch (0 on a build without the multi-CTA +/// path: pass null). +int64_t qsa_topk_multi_scratch_ints(int64_t nq); + } // namespace strata::kernels diff --git a/include/strata/prefill/copy_events.hpp b/include/strata/prefill/copy_events.hpp new file mode 100644 index 00000000..b8e93e40 --- /dev/null +++ b/include/strata/prefill/copy_events.hpp @@ -0,0 +1,44 @@ +// include/strata/prefill/copy_events.hpp - which streamed expert copies get a "copied" event (#4005). +// +// The streamed prompt walk issues one host-to-device copy per expert entry on the copy stream and the compute stream +// waits for it. By default every entry records its own event (every == 1) and the compute stream waits on the event of +// the entry it needs. STRATA_PREFILL_COPY_EVENT_EVERY=N (tester switch) records every N-th entry only, and the +// compute stream waits on the first recorded entry at or after the one it needs: the copy stream is in order, so that +// event covers it. The two rules are pure functions so a host test can check them without a GPU. +#pragma once + +#include +#include + +namespace strata::prefill { + +/// The value of STRATA_PREFILL_COPY_EVENT_EVERY: 1 (every entry) unless the text is a number above 1; at most 64. +inline int copy_event_every_from(int parsed) { return parsed > 1 ? (parsed < 64 ? parsed : 64) : 1; } + +/// Entry `idx` of `total` records its copied event right after its copy: always with every == 1; else every N-th entry +/// and the last one. +inline bool copy_event_due(size_t idx, size_t total, int every) { + return every <= 1 || (idx + 1) % (size_t) every == 0 || idx + 1 == total; +} + +/// The entry whose recorded event a consumer waits on for entry `k`, when the entries [0, recorded) have had their +/// events decided (`recorded` = 1 + the last recorded entry) and `is_recorded(r)` says whether entry r has one. The +/// first recorded entry at or after k; the last recorded entry (recorded - 1) when none is found, which covers k as +/// well. Precondition: k < recorded. +template +inline size_t copy_event_entry(size_t k, size_t recorded, IsRecorded is_recorded) { + for (size_t r = k; r < recorded; ++r) + if (is_recorded(r)) return r; + return recorded - 1; +} + +/// STRATA_PREFILL_COPY_WAIT_DEDUPE: the copy stream may skip its wait on the release event of entry `idx`'s slot (`rel`) +/// when the wait it made for the previous entry was on the same event (`prev_rel`). That holds only when both slots were +/// released in the current walk (idx - 1 >= ring), because the event of an earlier walk can be re-recorded by this walk's +/// first flush, and when the ring is longer than one MMQ group of `group` experts, because a flush of a whole ring would +/// re-record the event right after the previous slot's wait. +inline bool copy_wait_dedupe_ok(size_t idx, int ring, int group, int rel, int prev_rel) { + return ring > group && idx > (size_t) ring && rel == prev_rel; +} + +} // namespace strata::prefill diff --git a/include/strata/prefill/gemm.hpp b/include/strata/prefill/gemm.hpp index 596b3e4b..80f625ee 100644 --- a/include/strata/prefill/gemm.hpp +++ b/include/strata/prefill/gemm.hpp @@ -66,6 +66,13 @@ public: /// Caller-owned buffers only: the scratch and workspace moved (the prompt path laid its buffers out again). void rebind(uint16_t* scratch, int64_t scratch_elems, void* workspace, size_t ws_bytes); + /// STRATA_DEQUANT_SIDE=1 (gemm_dequant_side): a second dequant scratch of scratch_elems() elements, caller-owned + /// like the first. native() then dequantizes on a side stream into the two in turn, so a weight's dequant runs + /// while the kernels queued ahead of its GEMM do; events order every write and read of each scratch, so the + /// products are the serial form's, bit for bit. nullptr: the serial form. Called after init_external and + /// after every rebind (the "scratch free" events are re-armed on the compute stream). CUDA only. + bool set_dequant_side(uint16_t* scratch2, std::string& err); + uint16_t* scratch() const { return scratch_; } int64_t scratch_elems() const { return scratch_elems_; } void* stream() const { return stream_; } @@ -77,6 +84,14 @@ private: int64_t scratch_elems_ = 0; void* workspace_ = nullptr; bool external_ = false; + // STRATA_DEQUANT_SIDE (set_dequant_side): the second scratch, the side stream and, per scratch, "the dequant + // landed" (recorded on the side stream) and "the GEMM read it" (recorded on the compute stream); side_cur_ is + // the scratch the next native() dequantizes into (0: scratch_, 1: side_scratch_) + uint16_t* side_scratch_ = nullptr; + void* side_stream_ = nullptr; + void* side_ready_[2] = {}; + void* side_free_[2] = {}; + int side_cur_ = 0; void* hipblaslt_state_ = nullptr; void* rocblas_state_ = nullptr; // HIP: the rocBLAS solution table of f16_inplace (STRATA_ROCBLAS_TUNING) bool f16_io_ = false; @@ -122,6 +137,11 @@ void gemm_set_dense_f32(int mode); /// set_act_f16). Cached per device (a layer split can mix cards). STRATA_HIP_PROMPT_F16=0/1 overrides. bool prompt_f16(); +/// STRATA_DEQUANT_SIDE=1: the prompt path's dense-weight dequant on a side stream with a second GEMM scratch +/// (Gemm::set_dequant_side; the prompt path takes the scratch from its borrowed region when this is on). Off by +/// default; always off on HIP (its padded / MMQ paths use the scratch on the compute stream without the events). +bool gemm_dequant_side(); + } // namespace strata::prefill diff --git a/include/strata/prefill/moe_fused.hpp b/include/strata/prefill/moe_fused.hpp index eef9e2dc..b69bf660 100644 --- a/include/strata/prefill/moe_fused.hpp +++ b/include/strata/prefill/moe_fused.hpp @@ -24,6 +24,14 @@ namespace strata::prefill::fused { constexpr int kTileRows = 64; /// Experts per launch: their blob pointers travel in the launch's parameters (1 KB). constexpr int kMaxBatch = 128; +/// The room of WideBatch::blob (below): a whole layer of 512 experts, which STRATA_PF_BATCH=512 (opt-in) launches at +/// once on the native kernels' NT = 256 instances when all of them are resident (4 KB of kernel parameters: CUDA 12.1+, +/// Volta and newer). HIP, gfx906 and the Pascal / Volta build (STRATA_EXPERIMENTAL_SM60): kMaxBatch. +#if defined(__HIPCC__) || defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_EXPERIMENTAL_SM60) +constexpr int kBatchRoom = kMaxBatch; +#else +constexpr int kBatchRoom = 512; +#endif /// This build has the kernels (a CUDA build; HIP and builds without MMQ do not). bool built(); @@ -57,6 +65,13 @@ struct Batch { int e0 = 0, e1 = 0; const uint8_t* blob[kMaxBatch] = {}; }; +/// Batch with room for kBatchRoom experts (e1 - e0 <= kBatchRoom): only the opt-in launches of STRATA_PF_BATCH above +/// kMaxBatch on the native NT = 256 or warp-specialized kernels (moe_fused_iq.hpp, native_wide()) take it; every other +/// launch takes Batch. +struct WideBatch { + int e0 = 0, e1 = 0; + const uint8_t* blob[kBatchRoom] = {}; +}; /// The batch's products: gate/up from `xa` (quantize_act of the layer's input, [tokens][2560]) through the rows /// `src` of `group`, SwiGLU, H as int8 into `ha` (act_bytes(n, 640)), down into `dm` [n][2560] FP32 at the rows of /// `group`. `n`: the layer's routed rows (tokens * k), which bounds the launch grid. diff --git a/include/strata/prefill/moe_fused_iq.hpp b/include/strata/prefill/moe_fused_iq.hpp index 7e63df9b..5cae47a1 100644 --- a/include/strata/prefill/moe_fused_iq.hpp +++ b/include/strata/prefill/moe_fused_iq.hpp @@ -38,5 +38,11 @@ void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, v /// through Alloc's 256-byte takes from a 256-aligned cache slot or cudaMalloc). void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src, void* ha, float* dm, void* stream); +/// The NT = 256 kernels (STRATA_PF_FUSED_NT=256 or _F16=1) or the warp-specialized kernel (STRATA_PF_FUSED_WS=1) are +/// set up on the current device: experts_native takes a WideBatch (STRATA_PF_BATCH up to kBatchRoom experts a launch). +bool native_wide(); +/// experts_native() of a WideBatch, on the NT = 256 kernels or the warp-specialized kernel; only when native_wide(). +void experts_native(const WideBatch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, + const int32_t* src, void* ha, float* dm, void* stream); } // namespace strata::prefill::fused diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index fee662fc..6fba093e 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -122,6 +122,11 @@ void gather_strata_q2(const uint8_t* blob, void* gu_dst, void* d_dst, void* stre /// h[r, k] = silu(gate) * up of GU rows [2 n_ff wide]: interleaved (gate 2k, up 2k+1: the Strata pack) or split /// (gate k, up n_ff + k: GGUF). FP32 out (the down product's quantizer reads floats). void swiglu(const float* gu, float* h, int64_t rows, int64_t n_ff, bool interleaved, void* stream); +/// swiglu (n_ff 640), then quantize() of its rows for a down product of `ggml_type`, in one pass: H never stored, +/// the same bytes in hq. Only where swiglu_quant_ok (a q8_1 D4 down type; gu 16-byte aligned): CUDA, the +/// STRATA_EXPERIMENTAL_SM60 build. +bool swiglu_quant_ok(int ggml_type); +void swiglu_quant(const float* gu, void* hq, int64_t rows, bool interleaved, void* stream); /// swiglu of an NVFP4 group's gate/up rows (split halves) with scale_gu_rows' scales applied as they are read. void swiglu_scaled(const float* gu, float* h, int64_t rows, int64_t n_ff, const int32_t* bounds, int n, const float* tails, int64_t row0, void* stream); diff --git a/include/strata/prefill/moe_ws.hpp b/include/strata/prefill/moe_ws.hpp new file mode 100644 index 00000000..d5a42eff --- /dev/null +++ b/include/strata/prefill/moe_ws.hpp @@ -0,0 +1,72 @@ +// include/strata/prefill/moe_ws.hpp - GP100 (sm_60, the STRATA_EXPERIMENTAL_SM60 build): the prompt path's expert +// products of a layer whose experts are all resident in VRAM, read in place there and weight-stationary: ONE launch +// for the layer's gate/up and ONE for its down instead of a gate/up, swiglu and down MMQ launch per 16-expert group. +// A CTA holds 128 (or 256) weight rows of one expert and runs them against up to 64 of the expert's activation rows, a +// thread per weight row: each weight block is decoded once per pass instead of once per MMQ tile, and an expert's +// rows are its own count, not the group's largest. Every product keeps MMQ's int8 values, scales and per-32-value +// epilogue in its K order (the down K loop stops at 640), so GU, H and Dm are the per-group MMQ's bits. Swift +// Flash's shapes and formats only: gate/up [1280 x 2560] IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS or IQ3_S, down [2560 x 640] +// Q2_0 or IQ4_NL. +#pragma once + +#include +#include + +namespace strata::prefill::ws { + +/// The products of a layer: 1 with STRATA_MMQ_WS=1 (opt-in) gate/up and down, else 0 (the per-group MMQ). 0 also where +/// the build has no kernels (HIP, no ggml sources, not the STRATA_EXPERIMENTAL_SM60 build) or a visible GPU is not +/// cc 6.0 (the kernels were tuned and checked on GP100 only). +int mode(); +/// mode() != 0 and both formats have kernels. +bool supported(int gu_type, int d_type); +/// STRATA_WS_FAST=1 (opt-in, read once): the IQ4_NL down's 32-token tier (u >= 20 rows per routed expert) runs a +/// kernel that issues fewer instructions per pass - a switch into the unrolled token pairs, dy transposed - with every +/// token's operations and their order unchanged, so Dm is the same bits. 0 (unset): the kernels as before. +int fast(); +/// Benches and tests: 0 / 1 overrides fast(), -1 goes back to the environment. +void set_fast(int v); +/// Tests: 0 / 1 overrides mode() (1 runs the kernels on a card that is not cc 6.0), -1 goes back to the environment. +void set_mode(int v); +/// The weight-stationary product of `ggml_type` beats the per-group MMQ at u rows per routed expert (the measured +/// ratios, moe_ws.cu; u is clamped to the measured 2.5 .. 160). +bool faster(int ggml_type, double u); +/// Every gate/up and down matrix starts this aligned (the IQ4_NL down reads 8-byte pieces; the expert cache's slots are +/// 256-byte aligned and the Swift gate/up sizes multiples of 8). +constexpr uint64_t kAlign = 8; + +/// The CTAs' work: rows [row0, row0 + rows) of Xq / GU / Hq / Dm, all of the expert at position j of the layer's order +/// (MMQ's: its xoff entry), at most kChunkRows. A CTA takes one chunk and one 128- or 256-row piece of the weights. +struct alignas(16) Chunk { + int32_t j, row0, rows, pad; +}; +constexpr int kChunkRows = 64; +/// The most chunks a layer of `rows` routed rows over at most `n_expert` experts makes. +inline size_t max_chunks(int64_t rows, int64_t n_expert) { return (size_t) (rows / kChunkRows + n_expert); } +/// The chunks of the n experts of `order` (expert e has cnt[e] rows from bounds[j], j its position), the largest +/// expert first (the long CTAs start first); returns their number (<= max_chunks). +size_t chunks(const int32_t* order, size_t n, const int32_t* cnt, const int32_t* bounds, Chunk* out); + +/// One layer: its n routed experts' matrices at w + xoff[j] (gate/up, rows 0-639 gate then up) and w + xoff[j] + +/// down_off (down), xoff on the device in the layer's order (Product::xoff's table, all n entries); `rows` = T*K. +struct Layer { + int gu_type = -1, d_type = -1; + const void* w = nullptr; + const int64_t* xoff = nullptr; + int64_t down_off = 0; + const Chunk* chunks = nullptr; ///< on the device + int64_t nchunks = 0; + int64_t rows = 0; + int n = 0; + const void* xq = nullptr; ///< the gate/up's q8_1 rows (mmq::quantize_scatter's, rows of them) + float* gu = nullptr; ///< [rows][1280], the rows MMQ writes through identity ids + const void* hq = nullptr; ///< H's q8_1 rows: ONE mmq::swiglu_quant over all `rows` rows of gu + float* dm = nullptr; ///< [rows][2560] +}; +/// The layer's gate/up into gu, one launch; false (nothing launched) where the per-group MMQ is to run instead (mode 0, +/// or not faster at this u) - the same GU rows either way. +bool gate_up(const Layer& L, void* stream); +/// The layer's down from hq into dm, one launch. +void down(const Layer& L, void* stream); + +} // namespace strata::prefill::ws diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 39ed8557..fa75c31d 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -169,6 +169,11 @@ public: /// build with the pointer-table MMQ (STRATA_MMQ_TAB). static size_t slot_guard_bytes(); + /// STRATA_EXPERT_NIBBLE=1: whether every converted layer's experts reach the prompt path's MMQ gather only (the + /// GGUF blocks rebuilt from the 4-bit slots); false with the first layer and the reason in `why`. Pure: the + /// layers' formats, the environment and the visible GPUs (generate.cpp asks once, before anything is allocated). + static bool nibble_prompt_check(std::string& why); + /// Positions [pos0, pos0 + n) holding `tokens`; `ss.ple_prev` must be the two tokens before pos0 (oldest /// first, -1 for none) and is advanced to the last two of these. bool run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err); diff --git a/include/strata/program/batch_groups.hpp b/include/strata/program/batch_groups.hpp index 9f614d45..168019b6 100644 --- a/include/strata/program/batch_groups.hpp +++ b/include/strata/program/batch_groups.hpp @@ -10,11 +10,41 @@ // the serial windows with the slots' drafts (the 0.1.42/0.1.43 behaviour). A number or `auto` given on the command line // is honoured as before. // +// The pipelined path starts no round of the adaptive VRAM tier on its own (the serial batch windows start one every +// `--adapt-every` windows): opt-in, STRATA_PIPE_ADAPT_EVERY=N lets it run one after every N group windows, once the groups +// in flight have finished (pipe_adapt_every / pipe_adapt_due below). +// // Pure (no GPU, no environment read): generate.cpp passes in what it knows. #pragma once +#include + namespace strata::program::batch_groups { +/// STRATA_PIPE_ADAPT_EVERY's value -> the interval in group windows; 0 (off: the pipelined path adapts nothing, as before) +/// when unset, empty, not a number, 0 or negative. +inline int pipe_adapt_every(const char* value) { + if (value == nullptr) return 0; + const int n = std::atoi(value); + return n > 0 ? n : 0; +} + +/// What the pipelined loop knows when it decides on a round. +struct PipeAdapt { + int every = 0; ///< pipe_adapt_every() + bool tier_on = false; ///< the adaptive tier counts the routing here (it is on and not the whole model) + bool async_tier = false; ///< --adapt-async 1 runs its own rounds + bool prompt_read = false; ///< a prompt is read beside the slots (it may hold a loan of cache slots) + bool swaps_pending = false; ///< the last round's copies have not landed yet + long long windows = 0; ///< group windows completed so far + long long last = 0; ///< `windows` when the last round ran +}; + +/// A round is due: the loop starts no new group, and runs the round once nothing is in flight. +inline bool pipe_adapt_due(const PipeAdapt& p) { + return p.every > 0 && p.tier_on && !p.async_tier && !p.prompt_read && !p.swaps_pending && p.windows - p.last >= p.every; +} + /// What kept `auto` from pipelining. enum class Serial { None, BatchMtp, AdaptAsync, TwoCardsSerialFaster }; diff --git a/metal/setup_mac.py b/metal/setup_mac.py index b939e246..774ac3b2 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -433,6 +433,18 @@ def main(argv=None) -> int: (BUILD_DIR / "BUILD.json").unlink(missing_ok=True) exe = build_engine(llama) if a.update: + # update.sh's own text: "The model files are not touched". The questions are asked anyway, so when the + # answers name a model (or an image encoder) that is not here, say it: a silent exit reads like a broken + # download (an M1 Max chose IQ3_S in update.sh and got no model and no message). + files = [Path(a.gguf_dir) / n if a.gguf_dir else models_root / tag / n for n in model_shard_names(model)] + pack = S.find_in(roots, f"packs/{tag.lower()}") or data / "packs" / tag.lower() + pack_done = (pack / "native_experts.txt").exists() and (pack / "tokenizer" / "vocab.json").exists() + if not (all(f.exists() and S.done(f) for f in files) and pack_done): + S.warn(f"{model} is not installed here, and an update does not download model files: nothing was installed") + S.say(f" to download and prepare {model}: ./setup.sh --setup") + elif vision == "yes" and not (models_root / fam["mmproj"]).exists(): + S.warn("the image encoder is not downloaded here, and an update does not download model files") + S.say(" to add image support: ./setup.sh --setup") return 0 # ---- 5. the model diff --git a/metal/src/engine/stubs_0145.cpp b/metal/src/engine/stubs_0145.cpp index 0c1976f6..a429dab1 100644 --- a/metal/src/engine/stubs_0145.cpp +++ b/metal/src/engine/stubs_0145.cpp @@ -147,5 +147,17 @@ namespace strata::kernels { bool gemm_iq_f16_grouped(int p0, void const* p1, uns // STRATA_Q8_SM60 (Pascal GP100, opt-in): a no-op on Metal; NativeHead::load()/unload() call these for a Q8_0 head, so they must exist and answer "nothing packed". namespace strata::kernels { bool native_q8_0_sm60_pack(void const* p0, int p1, int p2, char const* p3) { return false; } } namespace strata::kernels { void native_q8_0_sm60_release(void const* p0) { } } +// the MTP drafter's STRATA_MTP_Q8_SM60 packing (mtp.cpp): nothing packed on Metal +namespace strata::kernels { bool native_q8_0_sm60_pack_quiet(void const* p0, int p1, int p2, char const* p3) { return false; } } +namespace strata::kernels { bool native_q8_0_sm60_pack_in_place(void* p0, int p1, int p2, char const* p3) { return false; } } +// STRATA_SELECT_LONG (verify.cpp's long-context decode select): CUDA only; never reached on Metal (no scratch asked for) +namespace strata::kernels { long long qsa_topk_multi_scratch_ints(long long p0) { return 0; } } +namespace strata::kernels { void qsa_block_topk_long(float const* p0, int const* p1, long long p2, long long p3, long long p4, strata::kernels::QsaShapes const& p5, int* p6, void* p7, long long p8, int* p9) { strata::metal_engine::missing("strata::kernels::qsa_block_topk_long"); } } +namespace strata::kernels { void qsa_block_scores_long(float const* p0, float const* p1, float const* p2, int const* p3, long long p4, long long p5, strata::kernels::QsaShapes const& p6, float* p7, void* p8, long long p9) { strata::metal_engine::missing("strata::kernels::qsa_block_scores_long"); } } // only reached with pf_wmma (off on Metal) namespace strata::prefill { void swiglu_split_f16(float const* p0, unsigned short* p1, long long p2, int p3, bool p4, void* p5) { } } +// STRATA_PLE_COMPACT (opt-in, CUDA / HIP prompt path): prefill.cpp references it; the Metal prompt runs through its window and never reaches it. +namespace strata::kernels { void ple_iq4nl_dequant(const uint8_t* p0, int64_t p1, float* p2, void* p3) { strata::metal_engine::missing("strata::kernels::ple_iq4nl_dequant"); } } +// STRATA_DEQUANT_SIDE (opt-in, CUDA only): off on Metal; the prompt path takes no second scratch and set_dequant_side(nullptr) keeps the serial form. +namespace strata::prefill { bool gemm_dequant_side() { return false; } } +auto strata::prefill::Gemm::set_dequant_side(uint16_t* p0, std::string& p1) -> bool { if (p0 == nullptr) return true; strata::metal_engine::missing("strata::prefill::Gemm::set_dequant_side"); return false; } diff --git a/packaging/build_dsv41_cuda.sh b/packaging/build_dsv41_cuda.sh index 4ebfd558..9a82b28d 100644 --- a/packaging/build_dsv41_cuda.sh +++ b/packaging/build_dsv41_cuda.sh @@ -3,18 +3,19 @@ # beside `strata` (setup.py dsv41_exe() looks for strata-dsv41 in the engine folder). Same toolchain and RUNPATH rule as the # engine build: the result finds cudart/cublas beside itself ($ORIGIN), never the toolkit it was built with. # -# SRC= B= CUDA=/usr/local/cuda-13.0 GG= [ARCH="86-real;120"] [JOBS=6] packaging/build_dsv41_cuda.sh +# SRC= B= CUDA=/usr/local/cuda-13.0 GG= [ARCH="86-real;89-real;120"] [JOBS=6] packaging/build_dsv41_cuda.sh # -# ARCH defaults to the 0.2.4 release shape: SASS for sm_86 (RTX 3090 / 3060) and sm_120 (RTX Blackwell) + PTX sm_120 (the Windows twin -# built and ran on an RTX 5070; the Linux sm_86 build is the one tested on the RTX 3060 box). Needs CUDA 13 (the sm_120 code); for a -# CUDA 12.9 package pass ARCH="86-real;89-real;89-virtual" or leave strata-dsv41 out (the Pascal cuda12 variant has no DeepSeek path). +# ARCH defaults to the 0.2.7 release shape: SASS for sm_86 (RTX 3090 / 3060), sm_89 (RTX 40, #3935) and sm_120 (RTX Blackwell) + PTX sm_120, i.e. +# the package lists sm_86, sm_89, sm_120, compute_120 (the Windows twin built and ran on an RTX 5070; the Linux sm_86 build is the one tested on the +# RTX 3060 box; sm_89 is built here, not run: the one reporter's own build ran at 40.2 tok/s on an RTX 4090). Needs CUDA 13 (the sm_120 code); +# for a CUDA 12.9 package pass ARCH="86-real;89" (sm_86, sm_89, compute_89) or leave strata-dsv41 out (the Pascal cuda12 variant has no DeepSeek path). # Prints the binary path on the last line; collect its libraries with packaging/collect_libs.py --binary --search $CUDA/lib64. set -eu SRC=${SRC:-$(cd "$(dirname "$0")/.." && pwd)} B=${B:?B=} CUDA=${CUDA:?CUDA=} GG=${GG:?GG=} -ARCH=${ARCH:-86-real;120} +ARCH=${ARCH:-86-real;89-real;120} JOBS=${JOBS:-6} export PATH=$CUDA/bin:$PATH # the build id: the commit, 9 characters. A git checkout gives it to CMake itself; a tarball has no .git, so COMMIT= is required there and goes to BUILD_ID. diff --git a/packaging/build_dsv41_windows.bat b/packaging/build_dsv41_windows.bat index 8fe958e4..8faea651 100644 --- a/packaging/build_dsv41_windows.bat +++ b/packaging/build_dsv41_windows.bat @@ -3,7 +3,7 @@ rem strata-dsv41.exe (the DeepSeek-V4.1 engine) for NVIDIA on Windows, built nex rem beside strata.exe (setup.py dsv41_exe() looks for it in the engine folder). cudart is static; the only extra DLL is cublas64_13.dll, rem which package_engine.py copies from CUDA_PATH like it does for strata.exe. rem build_dsv41_windows.bat [source dir] env: STRATA_GGML_DIR (llama.cpp), CUDA_ROOT (default CUDA 13.0), BUILD_JOBS (default 4), -rem DSV41_ARCH (default "86-real;120" = sm_86 + sm_120 SASS, PTX sm_120) +rem DSV41_ARCH (default "86-real;89-real;120" = sm_86 + sm_89 + sm_120 SASS, PTX sm_120) rem Result: \strata-dsv41.exe (about 66 MB). Windows: only the cuda13 variant gets it (sm_120 needs CUDA 13). setlocal set "BD=%~1" @@ -11,7 +11,7 @@ set "SRCD=%~2" if "%BD%"=="" ( echo usage: build_dsv41_windows.bat ^ [source dir] & exit /b 2 ) if "%SRCD%"=="" set "SRCD=%~dp0.." if "%CUDA_ROOT%"=="" set "CUDA_ROOT=C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v13.0" -if "%DSV41_ARCH%"=="" set "DSV41_ARCH=86-real;120" +if "%DSV41_ARCH%"=="" set "DSV41_ARCH=86-real;89-real;120" if "%BUILD_JOBS%"=="" set "BUILD_JOBS=4" if "%STRATA_GGML_DIR%"=="" ( echo set STRATA_GGML_DIR to the llama.cpp checkout & exit /b 2 ) call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >nul 2>&1 diff --git a/serve/frontend.py b/serve/frontend.py index 0d00ded4..63e319b8 100644 --- a/serve/frontend.py +++ b/serve/frontend.py @@ -546,6 +546,34 @@ def require_messages(messages: list) -> None: raise ValueError("messages must be a non-empty list: send at least one message") +def _order_chat_tool_results(messages: list[dict]) -> None: + """The template pairs results by position, so restore call order while IDs are still available. + + Only a complete, unambiguous run of results is reordered. Legacy or incomplete histories keep their + received order. IDs are private to this conversion and never reach the template. + """ + i = 0 + while i < len(messages): + if messages[i]["role"] != "tool": + i += 1 + continue + j = i + 1 + while j < len(messages) and messages[j]["role"] == "tool": + j += 1 + prev = messages[i - 1] if i else {} + calls = [c.get("_call_id") for c in prev.get("tool_calls") or []] if prev.get("role") == "assistant" else [] + results = [m.get("_call_id") for m in messages[i:j]] + if len(calls) == len(results) and all(isinstance(cid, str) and cid for cid in calls + results): + if len(set(calls)) == len(calls) and len(set(results)) == len(results) and set(calls) == set(results): + rank = {cid: n for n, cid in enumerate(calls)} + messages[i:j] = sorted(messages[i:j], key=lambda m: rank[m["_call_id"]]) + i = j + for message in messages: + message.pop("_call_id", None) + for call in message.get("tool_calls") or []: + call.pop("_call_id", None) + + def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: """OpenAI Chat Completions -> (template messages, template tools, template kwargs).""" messages = [] @@ -558,6 +586,8 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: content = _check_parts(m.get("content"), f"messages[{i}].content", TEXT_PARTS + IMAGE_PARTS if images else TEXT_PARTS) out = {"role": role, "content": _parts_of(content) if images else _text_of(content)} + if role == "tool": + out["_call_id"] = m.get("tool_call_id") if m.get("reasoning_content"): out["reasoning_content"] = m["reasoning_content"] if m.get("tool_calls"): @@ -566,9 +596,11 @@ def openai_to_messages(req: dict) -> tuple[list[dict], list[dict] | None, dict]: fn = c.get("function", c) if not isinstance(fn, dict): raise ValueError("tool_calls must be a list of objects (each with a \"function\" object)") - calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}}) + calls.append({"function": {"name": fn.get("name"), "arguments": tool_arguments(fn.get("arguments"))}, + "_call_id": c.get("id")}) out["tool_calls"] = calls messages.append(out) + _order_chat_tool_results(messages) tools = [t.get("function", t) if t.get("type") == "function" else t for t in _tool_list(req.get("tools"), "function")] or None kwargs = {} @@ -935,6 +967,12 @@ class OutputParser: for alias in (f"{namespace}__{member}", f"{namespace}={member}", f"{namespace}_{member}", member): aliases.setdefault(alias, set()).add(name) + # #3796: the same tool written with every `__` collapsed to `_` (`mcp__playwright__browser_navigate` as + # `mcp_playwright_browser_navigate`, the way Qwen often flattens a name) is that tool. Only a spelling of a declared + # name: a reordered or renamed tool (`server1_label_values` for `label_values_mcp_server1`) is not guessed. + for name in self.schemas: + if isinstance(name, str) and "__" in name: + aliases.setdefault(name.replace("__", "_"), set()).add(name) self.aliases = {alias: next(iter(names)) for alias, names in aliases.items() if len(names) == 1 and alias not in self.schemas} self.unread = 0 # #3441: `` blocks that opened like a call and were returned as text diff --git a/serve/mcp.py b/serve/mcp.py index 116251af..326249ec 100644 --- a/serve/mcp.py +++ b/serve/mcp.py @@ -19,6 +19,9 @@ breaking. from __future__ import annotations import collections +import base64 +import hashlib +from pathlib import Path import json import os import re @@ -34,7 +37,7 @@ import urllib.request from serve import lifeline PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given -DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0} +DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0, "image_results": False} class McpError(RuntimeError): @@ -486,6 +489,42 @@ def result_text(result: dict) -> str: return "\n".join(parts) +def cache_images(result, directory): + """Keep raster tool outputs outside chat history; never expose arbitrary tool paths.""" + images = [] + directory = Path(directory) + types = {"image/png": ("png", b"\x89PNG\r\n\x1a\n"), "image/jpeg": ("jpg", b"\xff\xd8\xff"), + "image/webp": ("webp", b"RIFF")} + for block in result.get("content") or []: + if not isinstance(block, dict): + continue + mime = block.get("mimeType") + if block.get("type") != "image" or mime not in types or len(images) >= 4: + continue + encoded = block.get("data") + if not isinstance(encoded, str) or len(encoded) > 24_000_000: + continue + try: + data = base64.b64decode(encoded, validate=True) + except (ValueError, TypeError): + continue + ext, magic = types[mime] + if not data.startswith(magic) or (ext == "webp" and data[8:12] != b"WEBP"): + continue + directory.mkdir(parents=True, exist_ok=True) + name = hashlib.sha256(data).hexdigest() + "." + ext + target = directory / name + if not target.exists(): + temporary = directory / (name + "." + os.urandom(8).hex() + ".tmp") + try: + temporary.write_bytes(data) + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + images.append({"url": "tool-media/" + name, "mimeType": mime, "name": "tool-image." + ext}) + return images + + def _clean(name: str) -> str: return re.sub(r"[^A-Za-z0-9_-]", "_", str(name)) or "x" @@ -494,6 +533,7 @@ class McpHub: """Every configured server, and the merged, namespaced tool list the model sees.""" def __init__(self, servers: dict[str, dict], settings: dict | None = None): + self.media_dir = None self.settings = {**DEFAULTS, **(settings or {})} self.servers = {name: McpServer(name, cfg, self.settings) for name, cfg in servers.items()} self.threads: list[threading.Thread] = [] @@ -560,6 +600,14 @@ class McpHub: res = server.call(tool, arguments if isinstance(arguments, dict) else {}, float(self.settings["timeout_s"]), cancel) text, ok = result_text(res), not res.get("isError") + if ok and self.settings["image_results"] and self.media_dir is not None: + try: + images = cache_images(res, self.media_dir) + except OSError as e: + print(f"[strata] MCP image cache unavailable: {e}", file=sys.stderr, flush=True) + else: + if images: + out["images"] = images if not ok: text = "error: " + (text or "the tool reported an error") except McpCancelled: @@ -571,6 +619,10 @@ class McpHub: if cap > 0 and full > cap: text = text[:cap] + (f"\n\n[... truncated: the tool returned {full:,} characters; only the first " f"{cap:,} are shown]") + if ok and out.get("images"): + out["model_content"] = [{"type": "text", "text": text.replace(": not shown to the model]", ": image attached]")}] + [ + {"type": "image", "source": str(Path(self.media_dir) / im["url"].split("/")[-1])} + for im in out["images"]] out.update(ok=ok, text=text, chars=full, truncated=cap > 0 and full > cap, ms=int((time.monotonic() - t0) * 1000)) return out @@ -627,11 +679,15 @@ def servers_from(block, where: str) -> dict[str, dict]: def settings_from(cfg: dict) -> dict: - """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s.""" + """The run config's optional `"mcp"` block: timeout_s, max_result_chars, max_rounds, start_timeout_s, image_results.""" out = {} for key, value in (cfg.get("mcp") or {}).items(): number = isinstance(value, (int, float)) and not isinstance(value, bool) - if key in ("timeout_s", "start_timeout_s"): + if key == "image_results": + if not isinstance(value, bool): + raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a boolean") + out[key] = value + elif key in ("timeout_s", "start_timeout_s"): if not number or value <= 0: raise SystemExit(f"[strata] config mcp.{key}={value!r}: expected a number of seconds > 0") out[key] = float(value) diff --git a/serve/responses.py b/serve/responses.py index 8b7241b9..d5ea4cd0 100644 --- a/serve/responses.py +++ b/serve/responses.py @@ -420,11 +420,12 @@ def text_format(req: dict): kind = fmt.get("type") if kind in (None, "text"): return None + extra = {"repair_latex_escapes": True} if fmt.get("repair_latex_escapes") is True else {} # #2893, opt-in if kind == "json_object": - return {"type": "json_object"} + return {"type": "json_object", **extra} if kind == "json_schema": spec = {k: fmt[k] for k in ("name", "schema", "strict", "description") if k in fmt} - return {"type": "json_schema", "json_schema": spec} + return {"type": "json_schema", "json_schema": spec, **extra} raise ResponsesError("text.format.type must be text, json_object or json_schema", "text.format.type") @@ -443,8 +444,10 @@ def check_request(req: dict) -> None: raise ResponsesError("stored prompt templates are not supported: send instructions and input", "prompt", "unsupported_parameter") n = req.get("max_output_tokens") - if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < 1): - raise ResponsesError("max_output_tokens must be a positive whole number", "max_output_tokens") + # -1 and 0 mean no cap, as max_tokens does on the chat path (docs/DETAILS.md); anything lower is a mistake + if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n < -1): + raise ResponsesError("max_output_tokens must be a whole number, 1 or more, or -1 or 0 for no cap", + "max_output_tokens") reasoning = req.get("reasoning") if reasoning is not None and not isinstance(reasoning, dict): raise ResponsesError("reasoning must be an object", "reasoning") @@ -662,10 +665,17 @@ class Assembler: if length: self.response["status"] = "incomplete" self.response["incomplete_details"] = {"reason": "max_output_tokens"} - return out + [self.event("response.incomplete", response=self.snapshot())] + return out + [self._with_timings(self.event("response.incomplete", response=self.snapshot()), done)] self.response["status"] = "completed" self.response["completed_at"] = int(time.time()) - return out + [self.event("response.completed", response=self.snapshot())] + return out + [self._with_timings(self.event("response.completed", response=self.snapshot()), done)] + + @staticmethod + def _with_timings(event: dict, done: dict) -> dict: + """Top-level `timings` on the final event, as /v1/chat/completions has them (#107).""" + if done.get("timings"): + event["timings"] = done["timings"] + return event def failed(self, message: str, code: str = "server_error") -> dict: """response.failed: an error after the stream started (the HTTP status is already sent).""" @@ -683,4 +693,6 @@ def collect(events) -> dict: for e in events: if e is not None: last = e + if last.get("timings"): # as on a whole /v1/chat/completions reply (#107) + return {**last["response"], "timings": last["timings"]} return last["response"] diff --git a/serve/server.py b/serve/server.py index 76b5a2c7..41cb81f6 100644 --- a/serve/server.py +++ b/serve/server.py @@ -65,6 +65,7 @@ from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthro tool_choice_of, unmark_think_literals) from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 +from serve.webfiles import subtree_file as web_subtree_file # noqa: E402 from strata_control import engine_component # noqa: E402 from strata_control import tls # noqa: E402 @@ -80,7 +81,7 @@ from serve import owner_guard # noqa: E402 from serve import launch_identity # noqa: E402 from serve import logit_bias as bias_api # noqa: E402 from serve import lifeline # noqa: E402 -from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 +from serve.structured import StructuredOutputError, prepare_format, validated_json, extract_json # noqa: E402 from serve import responses as responses_api # noqa: E402 from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 from serve import images as images_api # noqa: E402 @@ -448,6 +449,11 @@ class GpuBusy(RuntimeError): self.retry_after = retry_after +# The page's only CSP directive: its preview frames (srcdoc) may not load any address. Other directives are left out +# on purpose: a frame made from srcdoc inherits the page's policy, and the opt-in "run scripts" preview needs its own inline script. +PAGE_CSP = "frame-src 'none'" + + def unload_wait(value, default: float) -> float: """#1997: the `wait` of POST /unload?wait=...: absent / 0 / false: 0 (answer "busy" at once, as before); 1 / true / yes: `default` seconds; a number of seconds above 1: that long (at most an hour).""" @@ -1456,6 +1462,15 @@ class StrataEngine: pn = prefix.get("tokens") if isinstance(pn, int) and not isinstance(pn, bool) and pn > 0: keys += f" pin={pn}" + # logprobs: the engine writes an `LP` line after each `T` line (an engine without them ignores + # the key, so an older engine answers exactly as it did). Absent = no LP lines at all. + k = top_logprobs(sampling) + if k is not None: + keys += f" logprobs={k}" + ids = allowed_ids(sampling) + if ids: + # only these ids are printed; the engine's comma-separated list, renormalised below + keys += " allowed=" + ",".join(str(i) for i in ids) return keys + StrataEngine.projection_key(sampling) + bias_api.engine_key(sampling.get("logit_bias")) @staticmethod @@ -1474,35 +1489,56 @@ class StrataEngine: except (OSError, AttributeError): # the pipe is gone (or a restart's close() took the process): raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") from None - def _control(self, cancel, on_token, stop_when=None, on_quiet=None): + def _control(self, cancel, on_token, stop_when=None, on_quiet=None, want_lp=False): """Reads the control lines of the request on them (GEN / BGEN), yielding None heartbeats. Calls on_token(id) for each `T`; returns ("done", None) at DONE, or ("badm", continues) at BADM (after DONE). `stop_when()` true sends STOP once (the request is then read to its DONE). `on_quiet()` runs whenever the engine has been - quiet for half a second: between two PP lines of a read whose chunks take longer than that.""" + quiet for half a second: between two PP lines of a read whose chunks take longer than that. + + `want_lp`: a batch admission's token is the only one this reader ever sees with an `LP` line after it (a + slot's `BT` lines carry none), so a request asking for logprobs there is a `max_tokens` 1 one: read the + line here, for the request itself (its own lines: the engine's is shared by the slots' readers).""" stopped = False beat = time.monotonic() + held = NO_LINE # a line read while looking for a token's LP line while True: - try: - # A client can leave before the first PP/token. Poll its Event as often as _take_control does; - # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. - line = self.lines.get(timeout=0.5) - except queue.Empty: - if cancel.is_set() and not stopped: - self._send("STOP") - stopped = True - if on_quiet is not None: - on_quiet() - if time.monotonic() - beat >= 10.0: - beat = time.monotonic() - yield None - continue + if held is not NO_LINE: + line, held = held, NO_LINE + else: + try: + # A client can leave before the first PP/token. Poll its Event as often as _take_control does; + # the ten-second HTTP heartbeat is independent of how promptly STOP reaches the engine. + line = self.lines.get(timeout=0.5) + except queue.Empty: + if cancel.is_set() and not stopped: + self._send("STOP") + stopped = True + if on_quiet is not None: + on_quiet() + if time.monotonic() - beat >= 10.0: + beat = time.monotonic() + yield None + continue beat = time.monotonic() if line is None: raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})") if not line.startswith(("PP ", "INFO")): btrace("ctl<", self._ctl_mode, line.strip()[:60]) if line.startswith("T "): - on_token(int(line[2:])) + t = int(line[2:]) + if want_lp: + # the engine writes the token and its LP line in one flush: the next line is that one, or a + # line this reader must still see (held for the next turn, as generate() does) + try: + held = self.lines.get(timeout=0.5) + except queue.Empty: + held = NO_LINE + if isinstance(held, str) and held.startswith("LP "): + own = getattr(cancel, "_strata_lp_lines", None) + if own is not None: + own.append((t, held)) + held = NO_LINE + on_token(t) if not stopped and (cancel.is_set() or (stop_when is not None and stop_when())): self._send("STOP") stopped = True @@ -1779,6 +1815,12 @@ class StrataEngine: self.progress, self.progress_ms, self.reused = None, 0, 0 born = self.gen # the engine process this request is sent to keys = self.sampling_keys(sampling or {}) + # logprobs: only an admission's token can have an LP line here (the slot's "BT" lines carry none), so the + # server refuses these requests unless max_tokens is 1. The lines go to the request itself, through its + # cancel Event: several requests read control lines at once, and the engine's lp_lines is one attribute. + want_lp = top_logprobs(sampling or {}) is not None + if want_lp: + cancel._strata_lp_lines = LPLines(cancel) out: list[int] = [] pending: list[int] = [] prompt, left = list(ids), int(max_new) @@ -1833,7 +1875,8 @@ class StrataEngine: self.slot_claims.add(reserved) if reserved is not None: self._send(f"BYIELD {reserved}") - for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way): + for x in self._control(cancel, pending.append, stop_when=others, on_quiet=give_way, + want_lp=want_lp): while pending: t = pending.pop(0) out.append(t) @@ -1961,7 +2004,8 @@ class StrataEngine: if self.progress and live["state"] == "reading": live["prompt_read"] = self.progress[0] try: - for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress())): + for x in self._control(cancel, pending.append, on_quiet=lambda: (ask(), note_progress()), + want_lp=want_lp): while pending: t = pending.pop(0) out.append(t) @@ -2195,6 +2239,12 @@ class StrataEngine: return self.progress, self.progress_ms, self.reused = None, 0, 0 self.prefill_tok_s_mean = None + # logprobs: the engine writes "LP [id:logprob ...]" right after each "T " (the same + # flush), read here before the token is yielded, so whoever takes the token finds its line in + # lp_lines. Not asked for = the deque stays empty and nothing on this path changes. + want_lp = top_logprobs(sampling or {}) is not None + self.lp_lines = LPLines(cancel) + carry = NO_LINE # a line read for a token's LP line, held until it is used # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" @@ -2222,7 +2272,10 @@ class StrataEngine: raise self._silent(f"the engine said nothing for {time.monotonic() - heard:.0f} s during " "the request") try: - line = self.lines.get(timeout=min(wait, 0.5)) + if carry is not NO_LINE: # the line read after a token for its LP line + line, carry = carry, NO_LINE + else: + line = self.lines.get(timeout=min(wait, 0.5)) except queue.Empty: if cancel.is_set(): return @@ -2249,7 +2302,18 @@ class StrataEngine: allow = silence if cancel.is_set(): return - yield int(line[2:]) + t = int(line[2:]) + if want_lp: + # the engine writes the token and its `LP` line in one flush, so the line is + # here now; an engine without logprobs leaves the next line a normal one + try: + carry = self.lines.get(timeout=0.5) + except queue.Empty: + carry = NO_LINE + if isinstance(carry, str) and carry.startswith("LP "): + self.lp_lines.append((t, carry)) + carry = NO_LINE + yield t elif line.startswith("PP "): f = line.split() if len(f) >= 3 and f[1].isdigit() and f[2].isdigit(): @@ -2292,9 +2356,12 @@ class StrataEngine: while True: left = allow - (time.monotonic() - heard) if allow > 0 else None try: - if left is not None and left <= 0: + if carry is not NO_LINE: # read already, after the last token + line, carry = carry, NO_LINE + elif left is not None and left <= 0: raise queue.Empty - line = self.lines.get(timeout=left) + else: + line = self.lines.get(timeout=left) except queue.Empty: raise self._silent("the engine did not finish the request after it was stopped (STOP) " f"within {allow:.0f} s") from None @@ -3531,6 +3598,9 @@ def child_env(cfg: dict, *, offline: bool = False) -> dict: env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else [])) if cfg.get("backend") == "hip": hip_env_guard(env, cfg) + note = sh_stream_warning(env, cfg) + if note: + print(note, flush=True) auto = hip_auto_devices(cfg, env) if auto: env["HIP_VISIBLE_DEVICES"] = ",".join(str(i) for i in auto) @@ -3545,6 +3615,20 @@ def _dir_writable(p: str) -> bool: return False +def sh_stream_warning(env: dict, cfg: dict) -> str | None: + """#3895: the shared-expert fork (STRATA_SH_STREAM=1) together with KV streaming (--kv-resident) made one Windows RX 6900 XT fail on the first + request ("verify: unspecified launch failure"); each alone, or Linux, did not. A warning, not a refusal: the person set the variable, the + engine runs as asked, and the line says what to take out.""" + if os.name != "nt" or str(env.get("STRATA_SH_STREAM", "")).strip() in ("", "0"): + return None + args = [str(a) for a in cfg.get("args") or []] + if "--kv-resident" not in args: + return None + return ("[strata] WARNING: STRATA_SH_STREAM=1 with --kv-resident (KV streaming) failed on the first request on one Windows RX 6000 PC " + "(\"verify: unspecified launch failure\", #3895). If the engine stops that way, take STRATA_SH_STREAM out of the config's env " + "(AMD runs without it by default) or run without --kv-resident, and tell us the card and the driver.") + + def hip_env_guard(env: dict, cfg: dict) -> list[str]: """#654: two things in an AMD user's environment that crash the HIP runtime before it prints a line. (1) HIP_PATH, HIP_DEVICE_LIB_PATH or LLVM_PATH naming a folder that is gone (a ROCm build that was deleted): the bundled runtime @@ -3720,6 +3804,40 @@ class Detokenizer: OPENAI_MAX_STOP = 4 # OpenAI's limit on `stop` +def top_logprobs(req: dict): + """The K for the engine's logprobs=K, or None when the request did not ask. + + OpenAI: "logprobs": true with "top_logprobs" 0..20; the legacy completions form, + "logprobs": N, is taken as N.""" + lp = req.get("logprobs") + if lp is True: + k = req.get("top_logprobs") + return max(0, min(20, k)) if isinstance(k, int) and not isinstance(k, bool) else 0 + if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 0: + return min(20, lp) + return None + + +def allowed_ids(req: dict) -> list: + """`allowed_token_ids`: the ids a caller named, or [] (vLLM's semantics, see LogprobEntries).""" + ids = req.get("allowed_token_ids") + if not isinstance(ids, (list, tuple)): + return [] + return [x for x in ids if isinstance(x, int) and not isinstance(x, bool) and x >= 0] + + +def batch_slots_on(engine) -> bool: + """Does this engine run requests in batch slots ("parallel", whose `BT` lines carry no LP lines)? + + Asked of each engine behind a ReplicaEngine: its own `batch` is how many requests it can run at once, so it + counts a replica without slots as one (serve/replicas.py) -- a server with `--replicas 2` and no `--parallel` + has none, and reads every reply by the GEN path, which does write them.""" + return any(int(getattr(e, "batch", 0) or 0) for e in (getattr(engine, "engines", None) or [engine])) + + +NO_LINE = object() # StrataEngine.generate: no line held after a token + + def stop_strings(req: dict) -> list[str]: """The request's stop strings: OpenAI's `stop` (a string or a list of up to 4) or Anthropic's `stop_sequences` (a list). Empty strings are left out. A bad value is a ValueError, so a 400 before anything is generated.""" @@ -4202,7 +4320,10 @@ class Service: if self.vision_held: time.sleep(0.2) # the driver's free-VRAM counter shows the cache's release a moment later free0, t0 = self.free_vram_mib(), time.time() - v.restart() + try: + v.restart() + except Exception as e: # a 503 as for a non-elastic encoder at a load, not a dropped connection + raise EngineDied(f"the image encoder failed to start: {e}") from e free1 = self.free_vram_mib() took = f", {free0 - free1} MiB of VRAM" if free0 is not None and free1 is not None else "" print(f"[strata] images: the image encoder started in {time.time() - t0:.1f} s{took}", flush=True) @@ -4220,11 +4341,14 @@ class Service: return "busy" try: v.unload() + back = "" if self.vision_held and hasattr(self.engine, "vram") and self.loaded(): out = self.engine.vram(self._engine_reserve()) - print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture; " - f"the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " - f"{out.get('expert_cache_full_mib')} MiB)", flush=True) + back = (f"; the expert cache took its VRAM back ({out.get('expert_cache_mib')} of " + f"{out.get('expert_cache_full_mib')} MiB)") + # also when the cache never made room (a layer split, an engine without --vram-elastic): the stop happened + print(f"[strata] images: the image encoder stopped after {v.elastic_idle_s:g} s without a picture{back}", + flush=True) self.vision_held = False return "down" finally: @@ -4680,6 +4804,8 @@ class Service: ("strata:requests_total", "counter", "Requests finished", t["requests"]), ("strata:drafts_offered_total", "counter", "Speculative draft tokens offered", t["drafts_offered"]), ("strata:drafts_accepted_total", "counter", "Speculative draft tokens accepted", t["drafts_accepted"]), + ("strata:tool_calls_unread_total", "counter", " blocks returned as text (an undeclared name or a form the template does not use)", + t.get("tool_calls_unread", 0)), ("strata:model_loaded", "gauge", "1 while the model is loaded", int(self.loaded())), ] return "".join(f"# HELP {name} {help_}\n# TYPE {name} {kind}\n{name} {value}\n" @@ -4824,6 +4950,24 @@ class Service: prompt; with thinking, Service.run writes it once the thinking is over.""" # `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop # between pictures and raise ClientGone + # Cached tool images are references in browser history, never arbitrary file paths or huge base64 strings. + for message in messages: + for part in message.get("content", []) if isinstance(message.get("content"), list) else []: + source = part.get("source", "") if isinstance(part, dict) else "" + if isinstance(part, dict) and part.get("type") == "image" and isinstance(source, str) and source.startswith("strata-tool-media:"): + name = source[len("strata-tool-media:"):] + if not re.fullmatch(r"[0-9a-f]{64}\.(png|jpg|webp)", name): + raise ValueError("invalid tool image reference") + # Clients resend old tool results. A removed cache or disabled feature must not poison + # every later turn; keep the other text and replace only the unavailable picture. + media_dir = self.mcp.media_dir if self.mcp is not None else None + image = Path(media_dir) / name if media_dir is not None else None + if image is None or not image.is_file(): + why = "tool image cache is disabled" if image is None else "cached tool image is no longer available" + part.clear() + part.update(type="text", text=f"[image omitted: {why}]") + else: + part["source"] = str(image) fetched = self._note_unreadable_tool_images(messages, cancel) ids = encoded_ids = self.encode_prompt(messages, tools, kwargs) if force and kwargs.get("enable_thinking", True) is False: @@ -5596,11 +5740,17 @@ class Service: self.totals["tool_calls_from_reasoning"] = self.totals.get("tool_calls_from_reasoning", 0) + parser.rescued print(f"[strata] tool calls inside the thinking: {parser.rescued} read as calls, {parser.refused} kept as " f"reasoning (quoted, or the turn did not end on a stop)", flush=True) + rejected = [] if parser.unread: named = getattr(parser, "unread_names", None) print(f"[strata] {parser.unread} block(s) in the answer did not read as a call of a declared " "tool and went back as text (a name the request did not declare, or a form the template does " - "not use)" + (f"; the names the model wrote: {', '.join(named)}" if named else ""), flush=True) + "not use)" + (f"; the names the model wrote: {', '.join(named)}" if named else "") + + "; the response carries them as strata_rejected_tool_calls, /metrics counts them", flush=True) + with self.status_lock: + self.totals["tool_calls_unread"] = self.totals.get("tool_calls_unread", 0) + parser.unread + # #3796: the same names for the client (a machine-readable marker next to the text, which stays as the model wrote it) + rejected = [{"name": nm, "reason": "undeclared"} for nm in named or []] if stops is not None and stops.hit is None and stops.held: yield "event", Event("content", stops.flush()) # the held tail was not a stop string after all done = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0), @@ -5608,6 +5758,8 @@ class Service: "reasoning_recoveries": recovery_count} if stops is not None and stops.hit is not None: done["stop_sequence"] = stops.hit + if rejected: + done["rejected_tool_calls"] = rejected yield "done", done @@ -5719,13 +5871,15 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, """Service.run with the MCP tools executed here: the model writes a call to an MCP tool, the server runs it, adds the call and its result to the conversation and lets the model continue - up to `max_rounds` times. Yields what Service.run yields (text, thinking, the request's own tool calls) plus ("mcp", {...}) for the tool activity, and - one ("done", ...) at the very end with the output tokens of every round. + one ("done", ...) at the very end with the output tokens of every round. After the last tool round, one final + reply uses the results already obtained, with no tools offered or executed. `mcp_names`: the MCP tools this request offered; any other call is one of the request's own tools and ends the turn as always (the client answers it). MCP calls written in the same answer are then not run (their results could not reach the model before the client's).""" max_rounds = int(hub.settings["max_rounds"]) total, rounds, done = 0, 0, None + finalizing = False messages = list(messages) while True: text, reasoning, calls, own_calls = [], [], [], 0 @@ -5749,10 +5903,7 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, reasoning.append(ev.text) yield kind, x total += done["completion_tokens"] - run_them = calls and not own_calls and done["finish"] == "stop" and not cancel.is_set() - if run_them and rounds >= max_rounds: - yield "mcp", {"event": "limit", "max_rounds": max_rounds} - run_them = False + run_them = calls and not own_calls and not finalizing and done["finish"] == "stop" and not cancel.is_set() if not run_them: for c in calls: # announced, never run: close them in the client's view yield "mcp", {"event": "result", "id": c.id, "ok": False, "skipped": True, "text": "not run", @@ -5788,8 +5939,10 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, r = box["r"] print(f"[strata] tool {c.name}: {'ok' if r['ok'] else 'error'}, {r['chars']:,} characters in " f"{r['ms'] / 1000:.1f} s{' (truncated for the model)' if r['truncated'] else ''}", flush=True) - results.append(r["text"]) - yield "mcp", {"event": "result", "id": c.id, **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}} + results.append(r.get("model_content", r["text"]) if svc.vision is not None else r["text"]) + yield "mcp", {"event": "result", "id": c.id, + **({"images": r["images"], "vision": svc.vision is not None} if r.get("images") else {}), + **{k: r[k] for k in ("ok", "text", "chars", "truncated", "ms")}} if cancel.is_set() or len(results) < len(calls): done = {**done, "finish": "cancel"} break @@ -5797,6 +5950,16 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, **({"reasoning_content": "".join(reasoning).strip()} if reasoning else {}), "tool_calls": [{"function": {"name": c.name, "arguments": c.arguments}} for c in calls]}) messages += [{"role": "tool", "content": r} for r in results] + if rounds >= max_rounds: + finalizing = True + tools = None + system_end = next((index for index, message in enumerate(messages) + if message.get("role") not in ("system", "developer")), len(messages)) + messages.insert(system_end, {"role": "system", "content": + f"The tool-use limit of {max_rounds} rounds has been reached. No tools are available for this final " + "reply. Answer the user's original request in their language using the results already obtained. " + "Explain any gaps in the available evidence. Do not request or emit further tool calls."}) + yield "mcp", {"event": "limit", "max_rounds": max_rounds} try: ids, thinking, max_new = svc.prepare(messages, tools, kw, max_req, cancel=cancel) except ClientGone: # #1999: the client left while a picture was prepared @@ -5814,6 +5977,141 @@ def run_with_mcp(svc: Service, hub, messages, tools, kw, ids, thinking, max_new, PP_DONE_TAIL = 64 + +class LPLines(collections.deque): + """One request's LP lines, tagged with its cancel Event (one per request, handed unchanged from the handler + through Service.run to Engine.generate). The last events of a request - the parser's and the stop strings' + tail - come after it has left the queue, when the next request may already have replaced the engine's lp_lines + with its own: LogprobEntries reads only the lines tagged with its own request's Event.""" + + def __init__(self, owner=None): + super().__init__() + self.owner = owner + + +class LogprobEntries: + """The engine's LP lines as OpenAI's logprobs.content entries. + + Each token's "token" is the text it completes (an incremental UTF-8 decode, as the reply's + text is made), so a character split across tokens lands in the token that finishes it and + the tokens, joined, spell the reply. "bytes" are the token's own bytes. The stop token + ends the reply and is not listed (OpenAI does not list it either). Tokens that make no + text of the reply are left out, because spell() gives each piece of text the tokens that + spell it. + + `allowed_token_ids`: only those ids are kept, and the logprobs are renormalised over them, + so a caller asking about specific candidates gets a distribution over exactly those instead + of a top-K list it has to hope contains them. vLLM, which named the field, masks generation + with these ids instead (every other logit -inf before sampling) and reports the unmasked + distribution; here they filter what is reported, so the chosen token can be outside them. + + On `--parallel`: only a `max_tokens` 1 request gets entries (an admission, decoded through the single-token path + that writes an LP line); the slot's `BT` lines carry none, so a longer reply is refused (400) before it starts. + """ + + def __init__(self, svc, allowed=(), owner=None): + self.tok, self.stop_ids = svc.tok, svc.stop_ids + self.allowed = [i for i in allowed] + self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") + self.pending = [] # entries read but not yet given to a piece of text + self.owner = owner # the request's cancel Event (LPLines) + self.lines = None # this request's current LPLines, kept once seen + + def spell(self, eng, text: str) -> list: + """The entries whose tokens spell `text`, the next piece of the reply.""" + self.pending += self.take(eng) + at = [0] + for e in self.pending: + at.append(at[-1] + len(e["token"])) + joined = "".join(e["token"] for e in self.pending) + i = joined.find(text) + while i >= 0 and text: + if i in at: + a = at.index(i) # the first token there + end = i + len(text) + b = next((j for j in range(a + 1, len(at)) if at[j] == end), None) + if b is not None: + out, self.pending = self.pending[a:b], self.pending[b:] + return out + i = joined.find(text, i + 1) + out, self.pending = self.pending, [] + return out + + def raw(self, t): + if hasattr(self.tok, "token_bytes"): + return self.tok.token_bytes(t) + return self.tok.decode([t]).encode("utf-8") + + def take(self, eng) -> list: + # the engine's current lines are this request's only when they carry its Event (a later generate pass + # of the same request makes new ones: the old ones are read to the end first); another request's never are. + # A batch admission keeps its own lines on the request's cancel Event: the engine's is one attribute, and + # the next request to read control lines may already have replaced it. + own = getattr(self.owner, "_strata_lp_lines", None) + cur, old = (own if own is not None else getattr(eng, "lp_lines", None)), None + if cur is not self.lines and getattr(cur, "owner", None) is self.owner: + old, self.lines = self.lines, cur + out = [] + for lines in (old, self.lines): + while lines: + t, line = lines.popleft() + if t in self.stop_ids: + continue + f = line.split() + if len(f) < 2: + continue + try: # "nan" (no head logits for that window row), "-nan(ind)" + lp = float(f[1]) # (MSVC) or a cut line: no entry for that token + alts = [(int(i), float(v)) for i, _, v in (x.partition(":") for x in f[2:])] + except ValueError: + continue + if not math.isfinite(lp) or not all(math.isfinite(v) for _, v in alts): + continue + b = self.raw(t) + e = {"token": self.inc.decode(b), "logprob": lp, "bytes": list(b), + "top_logprobs": []} + if self.allowed: + alts = [(i, v) for i, v in alts if i in self.allowed] + for i, v in alts: + alt = self.raw(i) + e["top_logprobs"].append({"token": alt.decode("utf-8", "replace"), + "logprob": v, "bytes": list(alt)}) + if self.allowed: + e = self._renormalise(e, t, lp) + out.append(e) + return out + + def _renormalise(self, e, t, lp): + """Keep only the named ids and normalise over them, so they sum to 1. + + The line carries the chosen token's own logprob on its head and the named ids after it, and never + repeats the chosen one among them. So the chosen token is put back when the caller named it: with + `allowed_token_ids` naming only the token the model chose, that token is then the whole distribution, + at 1 (logprob 0), which is what vLLM's mask gives -- here it used to leave nothing to normalise over, + which returned None, the entry was appended all the same, and the reply failed on e["token"]. A line + that carries none of the named ids has nothing to normalise over either: the entry keeps the chosen + token and its own logprob, with no alternatives. It is never None and never dropped, because the + reply's tokens have to keep spelling its text. + """ + cand = e["top_logprobs"] + own = None + if t in self.allowed: # named, and not repeated on the line: it is a candidate + b = self.raw(t) + own = {"token": b.decode("utf-8", "replace"), "logprob": lp, "bytes": list(b)} + cand = [own] + cand + if not cand: + return e # no named id observed for this token: its own logprob, no top + mx = max(x["logprob"] for x in cand) + se = sum(math.exp(x["logprob"] - mx) for x in cand) + lse = mx + math.log(se) + for x in cand: + x["logprob"] -= lse + cand.sort(key=lambda x: -x["logprob"]) # most likely first, as the unfiltered top-k already is + e["top_logprobs"] = cand + if own is not None: # the chosen token is in the distribution: report its own value + e["logprob"] = own["logprob"] # (it used to copy the first alternative's, another token's) + return e + def prompt_progress(svc: Service): """The last PP line as llama.cpp's `prompt_progress`, so a client written for llama.cpp reads both servers: the same four fields, `time_ms` elapsed since prompt reading started, and `processed` counting from token 0 so that a @@ -5847,6 +6145,13 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} yield chunk({"role": "assistant", "content": ""}) + lp = LogprobEntries(svc, allowed_ids(req), cancel) if top_logprobs(req) is not None else None + + def with_lp(c, key): + got = lp.spell(svc.engine, c["choices"][0]["delta"][key]) if lp is not None else None + if got: + c["choices"][0]["logprobs"] = {key: got} + return c calls = 0 streamed = {} # tool call id -> index, for calls sent piece by piece finished = set() # ... and the ones whose final tool_call came (#211) @@ -5863,9 +6168,9 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel elif kind == "event": ev: Event = x if ev.kind == "reasoning" and ev.text: - yield chunk({"reasoning_content": ev.text}) + yield with_lp(chunk({"reasoning_content": ev.text}), "reasoning_content") elif ev.kind == "content" and ev.text: - yield chunk({"content": ev.text}) + yield with_lp(chunk({"content": ev.text}), "content") elif ev.kind == "tool_start": streamed[ev.call.id] = calls calls += 1 @@ -5892,6 +6197,8 @@ def openai_chunks(svc: Service, req: dict, ids, thinking, tools, max_new, cancel "prompt_tokens_details": {"cached_tokens": x.get("reused") or 0}} if x.get("timings"): last["timings"] = x["timings"] # llama.cpp's field: the speed its clients show + if x.get("rejected_tool_calls"): + last["strata_rejected_tool_calls"] = x["rejected_tool_calls"] # #3796: only when a call was refused as undeclared yield last @@ -5905,11 +6212,14 @@ def _is_json(text: str) -> bool: def openai_collect(chunks) -> dict: content, reasoning, by_index, last, mcp = [], [], {}, None, [] + lps = {} # "content" / "reasoning_content" -> logprob entries for c in chunks: if c is None: # a heartbeat continue if c.get("strata_mcp"): mcp.append(c["strata_mcp"]) + for k, v in (c["choices"][0].get("logprobs") or {}).items(): + lps.setdefault(k, []).extend(v) d = c["choices"][0]["delta"] content.append(d.get("content") or "") reasoning.append(d.get("reasoning_content") or "") @@ -5936,8 +6246,79 @@ def openai_collect(chunks) -> dict: out = {"id": last["id"], "object": "chat.completion", "created": last["created"], "model": last["model"], "choices": [{"index": 0, "message": msg, "finish_reason": last["choices"][0]["finish_reason"]}], "usage": last["usage"]} + if lps: + out["choices"][0]["logprobs"] = {"content": lps.get("content", []), "refusal": None, **( + {"reasoning_content": lps["reasoning_content"]} if lps.get("reasoning_content") else {})} if last.get("timings"): out["timings"] = last["timings"] + if last.get("strata_rejected_tool_calls"): + out["strata_rejected_tool_calls"] = last["strata_rejected_tool_calls"] + return out + + +def logprob_span(text: str, part: str, entries: list): + """The entries whose tokens spell `part`, a piece of `text`, or None when the tokens do not + spell `text` or no token boundary falls at both ends of `part`.""" + if "".join(e["token"] for e in entries) != text: + return None + start = text.find(part) + if start < 0: + return None + at, first = 0, None + for i, e in enumerate(entries): + if at == start and first is None: + first = i + if at == start + len(part) and first is not None: + return entries[first:i] + at += len(e["token"]) + return entries[first:] if first is not None and at == start + len(part) else None + + +def _same_json(a: str, b: str) -> bool: + """Are two strings the same JSON value (whitespace and key order aside)? No -> False.""" + try: + return json.loads(a) == json.loads(b) + except Exception: + return False + + +def _structured_logprobs(choice: dict, content: str): + """`content`'s logprobs, and the content the tokens actually spell. + + Returns `(content, logprobs)`: on failure `(the content as validated, None)`. + + `structured_chunks` returns the canonical JSON the validator produced, which the model never + generated, so its tokens do not spell it. Two honest outcomes: + + 1. a run of tokens spells what is being returned -> use it as it is; + 2. the tokens spell the model's own JSON, which is the same JSON value (the fenced-with-spaces + case, the common one) -> return the model's form, so `''.join(token) == content` again. + + Neither holds (a rearranged key order, or a reply that is not that JSON at all) and there are no + logprobs: a caller that joins the tokens must not silently get something that does not match. + """ + lps = choice.get("logprobs") + if not lps or not lps.get("content"): + return content, None + raw = choice["message"]["content"] or "" + entries = lps["content"] + if raw == content: # not rewritten: the entries are already its + return content, _with_reasoning(lps, entries) + span = logprob_span(raw, content, entries) + if span is not None: + return content, _with_reasoning(lps, span) + inner = extract_json(raw) + if inner and _same_json(inner, content): + span = logprob_span(raw, inner, entries) + if span is not None: + return inner, _with_reasoning(lps, span) # the model's own form: the tokens spell it + return content, None + + +def _with_reasoning(lps: dict, entries: list) -> dict: + out = {"content": entries} + if lps.get("reasoning_content"): + out["reasoning_content"] = lps["reasoning_content"] return out @@ -5956,12 +6337,23 @@ def structured_chunks(chunks, validator): result = openai_collect(buffered) choice = result["choices"][0] content = validated_json(choice["message"]["content"], validator, choice["finish_reason"]) + # logprobs: the entries spell what the model wrote, which this function replaces with the + # canonical JSON. `_structured_logprobs` gives back the form the tokens spell, or None. + content, logprobs = _structured_logprobs(choice, content) yield buffered[0] delta = {"content": content} if choice["message"].get("reasoning_content"): delta["reasoning_content"] = choice["message"]["reasoning_content"] - yield {**buffered[0], "choices": [{"index": 0, "delta": delta, "finish_reason": None}]} - yield buffered[-1] + piece = {"index": 0, "delta": delta, "finish_reason": None} + if logprobs: + piece["logprobs"] = logprobs + yield {**buffered[0], "choices": [piece]} + end = buffered[-1] + if end["choices"][0].get("logprobs"): + # those entries went out in the piece above (or were dropped with it): the closing + # chunk must not carry a second copy + end = {**end, "choices": [{k: v for k, v in end["choices"][0].items() if k != "logprobs"}]} + yield end finally: chunks.close() @@ -6029,11 +6421,12 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can # request, a cache write; input_tokens keeps the last token, as 0 makes Claude Code count the prompt twice (#1013) reused = max(0, min(x.get("reused") or 0, len(ids) - 1)) read_now = len(ids) - reused - yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, - "stop_sequence": x.get("stop_sequence")}, - "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1, - "cache_read_input_tokens": reused, - "output_tokens": x["completion_tokens"]}} + delta_event = {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": x.get("stop_sequence")}, + "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1, + "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} + if x.get("rejected_tool_calls"): + delta_event["strata_rejected_tool_calls"] = x["rejected_tool_calls"] # #3796 + yield "message_delta", delta_event yield "message_stop", {"type": "message_stop"} @@ -6065,6 +6458,8 @@ def anthropic_collect(events) -> dict: msg["stop_reason"] = e["delta"]["stop_reason"] msg["stop_sequence"] = e["delta"].get("stop_sequence") msg["usage"].update(e["usage"]) + if e.get("strata_rejected_tool_calls"): + msg["strata_rejected_tool_calls"] = e["strata_rejected_tool_calls"] for i in range(len(blocks) - 1): # a turn with no (serve/dsml.py): the text is the answer; it is not also a thinking block a, b = blocks[i], blocks[i + 1] if a.get("type") == "thinking" and b.get("type") == "text" and a.get("thinking", "").strip() == b.get("text", "").strip(): @@ -6372,6 +6767,28 @@ def make_handler(svc: Service): def do_GET(self): path = self.path.split("?")[0].rstrip("/") + if path.startswith("/tool-media/"): + if not self._authorized(): + return + name = path[len("/tool-media/"):] + hub = svc.mcp + if not re.fullmatch(r"[0-9a-f]{64}\.(png|jpg|webp)", name) or not hub or not hub.media_dir: + self._json(404, {"error": {"message": "not found"}}) + return + file = Path(hub.media_dir) / name + if not file.is_file(): + self._json(404, {"error": {"message": "not found"}}) + return + body = file.read_bytes() + self.send_response(200) + self.send_header("Content-Type", {".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp"}[file.suffix]) + self.send_header("Content-Length", str(len(body))) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Cache-Control", "private, max-age=86400") + self.send_header("Cross-Origin-Resource-Policy", "same-origin") + self.end_headers() + self.wfile.write(body) + return if path.startswith("/fonts/"): # the web app's font (Outfit, OFL: serve/web/fonts); the page falls back to the system font name = path[len("/fonts/"):] @@ -6387,6 +6804,21 @@ def make_handler(svc: Service): self.end_headers() self.wfile.write(body) return + sub = web_subtree_file(path) + if path.startswith(("/web/locales/", "/web/vendor/")): + # the page's translations (serve/web/locales/.json) and the vendored KaTeX (serve/web/vendor): + # only whitelisted names and types, never a path out of those folders + if sub is None: + self._json(404, {"error": {"message": "not found"}}) + return + body = sub[0].read_bytes() + self.send_response(200) + self.send_header("Content-Type", sub[1]) + self.send_header("Cache-Control", "no-cache") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return if path.startswith("/web/"): # the web app's own files (serve/web): styles, script, icon sprite - same origin, no CDN name = path[len("/web/"):] @@ -6630,6 +7062,10 @@ def make_handler(svc: Service): body = (ROOT / "serve" / "web" / ("monitor.html" if path else "index.html")).read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") + if not path: + # the chat's svg/html preview is a sandboxed frame; this keeps it from navigating away to a web page + # (a link or inside a model's html), which no sandbox flag does (serve/web/preview.js) + self.send_header("Content-Security-Policy", PAGE_CSP) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -7146,6 +7582,25 @@ def make_handler(svc: Service): raise ValueError("structured response_format with tools/MCP is not supported") svc.load() max_req = max_new = int(req.get("max_completion_tokens") or req.get("max_tokens") or 0) # 0/-1: the rest + # No cap of our own on the reply's length when logprobs are asked for: the reply is already bounded by + # max_tokens (by the rest of the context when it is not sent), which is the only bound OpenAI and vLLM + # put on it either. A reply that is not streamed does hold every entry (its token, bytes and up to 20 + # alternatives) until it ends, so a long one holds a lot: streaming hands each entry out with its chunk. + if top_logprobs(req) is not None and batch_slots_on(svc.engine) and max_req != 1: + # --parallel/--batch: a slot's "BT " lines carry no LP line, and the batched loop never + # calls emit_lp_line (src/program/generate.cpp); an admission -- a max_tokens 1 request -- is read + # as GEN 1, which does write them. Past that one token a reply would hold entries for a prefix + # only, which a client cannot tell from the model's own answer, so the longer one is refused. + raise ValueError('logprobs is available with "parallel" (batch slots) only for max_tokens 1; ' + 'run the server without "--parallel" for longer replies') + n_vocab = len(getattr(svc.tok, "tokens", ())) or None + if top_logprobs(req) is not None and n_vocab: + # emit_lp_line indexes the logits row with each named id as given, so an id past the vocabulary + # would read out of bounds: refused here, before anything is sent + bad = [i for i in allowed_ids(req) if i >= n_vocab] + if bad: + raise ValueError(f"allowed_token_ids: {bad[0]} is outside the vocabulary " + f"(0..{n_vocab - 1})") bias_api.validate_request(req, svc.engine, len(getattr(svc.tok, "tokens", ())) or None) use_mcp = req.get("strata_mcp") is True and svc.mcp is not None # the web app's opt-in (serve/mcp.py) own = {t.get("name") for t in tools or [] if isinstance(t, dict)} # #592: a second line of defence @@ -7445,6 +7900,11 @@ class Server(ThreadingHTTPServer): # (STRATA_HTTP_BACKLOG overrides it) request_queue_size = max(5, int(os.environ.get("STRATA_HTTP_BACKLOG") or 256)) + def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): + if ":" in server_address[0]: + self.address_family = socket.AF_INET6 + super().__init__(server_address, RequestHandlerClass, bind_and_activate) + def handle_error(self, request, client_address): if not isinstance(sys.exc_info()[1], ConnectionError): # a client that hangs up needs no stack trace super().handle_error(request, client_address) @@ -8143,7 +8603,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in "written by setup.py") ap.add_argument("--host", default=None, help="the address to listen on: 127.0.0.1 = this PC only (the default), 0.0.0.0 = also other devices " - "on your network (set an API key); also \"host\" in the config") + "on your network, :: = all IPv6 interfaces (set an API key); also \"host\" in the config") ap.add_argument("--script-cycle", action="store_true", help="with --script given more than once: repeat the scripts by position instead of advancing " "to the last one and staying there, so extra requests a harness makes (a session title, " @@ -8372,6 +8832,12 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in print('[strata] the vision section\'s "elastic" needs "vram_elastic": true (the expert cache gives the ' "encoder its VRAM): the encoder starts with the model instead", flush=True) vcfg["elastic"] = False + elif vcfg.get("elastic") is True and layer_split_of(cfg): + # the engine turns --vram-elastic off on a layer split (a cache per GPU): the encoder still starts + # with the first picture and stops when idle, but its VRAM has to be free already + print('[strata] images: on a layer split the expert cache cannot make room for the image encoder (the ' + 'engine turns --vram-elastic off); keep its VRAM free with "--vram-reserve-mib" on the ' + "encoder's GPU, or the first picture may not get it", flush=True) vision = Vision(vcfg, log=open(cfg["log"], "a", encoding="utf-8") if cfg.get("log") else None, env=vision_env(cfg, env), lazy=lazy) print("model unloaded; the first request loads it ..." if lazy else @@ -8609,6 +9075,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in if hub is not None: import atexit svc.mcp = hub + if hub.settings["image_results"]: + hub.media_dir = Path(a.config).with_suffix(".tool-media") if a.config else Path.cwd() / ".tool-media" print(f"[strata] starting {len(hub.servers)} MCP server{'s' * (len(hub.servers) != 1)} for the web app's " f"chat: {', '.join(hub.servers)}", flush=True) hub.start() @@ -8617,18 +9085,19 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in bound_port = httpd.server_address[1] # --port 0: report the port the OS actually assigned svc.start_idle_unload() svc.start_vision_idle() - here = "127.0.0.1" if a.host in ("0.0.0.0", "", "::") else a.host + here = "[::1]" if a.host == "::" else "127.0.0.1" if a.host in ("0.0.0.0", "") else f"[{a.host}]" if ":" in a.host else a.host print(f"ready: http://{here}:{bound_port}/v1 (OpenAI: /v1/chat/completions, Anthropic: /v1/messages, " f"context {engine.max_context} tokens{', images on' if vision else ''}" f"{', API key required' if svc.api_key else ''})", flush=True) print(f" open http://{here}:{bound_port}/ in a browser to chat; close this window to stop the model", flush=True) if a.host not in ("127.0.0.1", "localhost", "::1"): # issue #26: reachable from other devices - say at which address, and what can still block it - ips = lan_addresses() + ips = [f"[{a.host}]"] if ":" in a.host and a.host != "::" else [] if a.host == "::" else lan_addresses() for ip in ips: print(f" from other devices: http://{ip}:{bound_port}/ (API: http://{ip}:{bound_port}/v1)", flush=True) if not ips: - print(" from other devices: http://:" + str(bound_port) + "/", flush=True) + address = "[]" if a.host == "::" else "" + print(f" from other devices: http://{address}:{bound_port}/", flush=True) if not svc.api_key: print(" WARNING: " + open_server_warning(bound_port, tools=svc.mcp is not None), flush=True) @@ -8642,7 +9111,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in # on its own thread: webbrowser.open waits for the browser launcher, which on Linux can run for as long as # the browser does, and the main thread must be free to take Ctrl+C and SIGTERM (#1872) threading.Thread(target=webbrowser.open, daemon=True, name="strata-open-browser", - args=(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{bound_port}/",)).start() + args=(f"http://{here}:{bound_port}/",)).start() if ready_path is not None or event_sink is not None: ready_host = f"[{here}]" if ":" in here and not here.startswith("[") else here record = {"schema_version": 1, "instance_id": svc.instance_id, "pid": os.getpid(), diff --git a/serve/structured.py b/serve/structured.py index 9bed5348..1809a0c3 100644 --- a/serve/structured.py +++ b/serve/structured.py @@ -28,6 +28,46 @@ class _ObjectError: message = "the answer is not a JSON object" +class _Repairing: + """A validator that also tells validated_json to retry once, after a strict parse failed, with the backslashes that + are not valid JSON escapes doubled (response_format "repair_latex_escapes": true, #2893).""" + repair_escapes = True + + def __init__(self, inner): + self.inner = inner + + def iter_errors(self, value): + return self.inner.iter_errors(value) + + +_HEX = "0123456789abcdefABCDEF" + + +def repair_latex_escapes(text: str) -> str: + r"""Double every backslash that does not start a valid JSON escape, so \alpha and \gamma read as text. + The valid escapes (\b \f \n \r \t \/ \" and a well-formed \uXXXX) stay as they are: a model cannot be told + from LaTeX there, so a \beta next to a \alpha comes back with a backspace. Pairs of backslashes are skipped.""" + out = [] + i, n = 0, len(text) + while i < n: + ch = text[i] + if ch != "\\": + out.append(ch) + i += 1 + continue + nxt = text[i + 1] if i + 1 < n else "" + if nxt in ("\\", '"', "/", "b", "f", "n", "r", "t"): + out.append(ch + nxt) + i += 2 + elif nxt == "u" and len(text) >= i + 6 and all(c in _HEX for c in text[i + 2:i + 6]): + out.append(text[i:i + 6]) + i += 6 + else: + out.append("\\\\") + i += 1 + return "".join(out) + + _jsonschema = None # (validators, SchemaError, Registry, NoSuchResource), False when not installed _jsonschema_lock = threading.Lock() @@ -140,6 +180,8 @@ def prepare_format(response_format, messages, with_tools=False): # /v1/responses (#782): the schema is for the final answer; a turn that calls a tool is not an answer directive += ("\nThis applies only to your final answer. To use a tool, call it as usual; the JSON object is " "what you write once you are done with the tools.") + if response_format.get("repair_latex_escapes") is True: + validator = _Repairing(validator) messages = [dict(message) for message in messages] if messages and messages[0].get("role") == "system": content = messages[0].get("content") or "" @@ -152,7 +194,10 @@ def prepare_format(response_format, messages, with_tools=False): return messages, validator -def _extract_json(text: str) -> str: +def extract_json(text: str) -> str: + """The first JSON object in `text`: a ```-fenced block's inside when there is one, else the text + from its first `{`. Empty when there is nothing to take. The server's json_schema logprobs + alignment reads the model's own JSON form with it.""" s = (text or "").strip() if not s: return "" @@ -204,10 +249,20 @@ def validated_json(text, validator, finish): if finish != "stop": raise StructuredOutputError(f"structured output was incomplete (finish_reason={finish}); increase the output budget") try: - value = json.loads(_extract_json(text), object_pairs_hook=pairs, parse_constant=constant) + value = json.loads(extract_json(text), object_pairs_hook=pairs, parse_constant=constant) canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) except (ValueError, TypeError) as exc: - raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc + value = None + if getattr(validator, "repair_escapes", False): # opt-in (#2893); only after the strict parse failed + try: + value = json.loads(repair_latex_escapes(extract_json(text)), object_pairs_hook=pairs, + parse_constant=constant) + canonical = json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + print("[strata] structured output: repaired backslashes that were not valid JSON escapes", flush=True) + except (ValueError, TypeError): + value = None + if value is None: + raise StructuredOutputError(f"model did not return valid JSON: {exc}") from exc try: error = next(validator.iter_errors(value), None) except Exception as exc: diff --git a/serve/test_chat_tool_results.py b/serve/test_chat_tool_results.py new file mode 100644 index 00000000..9c99b2ee --- /dev/null +++ b/serve/test_chat_tool_results.py @@ -0,0 +1,133 @@ +"""Chat Completions tool results must follow call IDs before the template drops them.""" +import copy +import http.client +import json +from pathlib import Path +import unittest + +from serve.frontend import ChatTemplate, openai_to_messages +from serve.server import ByteTokenizer, MockEngine, Service, serve + + +TEMPLATE = ChatTemplate(Path(__file__).with_name("chat_template.jinja")) + + +def history(): + return [ + {"role": "user", "content": "Read a.txt and b.txt."}, + {"role": "assistant", "content": "", "tool_calls": [ + {"id": "call_a", "type": "function", "function": { + "name": "read_file", "arguments": '{"path":"a.txt"}'}}, + {"id": "call_b", "type": "function", "function": { + "name": "read_file", "arguments": '{"path":"b.txt"}'}}]}, + {"role": "tool", "tool_call_id": "call_b", "content": "RESULT_FROM_B"}, + {"role": "tool", "tool_call_id": "call_a", "content": "RESULT_FROM_A"}, + ] + + +def normalized(messages): + return openai_to_messages({"messages": messages})[0] + + +def rendered(messages): + return TEMPLATE.render(normalized(messages), enable_thinking=False) + + +class ChatToolResults(unittest.TestCase): + def test_reversed_results_of_the_same_function_follow_call_ids(self): + raw = history() + before = copy.deepcopy(raw) + ordered = raw[:2] + list(reversed(raw[2:])) + self.assertEqual(rendered(raw), rendered(ordered)) + self.assertLess(rendered(raw).index("RESULT_FROM_A"), rendered(raw).index("RESULT_FROM_B")) + self.assertEqual(raw, before) + messages = normalized(raw) + self.assertEqual([m["content"] for m in messages[2:]], ["RESULT_FROM_A", "RESULT_FROM_B"]) + self.assertTrue(all(set(m) == {"role", "content"} for m in messages[2:])) + self.assertTrue(all(set(c) == {"function"} for c in messages[1]["tool_calls"])) + + def test_already_ordered_and_legacy_prompts_are_identical(self): + ordered = history() + ordered[2:] = reversed(ordered[2:]) + legacy = copy.deepcopy(ordered) + for call in legacy[1]["tool_calls"]: + call.pop("id") + for result in legacy[2:]: + result.pop("tool_call_id") + self.assertEqual(normalized(ordered), normalized(legacy)) + self.assertEqual(rendered(ordered), rendered(legacy)) + + def test_ambiguous_or_incomplete_ids_preserve_received_order(self): + for case in ("missing_call", "missing_result", "duplicate_call", "duplicate_result", "unknown", + "list_call", "list_result", "empty_call", "empty_result", "partial"): + raw = history() + if case == "missing_call": + raw[1]["tool_calls"][0].pop("id") + elif case == "missing_result": + raw[2].pop("tool_call_id") + elif case == "duplicate_call": + raw[1]["tool_calls"][1]["id"] = "call_a" + elif case == "duplicate_result": + raw[3]["tool_call_id"] = "call_b" + elif case == "unknown": + raw[2]["tool_call_id"] = "unknown" + elif case == "list_call": + raw[1]["tool_calls"][0]["id"] = [] + elif case == "list_result": + raw[2]["tool_call_id"] = [] + elif case == "empty_call": + raw[1]["tool_calls"][0]["id"] = "" + elif case == "empty_result": + raw[2]["tool_call_id"] = "" + else: + raw.pop() + with self.subTest(case=case): + self.assertEqual([m["content"] for m in normalized(raw)[2:]], + [m["content"] for m in raw[2:]]) + + def test_each_tool_run_is_scoped_to_its_assistant_turn(self): + raw = history() + history() + self.assertEqual([m["content"] for m in normalized(raw) if m["role"] == "tool"], + ["RESULT_FROM_A", "RESULT_FROM_B"] * 2) + raw = history() + raw.insert(2, {"role": "user", "content": "intervening message"}) + self.assertEqual([m["content"] for m in normalized(raw) if m["role"] == "tool"], + ["RESULT_FROM_B", "RESULT_FROM_A"]) + + def test_json_encoded_history_and_calls(self): + raw = history() + raw[1]["tool_calls"] = json.dumps(raw[1]["tool_calls"]) + self.assertEqual(normalized(json.dumps(raw)), normalized(history())) + + def test_multimodal_result_moves_with_its_call(self): + raw = history() + raw[2]["content"] = [{"type": "text", "text": "RESULT_FROM_B"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}] + messages = normalized(raw) + self.assertEqual(messages[2]["content"], "RESULT_FROM_A") + self.assertEqual(messages[3]["content"], [{"type": "text", "text": "RESULT_FROM_B"}, + {"type": "image", "source": "data:image/png;base64,AA=="}]) + + def test_http_engine_receives_the_ordered_prompt(self): + tok = ByteTokenizer() + engine = MockEngine(tok, "ok", max_context=4096) + service = Service(engine, tok, TEMPLATE) + httpd = serve(service, port=0) + connection = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=10) + try: + connection.request("POST", "/v1/chat/completions", json.dumps({ + "messages": history(), "max_tokens": 16, "reasoning_effort": "none"}), + {"Content-Type": "application/json"}) + response = connection.getresponse() + body = response.read() + self.assertEqual(response.status, 200, body) + prompt = tok.decode(engine.last_prompt) + self.assertLess(prompt.index("RESULT_FROM_A"), prompt.index("RESULT_FROM_B")) + finally: + connection.close() + httpd.shutdown() + httpd.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_logprobs.py b/serve/test_logprobs.py new file mode 100644 index 00000000..a21237db --- /dev/null +++ b/serve/test_logprobs.py @@ -0,0 +1,541 @@ +"""OpenAI logprobs on /v1/chat/completions, from the engine's LP lines: python -m unittest serve.test_logprobs. + +The engine (src/program/generate.cpp) writes an `LP [id:logprob ...]` line right after +each `T ` when the request carries `logprobs=K`; this is the server half that turns those +lines into OpenAI's logprobs, and the parts that are easy to get wrong: + + - `allowed_token_ids`: only the named ids, renormalised over them (vLLM's semantics). + - `response_format: json_schema` rewrites the content, so the tokens no longer spell what is + returned; the entries are re-aligned or dropped, never returned wrong. +""" +from __future__ import annotations + +import json +import math +import queue +import threading +import unittest +import urllib.request +from pathlib import Path +from types import SimpleNamespace + +from serve.frontend import ChatTemplate +from serve.server import (ByteTokenizer, LogprobEntries, LPLines, MockEngine, Service, StrataEngine, batch_slots_on, + logprob_span, serve, top_logprobs, allowed_ids) + +ROOT = Path(__file__).resolve().parent.parent +TEMPLATE = ChatTemplate(ROOT / "serve" / "chat_template.jinja") + + +class Tokenizer(ByteTokenizer): + def token_bytes(self, token): + return self.SPECIALS[token - 256].encode() if token >= 256 else bytes([token]) + + +class ThinkTokenizer(Tokenizer): + # two extra special tokens that decode as the thinking marks; ALWAYS so the byte-level + # encode() maps them wherever they appear ("" would loop forever in startswith, so they + # are real strings, like the engine's own think tokens are) + SPECIALS = ByteTokenizer.SPECIALS + ["", ""] + ALWAYS = ("", "") + + +class LpEngine(MockEngine): + """MockEngine with the LP line of each token on lp_lines before the token is yielded, as the + engine leaves it; token i has the log-probability -(i + 1) / 100 and four named alternatives.""" + + def __init__(self, tok, script, lines=True): + super().__init__(tok, script, max_context=16384) + self.with_lines, self.sampling = lines, None + + def line(self, i, t): + """The LP line of token t, the i-th of the reply: the same four ids whatever was asked.""" + return (f"LP {-(i + 1) / 100:.6f} 65:-0.500000 72:-1.250000 " + f"88:-3.000000 91:-4.200000\n") + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.sampling, self.lp_lines = dict(sampling or {}), LPLines(cancel) + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if self.with_lines: + self.lp_lines.append((t, self.line(i, t))) + yield t + + +class NamedEngine(LpEngine): + """LpEngine that prints the request's own `allowed_token_ids`, as the engine's emit_lp_line does: + `LP : ...`, the chosen id left out (it is on the head).""" + + def line(self, i, t): + named = [int(x) for x in (self.sampling or {}).get("allowed_token_ids") or [] if int(x) != t] + alts = "".join(f" {x}:{-0.700000 - 0.010000 * j:.6f}" for j, x in enumerate(named)) + return f"LP {-(i + 1) / 100:.6f}{alts}\n" + + +class NextEngine(LpEngine): + """LpEngine for two requests: the second one stops after its first token (its LP line is in lp_lines) + until the first request's reply has been read.""" + + def __init__(self, tok, scripts, first_out): + super().__init__(tok, scripts) + self.first_out, self.calls = first_out, 0 + self.first_in, self.first_generated, self.second_started = (threading.Event(), threading.Event(), + threading.Event()) + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.calls += 1 + mine = self.calls + if mine == 1: + self.first_in.set() + try: + for i, t in enumerate(super().generate(ids, max_new, sampling, cancel, embeddings)): + if mine == 2 and i == 0: + self.second_started.set() + self.first_out.wait(10) + yield t + finally: + if mine == 1: + self.first_generated.set() + + +class HandOver: + """Service.fifo that, once the first request has generated, lets its turn go and then waits until the + next request is generating before the first one goes on.""" + + def __init__(self, engine): + self.lock, self.engine, self.waited = threading.Lock(), engine, False + + def acquire(self, *a, **k): + return self.lock.acquire(*a, **k) + + def release(self): + self.lock.release() + if self.engine.first_generated.is_set() and not self.waited: + self.waited = True + self.engine.second_started.wait(10) + + def locked(self): + return self.lock.locked() + + def __enter__(self): + self.acquire() + return self + + def __exit__(self, *exc): + self.release() + + +SCHEMA = {"type": "json_schema", "json_schema": {"name": "a", "strict": True, "schema": { + "type": "object", "properties": {"rent": {"type": "string"}, "quote": {"type": "string"}}, + "required": ["rent", "quote"], "additionalProperties": False}}} + + +class Keys(unittest.TestCase): + """What the request asks for, and what reaches the engine line.""" + + def test_what_the_request_asks(self): + self.assertEqual(top_logprobs({"logprobs": True}), 0) + self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 3}), 3) + self.assertEqual(top_logprobs({"logprobs": True, "top_logprobs": 50}), 20) + self.assertEqual(top_logprobs({"logprobs": 2}), 2) # the legacy completions form + for req in ({}, {"logprobs": False}, {"logprobs": None}, {"top_logprobs": 3}): + self.assertIsNone(top_logprobs(req)) + + def test_allowed_ids(self): + self.assertEqual(allowed_ids({"allowed_token_ids": [1, 2, 3]}), [1, 2, 3]) + for req in ({}, {"allowed_token_ids": "1,2"}, {"allowed_token_ids": [True]}, {"allowed_token_ids": [-1]}): + self.assertEqual(allowed_ids(req), []) + + def test_the_engine_key_only_when_asked(self): + self.assertIn(" logprobs=0", StrataEngine.sampling_keys({"logprobs": True})) + self.assertIn(" logprobs=5", StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 5})) + self.assertNotIn("logprobs", StrataEngine.sampling_keys({})) + self.assertNotIn("logprobs", StrataEngine.sampling_keys({"logprobs": False, "temperature": 0})) + + def test_allowed_reaches_the_engine_line(self): + keys = StrataEngine.sampling_keys({"logprobs": True, "top_logprobs": 2, + "allowed_token_ids": [7, 8, 9]}) + self.assertIn(" logprobs=2 ", keys) + self.assertIn(" allowed=7,8,9", keys) + + def test_unreadable_lines_give_no_entry(self): + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + for line in ("LP nan", "LP -nan(ind)", "LP inf", "LP -0.1 65:x", "LP -0.1 65:-inf", "LP -0.1 65", + "LP -0.200000 65:-1.0"): + eng.lp_lines.append((72, line)) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), owner=a).take(eng) + self.assertEqual([e["logprob"] for e in got], [-0.2]) + + def test_a_filtered_line_with_nothing_left_keeps_its_token(self): + # none of the named ids on the line: the entry keeps the chosen token and its own logprob, and no + # alternatives. It used to be None, appended all the same, and the reply failed on e["token"]. + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + eng.lp_lines.append((72, "LP -0.300000 65:-0.500000")) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [70], a).take(eng) + self.assertEqual([(e["token"], e["logprob"], e["top_logprobs"]) for e in got], [("H", -0.3, [])]) + + def test_a_named_token_the_line_does_not_repeat_is_its_own_distribution(self): + # the engine prints the chosen token's logprob on the head and the named ids after it, never repeating + # the chosen one: naming only that id leaves it alone in the distribution, at 1 (logprob 0) + a = threading.Event() + eng = SimpleNamespace(lp_lines=LPLines(a)) + eng.lp_lines.append((72, "LP -0.300000 65:-0.500000")) + got = LogprobEntries(SimpleNamespace(tok=Tokenizer(), stop_ids=set()), [72], a).take(eng) + self.assertEqual(got[0]["top_logprobs"], [{"token": "H", "logprob": 0.0, "bytes": [72]}]) + self.assertEqual(got[0]["logprob"], 0.0) + + +class Generate(unittest.TestCase): + """The token's LP line is read next to it, and only when it was asked for.""" + + def engine(self, *lines): + e = StrataEngine.__new__(StrataEngine) + e.proc = __import__("types").SimpleNamespace( + stdin=__import__("io").StringIO(), poll=lambda: None) + e.lines, e.can_stop, e.max_context, e.silence_s = queue.Queue(), False, 262144, 0 + for line in lines: + e.lines.put(line) + return e + + def test_a_token_is_yielded_with_its_lp_line_read(self): + e = self.engine("PP 3 3", "T 72", "LP -0.100000 72:-0.1 65:-2.5", "T 105", + "LP -0.200000 105:-0.2 65:-3", "T 257", "LP -0.010000", + "DONE 3 3 0 3 stop 0 0 0") + seen = [] + for t in e.generate([1, 2, 3], 8, {"logprobs": True, "top_logprobs": 2}, threading.Event()): + if t is not None: + seen.append((t, [x[0] for x in e.lp_lines])) + self.assertEqual(seen, [(72, [72]), (105, [72, 105]), (257, [72, 105, 257])]) + self.assertIn(" logprobs=2 ", e.proc.stdin.getvalue()) + self.assertEqual(e.lp_lines[1][1], "LP -0.200000 105:-0.2 65:-3") + + def test_an_engine_without_lp_lines(self): + e = self.engine("T 72", "T 105", "DONE 3 3 0 2 stop 0 0 0") + toks = [t for t in e.generate([1], 8, {"logprobs": True}, threading.Event()) if t is not None] + self.assertEqual(toks, [72, 105]) + self.assertEqual(list(e.lp_lines), []) + self.assertEqual(e.last["finish"], "stop") + + def test_not_asked_reads_as_before(self): + e = self.engine("T 72", "LP -0.1", "T 105", "DONE 3 3 0 2 stop 0 0 0") + toks = [t for t in e.generate([1], 8, {}, threading.Event()) if t is not None] + self.assertEqual(toks, [72, 105]) + self.assertEqual(list(e.lp_lines), []) + + def test_a_consumer_that_stops_early_does_not_lose_the_done_read_after_the_token(self): + # the DONE line was read while looking for the token's LP line: the drain must take it, + # not wait for another + e = self.engine("T 72", "DONE 3 3 0 1 length 0 0 0", None) + gen = e.generate([1], 1, {"logprobs": True}, threading.Event()) + self.assertEqual(next(gen), 72) + gen.close() + self.assertEqual(e.last["finish"], "length") + + +class Api(unittest.TestCase): + def setUp(self): + self.tok = Tokenizer() + self.engine = LpEngine(self.tok, "Café costs €5.") + self.svc = Service(self.engine, self.tok, TEMPLATE) + self.httpd = serve(self.svc, port=0) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def tearDown(self): + self.httpd.shutdown() + self.httpd.server_close() + + def post(self, body, stream=False): + body = {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 200, + "chat_template_kwargs": {"enable_thinking": False}, **body} + if stream: + body["stream"] = True + req = urllib.request.Request(self.base + "/v1/chat/completions", json.dumps(body).encode(), + {"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read().decode() + if not stream: + return json.loads(raw) + return [json.loads(x[6:]) for x in raw.splitlines() if x.startswith("data: {")] + + def test_the_tokens_spell_the_content(self): + out = self.post({"logprobs": True, "top_logprobs": 1}) + choice = out["choices"][0] + content = choice["message"]["content"] + lps = choice["logprobs"]["content"] + self.assertEqual(content, "Café costs €5.") + self.assertEqual("".join(e["token"] for e in lps), content) + self.assertEqual(len(lps), len(content.encode())) # one per byte token; no stop token + self.assertEqual(b"".join(bytes(e["bytes"]) for e in lps), content.encode()) + e_acute = [e for e in lps if len(e["bytes"]) == 1 and e["bytes"][0] >= 0x80] + self.assertEqual([e["token"] for e in e_acute[:2]], ["", "é"]) # split across two tokens + self.assertEqual(lps[0]["logprob"], -0.01) + self.assertEqual(lps[0]["top_logprobs"][0]["token"], "A") + self.assertEqual(self.engine.sampling.get("logprobs"), True) + + def test_a_request_reads_only_its_own_lines(self): + # A's last "." is held by its stop string and sent after A has left the queue, when B is + # already generating on the same engine: each reply's tokens must spell that reply + first_out = threading.Event() + engine = NextEngine(self.tok, ["Café costs €5.", "Bonjour!"], first_out) + svc = Service(engine, self.tok, TEMPLATE) + svc.fifo = HandOver(engine) + httpd = serve(svc, port=0) + got = {} + try: + self.base = f"http://127.0.0.1:{httpd.server_address[1]}" + a = threading.Thread(target=lambda: got.update(a=self.post({"logprobs": True, "stop": [".!"]}))) + b = threading.Thread(target=lambda: got.update(b=self.post({"logprobs": True}))) + a.start() + self.assertTrue(engine.first_in.wait(10)) + b.start() + a.join(30) + first_out.set() + b.join(30) + finally: + first_out.set() + httpd.shutdown() + httpd.server_close() + for key, text in (("a", "Café costs €5."), ("b", "Bonjour!")): + choice = got[key]["choices"][0] + self.assertEqual(choice["message"]["content"], text) + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), text, key) + + def test_logprobs_take_any_max_tokens(self): + # No cap of our own: the reply is already bounded by max_tokens (the rest of the context when it is not + # sent), which is the only bound OpenAI and vLLM put on it too -- openai-node's max_tokens is optional + # and vLLM's defaults to 16 or None, neither tying it to logprobs. + for max_tokens in (200, 5000, 0, -1, None): # 0 / -1: "the rest of the context"; None: not sent + choice = self.post({"logprobs": True, "top_logprobs": 1, "max_tokens": max_tokens})["choices"][0] + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), + "Café costs €5.", max_tokens) + self.assertNotIn("logprobs", self.post({"max_tokens": 0})["choices"][0]) # not asked: as before + + def test_a_streamed_reply_needs_no_bound(self): + # A streamed reply hands each entry out with its chunk and keeps none, so it is bounded by the reply's own + # length. OpenAI itself bounds a reply only by the model's context, and its SDKs send no max_tokens by + # default. 5000 and "the rest of the context" must both be answered, as they are without logprobs. + for max_tokens in (5000, 0, None): # None: the field is not sent at all + chunks = self.post({"logprobs": True, "max_tokens": max_tokens}, stream=True) + text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(text, "Café costs €5.", max_tokens) + self.assertEqual("".join(toks), text, max_tokens) # an entry for every token, streamed or not + + def test_a_json_schema_reply_takes_any_max_tokens(self): + # structured_chunks buffers the reply to validate it, logprobs included: it holds the entries until the + # end, as a reply that is not streamed does. That memory is bounded by max_tokens, not by a cap of ours. + written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' + self.engine = self.svc.engine = LpEngine(self.tok, written) + content = '{"rent": "$1,250", "quote": "x"}' + for max_tokens in (200, 0, 5000): + choice = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA})["choices"][0] + self.assertEqual(choice["message"]["content"], content, max_tokens) + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content, max_tokens) + chunks = self.post({"logprobs": True, "max_tokens": max_tokens, "response_format": SCHEMA}, stream=True) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), content, (max_tokens, "streamed")) + + def test_logprobs_are_refused_on_the_batch_path(self): + # --parallel/--batch: the engine's batched loop prints "BT " and never calls emit_lp_line + # (src/program/generate.cpp), so no LP line reaches the server and the field would simply be absent. + # Refused up front instead, before anything is generated; a request that does not ask is untouched. + self.engine.batch = 2 + with self.assertRaises(urllib.error.HTTPError) as cm: + self.post({"logprobs": True}) + self.assertEqual(cm.exception.code, 400) + self.assertIn("--parallel", cm.exception.read().decode()) + self.engine.batch = 0 + self.assertIn("logprobs", self.post({"logprobs": True})["choices"][0]) + + def test_allowed_token_ids_outside_the_vocabulary_is_a_400(self): + # emit_lp_line indexes its logits row with each named id, so an id past the vocabulary would read out of + # bounds; the request is refused before anything is generated + self.tok.tokens = [str(i) for i in range(300)] # a tokenizer that knows its vocabulary + with self.assertRaises(urllib.error.HTTPError) as cm: + self.post({"logprobs": True, "top_logprobs": 1, "allowed_token_ids": [300]}) + self.assertEqual(cm.exception.code, 400) + self.assertIn("allowed_token_ids", cm.exception.read().decode()) + self.assertIn("logprobs", self.post({"logprobs": True, "top_logprobs": 1, + "allowed_token_ids": [299]})["choices"][0]) + + def test_streamed(self): + chunks = self.post({"logprobs": True}, stream=True) + content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + toks = [e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(content, "Café costs €5.") + self.assertEqual("".join(toks), content) + + def test_with_thinking_each_part_is_spelled_by_its_tokens(self): + tok = ThinkTokenizer() + svc = Service(LpEngine(tok, "Two times three.\n\nSix."), tok, + TEMPLATE) + httpd = serve(svc, port=0) + try: + self.base = f"http://127.0.0.1:{httpd.server_address[1]}" + for stream in (False, True): + out = self.post({"logprobs": True, "chat_template_kwargs": {"enable_thinking": True}}, + stream) + chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"], + "logprobs": out["choices"][0]["logprobs"]}]}] + for key in ("content", "reasoning_content"): + text = "".join(c["choices"][0]["delta"].get(key) or "" for c in chunks if c.get("choices")) + toks = "".join(e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get(key, [])) + self.assertTrue(text) + self.assertEqual(toks, text, (key, stream)) + self.assertNotIn("think>", toks) + finally: + httpd.shutdown() + httpd.server_close() + + def test_not_asked_no_logprobs(self): + out = self.post({}) + self.assertNotIn("logprobs", out["choices"][0]) + + def test_an_engine_without_lp_lines_gives_none(self): + self.engine.with_lines = False + out = self.post({"logprobs": True}) + self.assertEqual(out["choices"][0]["message"]["content"], "Café costs €5.") + self.assertNotIn("logprobs", out["choices"][0]) + + def test_allowed_token_ids_are_renormalised_over_the_named_ids(self): + out = self.post({"logprobs": True, "allowed_token_ids": [65, 72]}) + lps = out["choices"][0]["logprobs"]["content"] + self.assertTrue(lps) + for e in lps: + ids = [t["token"] for t in e["top_logprobs"]] + self.assertEqual(ids, ["A", "H"]) # only the named ones + import math + total = sum(math.exp(t["logprob"]) for t in lps[0]["top_logprobs"]) + self.assertAlmostEqual(total, 1.0, places=6) # renormalised: they sum to 1 + + def test_allowed_token_ids_with_nothing_to_renormalise(self): + # the mock's alternatives are 65/72/88/91: naming another id leaves every line with no survivor. Each + # token keeps its own logprob and an empty candidate list, and the reply still comes back whole (this + # used to be a 400 on the unstreamed path and a reply cut after the role chunk when streamed). + for body in ({"logprobs": True, "allowed_token_ids": [66]}, + {"logprobs": True, "allowed_token_ids": [66, 70, 71]}): + choice = self.post(body)["choices"][0] + lps = choice["logprobs"]["content"] + self.assertEqual(choice["message"]["content"], "Café costs €5.") + self.assertEqual("".join(e["token"] for e in lps), "Café costs €5.") + self.assertEqual([e["top_logprobs"] for e in lps], [[]] * len(lps)) + self.assertEqual(lps[0]["logprob"], -0.01) # the token's own, as the engine reported it + streamed = self.post(body, stream=True) + toks = [e["token"] for c in streamed if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), "Café costs €5.") + + def test_a_named_token_the_model_chose_is_in_its_distribution(self): + # 46 is the reply's final ".": the engine does not repeat the chosen token among the named ids, so + # naming only it used to leave nothing to normalise over. It is the whole distribution now, at 0. + lps = self.post({"logprobs": True, "allowed_token_ids": [46]})["choices"][0]["logprobs"]["content"] + dot = [e for e in lps if e["token"] == "."] + self.assertEqual(len(dot), 1) + self.assertEqual(dot[0]["top_logprobs"], [{"token": ".", "logprob": 0.0, "bytes": [46]}]) + self.assertEqual(dot[0]["logprob"], 0.0) + self.assertEqual([e["top_logprobs"] for e in lps if e["token"] != "."], [[]] * (len(lps) - 1)) + + def test_a_choice_of_ten_that_only_the_ended_reply_settles(self): + # ten named ids, and a reply that is two of them: "1" alone is already one of the choices, so which + # one was picked is only known when the reply ends. Here "11": each token's entries cover the ten + # named ids (the chosen one included, because the engine never repeats it), and they sum to 1. + self.engine = self.svc.engine = NamedEngine(self.tok, "11") + digits = [ord(c) for c in "0123456789"] + for stream in (False, True): + out = self.post({"logprobs": True, "top_logprobs": 10, "allowed_token_ids": digits}, stream) + chunks = out if stream else [{"choices": [{"delta": out["choices"][0]["message"], + "logprobs": out["choices"][0]["logprobs"]}]}] + content = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + lps = [e for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual(content, "11") + self.assertEqual([e["token"] for e in lps], ["1", "1"]) # the first token alone is a choice too + self.assertEqual("".join(e["token"] for e in lps), content) + for e in lps: + ids = [t["token"] for t in e["top_logprobs"]] + self.assertEqual(sorted(ids), sorted("0123456789")) # the ten named ids, and only them + self.assertIn(e["token"], ids) # the chosen one is one of them + self.assertEqual(ids[0], e["token"]) # ... and the most likely, here + self.assertEqual([t["logprob"] for t in e["top_logprobs"]], + sorted((t["logprob"] for t in e["top_logprobs"]), reverse=True)) + self.assertAlmostEqual(sum(math.exp(t["logprob"]) for t in e["top_logprobs"]), 1.0, places=6) + + def test_a_held_tail_of_more_than_one_token(self): + # "5." is the start of the stop string, so the parser holds two tokens and sends them as one piece + # after the request has left the queue: both entries come from this request's own lines all the same + chunks = self.post({"logprobs": True, "stop": ["5.!"]}, stream=True) + content = [c for c in chunks if c.get("choices") and c["choices"][0]["delta"].get("content")] + self.assertEqual(content[-1]["choices"][0]["delta"]["content"], "5.") # held, then flushed whole + self.assertEqual([e["token"] for e in content[-1]["choices"][0]["logprobs"]["content"]], ["5", "."]) + text = "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c.get("choices")) + self.assertEqual(text, "Café costs €5.") + self.assertEqual("".join(e["token"] for c in chunks if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])), text) + choice = self.post({"logprobs": True, "stop": ["5.!"]})["choices"][0] # and not streamed + self.assertEqual(choice["message"]["content"], "Café costs €5.") + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), "Café costs €5.") + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"][-2:]), "5.") + + def test_json_schema_answer_as_written_with_its_logprobs(self): + # MockEngine appends the stop token to the script it is built with, and reports + # finish_reason=length when it runs out -- so the engine is rebuilt with this answer + # rather than re-pointed at a raw token list (which would drop the stop token). + written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' + self.engine = self.svc.engine = LpEngine(self.tok, written) + out = self.post({"logprobs": True, "temperature": 0, "response_format": SCHEMA}) + choice = out["choices"][0] + content = choice["message"]["content"] + self.assertEqual(content, '{"rent": "$1,250", "quote": "x"}') # the JSON as written + self.assertEqual("".join(e["token"] for e in choice["logprobs"]["content"]), content) + streamed = self.post({"logprobs": True, "response_format": SCHEMA}, stream=True) + toks = [e["token"] for c in streamed if c.get("choices") + for e in (c["choices"][0].get("logprobs") or {}).get("content", [])] + self.assertEqual("".join(toks), content) + plain = self.post({"temperature": 0, "response_format": SCHEMA}) # not asked: as before + self.assertEqual(plain["choices"][0]["message"]["content"], + '{"rent":"$1,250","quote":"x"}') + self.assertNotIn("logprobs", plain["choices"][0]) + + +class Replicas(unittest.TestCase): + """`--replicas`: a ReplicaEngine's own `batch` is how many requests its engines run at once and counts a replica + without slots as one, so asking it "does this engine use batch slots" refused logprobs on a server that has + none -- one that reads every reply by the GEN path, which does write LP lines.""" + + @staticmethod + def replica(*batches): + from serve.replicas import ReplicaEngine + return ReplicaEngine([SimpleNamespace(gen=1, batch=b) for b in batches]) + + def test_no_slots_behind_replicas(self): + self.assertFalse(batch_slots_on(self.replica(0, 0))) + self.assertFalse(batch_slots_on(SimpleNamespace(batch=0))) # no replicas: the engine's own figure + + def test_slots_behind_replicas(self): + self.assertTrue(batch_slots_on(self.replica(2, 3))) # every one of them + self.assertTrue(batch_slots_on(self.replica(0, 2))) # one is enough + self.assertTrue(batch_slots_on(SimpleNamespace(batch=4))) + + +class Span(unittest.TestCase): + def entries(self, *toks): + return [{"token": t} for t in toks] + + def test_span(self): + es = self.entries("```", "json", "\n", "{", "}", "\n", "```") + self.assertEqual([e["token"] for e in logprob_span("```json\n{}\n```", "{}", es)], ["{", "}"]) + self.assertEqual(len(logprob_span("{}", "{}", self.entries("{", "}"))), 2) + + def test_no_span(self): + self.assertIsNone(logprob_span("x{}", "{}", self.entries("x{", "}"))) # no boundary at the start + self.assertIsNone(logprob_span("{}x", "{}", self.entries("{", "}x"))) # none at the end + self.assertIsNone(logprob_span("{}", "{}", self.entries("{"))) # do not spell it + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_logprobs_parallel.py b/serve/test_logprobs_parallel.py new file mode 100644 index 00000000..cc494aa3 --- /dev/null +++ b/serve/test_logprobs_parallel.py @@ -0,0 +1,117 @@ +"""Logprobs with "parallel" (batch slots): python -m unittest serve.test_logprobs_parallel. + +The fake engine of serve/test_parallel.py behind the real StrataEngine and Service, writing an LP line after each +T line when the GEN / BGEN line asks for logprobs. A typed decision (max_tokens 1) is read on the control lines +(an admission: BGEN, one T, DONE, BADM 0) and gets its logprobs; longer replies are refused with a 400, since the +slot's BT lines carry none. +""" +import json +import threading +import unittest +import urllib.error +import urllib.request +from unittest import mock + +import serve.test_parallel as tp + +# LP after each T when asked: the token's log-probability is -(prompt length) / 1000 (so two requests can be told +# apart) and "A" (65) is its one alternative at -1.5 -- or the named ids themselves, at -1, when the line carries +# `allowed=` (the engine's own branch: it prints those and no top-K) +_T_LINE = ' print(f"T {t}", flush=True)\n' +assert tp.FAKE_BATCH.count(_T_LINE) == 1 +FAKE_LP = tp.FAKE_BATCH.replace(_T_LINE, _T_LINE + ( + ' if " logprobs=" in line:\n' + ' al = [x[8:] for x in line.split() if x.startswith("allowed=")]\n' + ' cs = (" " + " ".join(i + ":-1.000000" for i in al[0].split(","))) if al else " 65:-1.500000"\n' + ' print(f"LP {-len(ids) / 1000:.6f}" + cs, flush=True)\n')) + + +class LogprobsWithBatchSlots(unittest.TestCase): + start, tearDown, get = tp.ParallelService.start, tp.ParallelService.tearDown, tp.ParallelService.get + + def start_lp(self, fake=FAKE_LP, slots=2): + with mock.patch.object(tp, "FAKE_BATCH", fake): + self.start(slots) + + def chat(self, text, max_tokens=1, logprobs=True, allowed=None): + body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, + "reasoning_effort": "none"} + if logprobs: + body |= {"logprobs": True, "top_logprobs": 1} + if allowed: + body["allowed_token_ids"] = allowed + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=60) as r: + return json.loads(r.read().decode()) + + @staticmethod + def entries(reply): + return ((reply["choices"][0].get("logprobs") or {}).get("content")) or [] + + def test_a_decision_gets_its_logprobs(self): + self.start_lp() + r = self.chat("Is it A or B?") + self.assertEqual(r["choices"][0]["message"]["content"], "o") + e = self.entries(r) + self.assertEqual(len(e), 1) + self.assertEqual(e[0]["token"], "o") + self.assertLess(e[0]["logprob"], 0) + self.assertEqual(e[0]["top_logprobs"], [{"token": "A", "logprob": -1.5, "bytes": [65]}]) + self.assertTrue(any(x.startswith("BGEN") for x in self.log.read_text().splitlines())) # an admission + + def test_the_named_ids_reach_the_slot_and_are_what_is_reported(self): + # allowed_token_ids travels in the same BGEN keys as logprobs, so the engine's own branch answers with + # exactly those ids: the admission path carries the whole feature, not just the top-K one + self.start_lp() + e = self.entries(self.chat("Is it A or B?", allowed=[65])) + self.assertEqual(len(e), 1) + self.assertEqual([x["token"] for x in e[0]["top_logprobs"]], ["A"]) + self.assertEqual(e[0]["top_logprobs"][0]["logprob"], 0) # the whole distribution: just that id + + def test_two_at_once_each_get_their_own(self): + self.start_lp() + short, long_ = "A or B?", "A or B? " + "x" * 300 + alone = {t: self.entries(self.chat(t))[0]["logprob"] for t in (short, long_)} + self.assertNotEqual(alone[short], alone[long_]) + for _ in range(5): + got, errs = {}, [] + + def run(t): + try: + got[t] = self.entries(self.chat(t))[0]["logprob"] + except Exception as exc: # noqa: BLE001 - reported below + errs.append(repr(exc)) + th = [threading.Thread(target=run, args=(t,)) for t in (short, long_, short, long_)] + for x in th: + x.start() + for x in th: + x.join(60) + self.assertEqual(errs, []) + self.assertEqual(got, alone) + + def test_not_asked_nothing_changes(self): + self.start_lp() + r = self.chat("Is it A or B?", logprobs=False) + self.assertEqual(r["choices"][0]["message"]["content"], "o") + self.assertIsNone(r["choices"][0].get("logprobs")) + + def test_longer_replies_are_refused_with_batch_slots(self): + self.start_lp() + with self.assertRaises(urllib.error.HTTPError) as cm: + self.chat("Is it A or B?", max_tokens=8) + self.assertEqual(cm.exception.code, 400) + self.assertIn("max_tokens 1", cm.exception.read().decode()) + # the server is still serving, and a reply that does not ask is untouched + self.assertEqual(self.chat("still serving?", max_tokens=16, logprobs=False)["choices"][0]["message"]["content"], + "ok, done.") + + def test_an_engine_without_lp_lines(self): + self.start_lp(fake=tp.FAKE_BATCH) # an older engine: the key is ignored, no LP line at all + r = self.chat("Is it A or B?") + self.assertEqual(r["choices"][0]["message"]["content"], "o") + self.assertEqual(self.entries(r), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_mcp.py b/serve/test_mcp.py index 2c414ef0..055089d9 100644 --- a/serve/test_mcp.py +++ b/serve/test_mcp.py @@ -365,14 +365,98 @@ class ToolLoop(unittest.TestCase): self.assertNotIn("y" * 501, second) def test_max_rounds(self): - self.start(call_script("fake__echo", text="again")) # the model never stops calling + self.start(call_script("fake__echo", text="first result"), + call_script("fake__echo", text="second result"), "\n\nSummary of both results.") code, text = self.post({"strata_mcp": True}) - mcp = [c["strata_mcp"] for c in self.chunks(text) if "strata_mcp" in c] - self.assertEqual(len(self.engine.prompts), 3) # 2 rounds of tools, then the limit + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + mcp = [chunk["strata_mcp"] for chunk in chunks if "strata_mcp" in chunk] + self.assertEqual(len(self.engine.prompts), 3) self.assertEqual(sum(m["event"] == "call" for m in mcp), 2) self.assertIn({"event": "limit", "max_rounds": 2}, mcp) - self.assertTrue(mcp[-1].get("skipped")) - self.assertEqual(self.chunks(text)[-1]["choices"][0]["finish_reason"], "stop") + self.assertFalse(any(m.get("skipped") for m in mcp)) + self.assertIn("Summary of both results.", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + final_prompt = self.engine.prompt_text(2) + self.assertIn("\nfirst result\n", final_prompt) + self.assertIn("\nsecond result\n", final_prompt) + self.assertIn("No tools are available for this final reply", final_prompt) + self.assertNotIn("", final_prompt) + self.assertEqual(chunks[-1]["choices"][0]["finish_reason"], "stop") + self.assertEqual(chunks[-1]["usage"]["prompt_tokens"], len(self.engine.prompts[2])) + + def test_max_rounds_non_stream_with_existing_system(self): + self.hub.settings["max_rounds"] = 1 + self.start(call_script("fake__add", a=2, b=3), "\n\nThe result is 5.") + code, text = self.post({"strata_mcp": True, "messages": [ + {"role": "system", "content": "Keep answers concise."}, + {"role": "developer", "content": "Use the provided evidence."}, + {"role": "user", "content": "Add 2 and 3."}]}, stream=False) + self.assertEqual(code, 200, text) + response = json.loads(text) + self.assertIn("The result is 5.", response["choices"][0]["message"]["content"]) + final_prompt = self.engine.prompt_text(1) + self.assertIn("Keep answers concise.", final_prompt) + self.assertIn("Use the provided evidence.", final_prompt) + self.assertIn("\n5\n", final_prompt) + self.assertNotIn("", final_prompt) + + def test_max_rounds_counts_rounds_with_multiple_calls(self): + self.hub.settings["max_rounds"] = 1 + self.start(call_script("fake__echo", text="source A") + "\n" + + call_script("fake__echo", text="source B"), "\n\nBoth sources agree.") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + mcp = [chunk["strata_mcp"] for chunk in chunks if "strata_mcp" in chunk] + calls = [event for event in mcp if event["event"] == "call"] + self.assertEqual([event["round"] for event in calls], [1, 1]) + self.assertEqual(len(self.engine.prompts), 2) + self.assertIn("\nsource A\n", self.engine.prompt_text(1)) + self.assertIn("\nsource B\n", self.engine.prompt_text(1)) + self.assertIn("Both sources agree.", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + + def test_sixteen_rounds_then_final_answer(self): + self.hub.settings["max_rounds"] = 16 + scripts = [call_script("fake__echo", text=f"source {index}") for index in range(16)] + self.start(*scripts, "\n\nSummary after sixteen rounds.") + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + mcp = [chunk["strata_mcp"] for chunk in chunks if "strata_mcp" in chunk] + self.assertEqual(sum(event["event"] == "call" for event in mcp), 16) + self.assertIn({"event": "limit", "max_rounds": 16}, mcp) + self.assertEqual(len(self.engine.prompts), 17) + final_prompt = self.engine.prompt_text(16) + self.assertIn("\nsource 0\n", final_prompt) + self.assertIn("\nsource 15\n", final_prompt) + self.assertNotIn("", final_prompt) + self.assertIn("Summary after sixteen rounds.", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + + def test_max_rounds_preserves_errors_and_disables_client_tools(self): + self.hub.settings["max_rounds"] = 1 + own = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}] + self.start(call_script("fake__fail"), "\n\nThe source failed; here is what is known.") + code, text = self.post({"strata_mcp": True, "tools": own}) + self.assertEqual(code, 200, text) + chunks = self.chunks(text) + self.assertFalse(any(chunk["choices"][0]["delta"].get("tool_calls") for chunk in chunks)) + self.assertIn("error: it failed on purpose", self.engine.prompt_text(1)) + self.assertNotIn("", self.engine.prompt_text(1)) + self.assertIn("here is what is known", "".join(chunk["choices"][0]["delta"].get("content", "") + for chunk in chunks)) + + def test_max_rounds_does_not_execute_more_calls(self): + self.hub.settings["max_rounds"] = 1 + self.start(call_script("fake__echo", text="known"), call_script("fake__echo", text="must not run")) + code, text = self.post({"strata_mcp": True}) + self.assertEqual(code, 200, text) + self.assertEqual(len(self.engine.prompts), 2) + mcp = [chunk["strata_mcp"] for chunk in self.chunks(text) if "strata_mcp" in chunk] + self.assertEqual(sum(event["event"] == "call" for event in mcp), 1) + self.assertNotIn("must not run", Path(self.log.name).read_text()) def test_stop_during_a_tool(self): """Closing the connection while a slow tool runs stops the tool (notifications/cancelled) and the loop.""" diff --git a/serve/test_mcp_media.py b/serve/test_mcp_media.py new file mode 100644 index 00000000..25a53bf3 --- /dev/null +++ b/serve/test_mcp_media.py @@ -0,0 +1,289 @@ +"""Raster MCP delivery: cache bounds, authenticated downloads and vision forwarding; no GPU.""" +import base64 +import json +import tempfile +import unittest +import urllib.error +import urllib.request +from pathlib import Path +from unittest.mock import patch +from serve.mcp import cache_images, hub_from_config +from serve.frontend import ChatTemplate, images_of +from serve.server import ByteTokenizer, Service, serve +from serve.test_mcp import ScriptedEngine, call_script +from serve import test_mcp as fixtures +PNG = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jB0kAAAAASUVORK5CYII=') + +def image(data=PNG, mime='image/png'): + return {'type': 'image', 'mimeType': mime, 'data': base64.b64encode(data).decode()} + +class Configuration(unittest.TestCase): + def test_documented_switch_reaches_hub_and_tool_result(self): + hub = hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, + 'mcp': {'image_results': True}}) + self.assertTrue(hub.settings['image_results']) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + with tempfile.TemporaryDirectory() as tmp: + hub.media_dir = Path(tmp) + with patch.object(server, 'call', return_value={'content': [image()]}): + result = hub.call('fake__image', {}) + self.assertEqual(len(result['images']), 1) + self.assertEqual(result['model_content'][1]['type'], 'image') + + def test_disabled_and_omitted_switch_stay_off(self): + for settings in ({}, {'image_results': False}): + with self.subTest(settings=settings): + hub = hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, 'mcp': settings}) + self.assertFalse(hub.settings['image_results']) + + def test_switch_rejects_non_booleans(self): + for value in ('true', 'false', 0, 1, None, [], {}): + with self.subTest(value=value), self.assertRaisesRegex(SystemExit, 'expected a boolean'): + hub_from_config({'mcp_servers': {'fake': {'command': 'unused'}}, + 'mcp': {'image_results': value}}) + +class Cache(unittest.TestCase): + + def test_image_text_obeys_result_cap(self): + from serve.mcp import McpHub + hub = McpHub({'fake': {'command': 'unused'}}, {'max_result_chars': 1000, 'image_results': True}) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + with tempfile.TemporaryDirectory() as tmp: + hub.media_dir = Path(tmp) + with patch.object(server, 'call', return_value={'content': [{'type': 'text', 'text': 'x' * 100000}, image()]}): + result = hub.call('fake__image', {}) + self.assertTrue(result['truncated']) + self.assertLessEqual(len(result['model_content'][0]['text']), len(result['text'])) + self.assertNotIn('x' * 1001, result['model_content'][0]['text']) + self.assertEqual(len(result['images']), 1) + + def test_disabled_is_identical_to_text_only_result(self): + from serve.mcp import McpHub, result_text + hub = McpHub({'fake': {'command': 'unused'}}) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + result = {'content': [{'type': 'text', 'text': 'hello'}, image()]} + with tempfile.TemporaryDirectory() as tmp: + hub.media_dir = Path(tmp) / 'unused' + with patch.object(server, 'call', return_value=result), patch('serve.mcp.cache_images') as cache: + output = hub.call('fake__image', {}) + cache.assert_not_called() + self.assertEqual(output['text'], result_text(result)) + self.assertNotIn('images', output) + self.assertNotIn('model_content', output) + self.assertFalse(hub.media_dir.exists()) + + def test_cache_failure_keeps_text_result(self): + from serve.mcp import McpHub + hub = McpHub({'fake': {'command': 'unused'}}, {'image_results': True}) + server = hub.servers['fake'] + server.status = 'ready' + server.tools = [{'name': 'image', 'inputSchema': {}}] + hub.media_dir = Path('unused') + with patch.object(server, 'call', return_value={'content': [{'type': 'text', 'text': 'hello'}, image()]}), patch('serve.mcp.cache_images', side_effect=OSError('disk full')): + output = hub.call('fake__image', {}) + self.assertTrue(output['ok']) + self.assertIn('hello', output['text']) + self.assertNotIn('model_content', output) + + def test_null_and_non_object_content(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(cache_images({'content': None}, tmp), []) + self.assertEqual(cache_images({'content': [None, False, 'bad', image()]}, tmp), cache_images({'content': [image()]}, tmp)) + + def test_cache_deduplicates_and_preserves_bytes(self): + with tempfile.TemporaryDirectory() as tmp: + a = cache_images({'content': [image()]}, tmp) + b = cache_images({'content': [image()]}, tmp) + self.assertEqual(a, b) + self.assertEqual(len(list(Path(tmp).iterdir())), 1) + self.assertEqual((Path(tmp) / a[0]['url'].split('/')[-1]).read_bytes(), PNG) + + def test_rejects_invalid_and_active_content(self): + with tempfile.TemporaryDirectory() as tmp: + blocks = [image(b'not a PNG'), image(b'', 'image/svg+xml'), {'type': 'image', 'mimeType': 'image/png', 'data': '***'}] + self.assertEqual(cache_images({'content': blocks}, tmp), []) + + def test_caps_images_per_result(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(len(cache_images({'content': [image()] * 8}, tmp)), 4) + + def test_authenticated_download_and_traversal(self): + with tempfile.TemporaryDirectory() as tmp: + media = cache_images({'content': [image()]}, tmp)[0] + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + + class Hub: + media_dir = tmp + svc.mcp = Hub() + svc.api_key = 'test-key' + httpd = serve(svc, port=0) + base = f'http://127.0.0.1:{httpd.server_address[1]}/' + try: + with self.assertRaises(urllib.error.HTTPError) as error: + urllib.request.urlopen(base + media['url']) + self.assertEqual(error.exception.code, 401) + req = urllib.request.Request(base + media['url'], headers={'Authorization': 'Bearer test-key'}) + with urllib.request.urlopen(req) as response: + self.assertEqual(response.read(), PNG) + self.assertEqual(response.headers['Content-Type'], 'image/png') + req = urllib.request.Request(base + 'tool-media/../../secret.png', headers={'Authorization': 'Bearer test-key'}) + with self.assertRaises(urllib.error.HTTPError) as error: + urllib.request.urlopen(req) + self.assertEqual(error.exception.code, 404) + finally: + httpd.shutdown() + httpd.server_close() + +class HistoryReferences(unittest.TestCase): + + def test_reference_resolves_only_to_cache(self): + with tempfile.TemporaryDirectory() as tmp: + im = cache_images({'content': [image()]}, tmp)[0] + name = im['url'].split('/')[-1] + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + + class Hub: + media_dir = tmp + svc.mcp = Hub() + message = [{'role': 'tool', 'content': [{'type': 'image', 'source': 'strata-tool-media:' + name}]}] + with patch.object(svc, '_note_unreadable_tool_images', return_value={}): + with self.assertRaisesRegex(ValueError, 'without the vision encoder'): + svc.prepare(message, [], {}, 16) + self.assertEqual(images_of(message), [str(Path(tmp) / name)]) + + def test_mixed_missing_and_valid_pictures_keeps_valid_vision(self): + with tempfile.TemporaryDirectory() as tmp: + media = cache_images({'content': [image()]}, tmp)[0] + source = str(Path(tmp) / media['url'].split('/')[-1]) + rows = Path(tmp) / 'img.sve' + rows.write_bytes(b'rows') + class Vision: + dir = Path(tmp) + + def encode(self, value): + if value != source: + raise AssertionError('Only the valid cached image may reach the encoder') + return rows, 3 + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, + ChatTemplate(Path(__file__).parent / 'chat_template.jinja'), vision=Vision()) + class Hub: + media_dir = tmp + svc.mcp = Hub() + messages = [{'role': 'tool', 'content': [ + {'type': 'text', 'text': 'Retain this text.'}, + {'type': 'image', 'source': 'strata-tool-media:' + '0' * 64 + '.png'}, + {'type': 'image', 'source': 'strata-tool-media:' + media['url'].split('/')[-1]}]}] + try: + ids, _, _ = svc.prepare(messages, [], {}, 16) + prompt = tok.decode(ids) + self.assertIn('Retain this text.', prompt) + self.assertIn('[image omitted:', prompt) + self.assertEqual(images_of(messages), [source]) + self.assertEqual(ids.count(tok.encode('<|image_pad|>', parse_special=True)[0]), 3) + finally: + if svc.embeddings.path: + svc.embeddings.path.unlink(missing_ok=True) + + def test_bad_reference_cannot_read_other_files(self): + tok = ByteTokenizer() + svc = Service(ScriptedEngine(tok, ['OK']), tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + with self.assertRaisesRegex(ValueError, 'invalid tool image reference'): + svc.prepare([{'role': 'tool', 'content': [{'type': 'image', 'source': 'strata-tool-media:../../secret.png'}]}], [], {}, 16) + +class ImageLoop(unittest.TestCase): + setUp = fixtures.ToolLoop.setUp + tearDown = fixtures.ToolLoop.tearDown + start = fixtures.ToolLoop.start + post = fixtures.ToolLoop.post + chunks = staticmethod(fixtures.ToolLoop.chunks) + + def check_stale_history(self, state): + self.start('\n\nText reply survives.') + with tempfile.TemporaryDirectory() as tmp: + self.hub.media_dir = Path(tmp) if state == 'missing' else None + if state == 'no_hub': + self.svc.mcp = None + history = [ + {'role': 'user', 'content': 'Create a picture'}, + {'role': 'assistant', 'content': '', 'tool_calls': [ + {'id': 'old', 'type': 'function', 'function': {'name': 'fake__echo', 'arguments': '{}'}}]}, + {'role': 'tool', 'tool_call_id': 'old', 'content': [ + {'type': 'text', 'text': 'Keep this original tool text.'}, + {'type': 'image_url', 'image_url': {'url': 'strata-tool-media:' + '0' * 64 + '.png'}}]}, + {'role': 'user', 'content': 'Continue with text only'}] + # API clients resend the original unmodified history on every later turn. + for turn in range(2): + for stream in (False, True): + with self.subTest(state=state, turn=turn, stream=stream): + code, text = self.post({'messages': history}, stream=stream) + self.assertEqual(code, 200, text) + if stream: + answer = ''.join(c['choices'][0]['delta'].get('content', '') for c in self.chunks(text)) + else: + answer = json.loads(text)['choices'][0]['message']['content'] + self.assertIn('Text reply survives.', answer) + prompt = self.engine.prompt_text(turn * 2 + int(stream)) + self.assertIn('Keep this original tool text.', prompt) + self.assertIn('[image omitted:', prompt) + self.assertNotIn('strata-tool-media:', prompt) + + def test_missing_cache_history_continues_across_turns(self): + self.check_stale_history('missing') + + def test_disabled_cache_history_continues_across_turns(self): + self.check_stale_history('disabled') + + def test_removed_mcp_history_continues_across_turns(self): + self.check_stale_history('no_hub') + + def test_malformed_history_still_rejected_over_http(self): + self.start('\n\nShould not run.') + self.svc.mcp = None + for name in ('../../secret.png', 'a' * 64 + '.svg', 'A' * 64 + '.png', 'short.png'): + with self.subTest(name=name): + code, text = self.post({'messages': [{'role': 'tool', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'strata-tool-media:' + name}}]}]}, stream=False) + self.assertEqual(code, 400) + self.assertIn('invalid tool image reference', text) + self.assertEqual(self.engine.prompts, []) + + def test_default_stream_has_no_image_fields(self): + self.start(call_script('fake__echo', text='hello'), '\n\nDone.') + code, text = self.post({'strata_mcp': True}) + self.assertEqual(code, 200) + event = [c['strata_mcp'] for c in self.chunks(text) if c.get('strata_mcp', {}).get('event') == 'result'][0] + self.assertEqual(set(event), {'event', 'id', 'ok', 'text', 'chars', 'truncated', 'ms'}) + + def test_image_result_streams_and_reaches_vision_prepare(self): + with tempfile.TemporaryDirectory() as tmp: + self.hub.settings['image_results'] = True + self.hub.media_dir = Path(tmp) + im = cache_images({'content': [image()]}, tmp) + source = str(Path(tmp) / im[0]['url'].split('/')[-1]) + self.start(call_script('fake__echo', text='picture'), '\n\nImage received.') + self.svc.vision = object() + native = self.svc.prepare + seen = [] + + def prepare(messages, *args, **kwargs): + seen.extend(images_of(messages)) + clean = [{**m, 'content': 'image delivered'} if isinstance(m.get('content'), list) else m for m in messages] + return native(clean, *args, **kwargs) + result = {'ok': True, 'text': 'image delivered', 'chars': 15, 'truncated': False, 'ms': 1, 'images': im, 'model_content': [{'type': 'text', 'text': 'image delivered'}, {'type': 'image', 'source': source}]} + with patch.object(self.hub, 'call', return_value=result), patch.object(self.svc, 'prepare', side_effect=prepare): + code, text = self.post({'strata_mcp': True}) + self.assertEqual(code, 200) + self.assertIn(source, seen) + events = [c['strata_mcp'] for c in self.chunks(text) if 'strata_mcp' in c] + self.assertEqual(events[-1]['images'], im) + answer = ''.join((c['choices'][0]['delta'].get('content', '') for c in self.chunks(text))) + self.assertIn('Image received.', answer) diff --git a/serve/test_responses.py b/serve/test_responses.py index d6c4e857..866582c3 100644 --- a/serve/test_responses.py +++ b/serve/test_responses.py @@ -389,6 +389,21 @@ class OverHttp(Server): code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": 5, "stream": True}) self.assertEqual(events[-1]["type"], "response.incomplete") + def test_max_output_tokens_zero_and_minus_one_mean_no_cap(self): + # #4036: the documented "no cap" values; the answer is complete, not cut at the cap + for n in (0, -1): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n}) + self.assertEqual((code, r["status"]), (200, "completed"), (n, r)) + self.assertIsNone(r["incomplete_details"]) + code, events = self.post({"model": "m", "input": "hi", "max_output_tokens": n, "stream": True}) + self.assertEqual((code, events[-1]["type"]), (200, "response.completed"), n) + + def test_max_output_tokens_bad_values_are_400(self): + for n in (-2, -100, 1.5, True, "5"): + code, r = self.post({"model": "m", "input": "hi", "max_output_tokens": n}) + self.assertEqual(code, 400, (n, r)) + self.assertEqual(r["error"]["param"], "max_output_tokens", n) + def test_effort_none_does_not_think(self): self.engine.scripts = [self.tok.encode("Hello.<|im_end|>", parse_special=True)] self.engine.script = self.engine.scripts[0] diff --git a/serve/test_security.py b/serve/test_security.py index 4b00f440..0fb695e7 100644 --- a/serve/test_security.py +++ b/serve/test_security.py @@ -12,12 +12,13 @@ import json import socket import sys import unittest +from http.server import BaseHTTPRequestHandler from pathlib import Path from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 -from serve.server import (ByteTokenizer, MockEngine, Service, allowed_hosts_of, host_allowed, # noqa: E402 +from serve.server import (ByteTokenizer, MockEngine, Server, Service, allowed_hosts_of, host_allowed, # noqa: E402 host_name, host_names_for, origin_allowed, serve) ROOT = Path(__file__).resolve().parents[1] @@ -57,6 +58,41 @@ class HostNames(unittest.TestCase): self.assertNotIn("*", names) +class ListenAddress(unittest.TestCase): + def test_ipv4_address_family(self): + with Server(("127.0.0.1", 0), BaseHTTPRequestHandler, bind_and_activate=False) as s: + self.assertEqual(s.address_family, socket.AF_INET) + + @unittest.skipUnless(socket.has_ipv6, "IPv6 is not available") + def test_ipv6_loopback(self): + for host in ("::1", "2001:db8::7"): + try: + with Server((host, 0), BaseHTTPRequestHandler, bind_and_activate=False) as s: + self.assertEqual(s.address_family, socket.AF_INET6) + except OSError as e: + self.skipTest(f"IPv6 socket is not available: {e}") + tok = ByteTokenizer() + svc = Service(MockEngine(tok, "\n\nok", max_context=4096), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + try: + httpd = serve(svc, host="::", port=0) + except OSError as e: + self.skipTest(f"IPv6 loopback is not available: {e}") + try: + self.assertEqual(httpd.address_family, socket.AF_INET6) + c = http.client.HTTPConnection("::1", httpd.server_address[1], timeout=10) + try: + c.request("GET", "/health") + r = c.getresponse() + self.assertEqual(r.status, 200) + r.read() + finally: + c.close() + finally: + httpd.shutdown() + httpd.server_close() + + class HostCheck(unittest.TestCase): def test_accepted(self): for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]", diff --git a/serve/test_server.py b/serve/test_server.py index 3e60dee4..09c88024 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3808,6 +3808,19 @@ class UsageAndStatus(unittest.TestCase): self.assertEqual(last["usage"]["prompt_tokens_details"]["cached_tokens"], ClockedEngine.REUSED) self.assertEqual(last["timings"]["cache_n"], ClockedEngine.REUSED) + def test_responses(self): + # /v1/responses carries the same top-level timings as /v1/chat/completions + body = {"model": "x", "max_output_tokens": 20, "input": "hi"} + status, raw = self.request("/v1/responses", body) + self.assertEqual(status, 200) + r = json.loads(raw) + self.assertEqual(r["timings"]["cache_n"], ClockedEngine.REUSED) + self.assertEqual(r["timings"]["predicted_n"], r["usage"]["output_tokens"]) + status, raw = self.request("/v1/responses", {**body, "stream": True}) + last = [json.loads(line[6:]) for line in raw.decode().splitlines() if line.startswith("data: {")][-1] + self.assertIn(last["type"], ("response.completed", "response.incomplete")) + self.assertAlmostEqual(last["timings"]["predicted_per_second"], 50.0, delta=0.1) # 20 ms a token + def test_anthropic(self): u = self.chat("/v1/messages")["usage"] self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) @@ -4521,6 +4534,74 @@ class ForcedToolChoice(unittest.TestCase): self.assertIn("Here is the report.", content) self.assertIn("", content) + def _undeclared_call_answer(self, name="lookup"): + from serve.frontend import CALL_END, CALL_START + return ("I will check that.\n" + CALL_START + f"\n\n\n2+2\n\n" + "\n" + CALL_END) + + def _rejected_of(self, b, stream): + """The strata_rejected_tool_calls of a whole reply or of a streamed one (None when the reply has none).""" + if not stream: + return b.get("strata_rejected_tool_calls") + found = [json.loads(line[6:]).get("strata_rejected_tool_calls") for line in b.splitlines() if line.startswith("data: {")] + found = [f for f in found if f] + self.assertLessEqual(len(found), 1, "sent once, with the last chunk") + return found[0] if found else None + + def test_an_undeclared_call_is_named_in_the_response(self): + """#3796: the call stays text and finish_reason stays "stop"; the response also lists the names the model wrote + (strata_rejected_tool_calls), so a client can tell this from an ordinary answer and answer the model.""" + self.says(self._undeclared_call_answer("execute_gdscript")) + for stream in (False, True): + with self.subTest(stream=stream): + before = self.svc.totals.get("tool_calls_unread", 0) + code, b = self.openai(stream=stream) + finish, calls, _ = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("stop", []), b) + self.assertEqual(self._rejected_of(b, stream), [{"name": "execute_gdscript", "reason": "undeclared"}]) + self.assertEqual(self.svc.totals["tool_calls_unread"], before + 1) # /metrics counts it + if not stream: + self.assertIn("", b["choices"][0]["message"]["content"]) # the text is untouched + + def test_no_marker_when_nothing_was_rejected(self): + """An ordinary answer and a declared call carry no extra field: the API is what it was.""" + from serve.frontend import CALL_END, CALL_START + for label, answer in (("text", "The answer is 4."), + ("declared call", CALL_START + "\n\n\n2+2\n\n\n" + CALL_END)): + self.says(answer) + for stream in (False, True): + with self.subTest(case=label, stream=stream): + code, b = self.openai(stream=stream) + self.call_of(code, b, stream) + self.assertIsNone(self._rejected_of(b, stream)) + if stream: + self.assertNotIn("strata_rejected_tool_calls", b) + + def test_a_collapsed_mcp_name_is_a_call_not_a_rejection(self): + """#3796: `mcp_playwright_browser_navigate` for the declared `mcp__playwright__browser_navigate`.""" + from serve.frontend import CALL_END, CALL_START + tools = [{"type": "function", "function": {"name": "mcp__playwright__browser_navigate", "description": "open a page", + "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}}}] + self.says(CALL_START + "\n\n\nx\n\n\n" + CALL_END) + for stream in (False, True): + with self.subTest(stream=stream): + code, b = self.openai(stream=stream, tools=tools) + finish, calls, _ = self.call_of(code, b, stream) + self.assertEqual((finish, calls), ("tool_calls", [("mcp__playwright__browser_navigate", {"q": "x"})])) + self.assertIsNone(self._rejected_of(b, stream)) + + def test_the_anthropic_reply_names_the_rejected_call_too(self): + self.says(self._undeclared_call_answer("bash")) + body = {"model": "m", "max_tokens": 400, "messages": [{"role": "user", "content": "2+2?"}], + "tools": [{"name": "search", "description": "search", "input_schema": {"type": "object", "properties": {}}}]} + req = urllib.request.Request(self.base + "/v1/messages", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + msg = json.loads(r.read().decode()) + self.assertEqual(msg["stop_reason"], "end_turn") + self.assertEqual(msg["strata_rejected_tool_calls"], [{"name": "bash", "reason": "undeclared"}]) + self.assertFalse([c for c in msg["content"] if c["type"] == "tool_use"]) + def test_a_call_with_a_dropped_function_keyword_is_still_the_call(self): """#3441: `<=search>` for ``, as a model under a large tool surface writes it.""" from serve.frontend import CALL_END, CALL_START diff --git a/serve/test_structured.py b/serve/test_structured.py index 6b66cf8b..f0e2c74a 100644 --- a/serve/test_structured.py +++ b/serve/test_structured.py @@ -112,6 +112,41 @@ class Structured(unittest.TestCase): # Plain text callers retain normal streaming, without a JSON validation gate. self.assertEqual(self.chat("Prose.", response_format={"type": "text"})[0], 200) + def test_latex_escape_repair_is_opt_in_and_only_after_a_strict_failure(self): + # #2893: \alpha is not a JSON escape. Off by default: still a 502. On: one retry after the strict parse failed. + bad = r'{"answer":"the angle \alpha and \gamma_0"}' + self.assertEqual(self.chat(bad, response_format={"type": "json_object"})[0], 502) + self.assertEqual(self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": False})[0], 502) + code, reply = self.chat(bad, response_format={"type": "json_object", "repair_latex_escapes": True}) + self.assertEqual(code, 200) + self.assertEqual(json.loads(reply["choices"][0]["message"]["content"]), + {"answer": "the angle \\alpha and \\gamma_0"}) + # streaming asks for the same check before any content leaves + _, raw = self.chat(bad, stream=True, response_format={"type": "json_object", "repair_latex_escapes": True}) + self.assertIn(r"\\alpha", raw) + # the repair does not hide what is wrong with the answer itself + fmt = {"type": "json_object", "repair_latex_escapes": True} + for script in ('[]', r'{"x":NaN}', r'{"a":"\alpha","a":2}', 'no json at all', r'{"x":"\alpha'): + self.assertEqual(self.chat(script, response_format=fmt)[0], 502, script) + self.assertEqual(self.chat(r'{"answer":"\alpha"}', response_format=fmt, max_tokens=5)[0], 502) + + def test_latex_escape_repair_helper(self): + fix = structured.repair_latex_escapes + self.assertEqual(fix(r'{"a":"\alpha \gamma_0"}'), r'{"a":"\\alpha \\gamma_0"}') + for same in (r'{"a":"x\ny\t\"q\" \\ \/ \u00e9"}', '{"a": 1}', ''): + self.assertEqual(fix(same), same) + self.assertEqual(fix(r'{"a":"\u12"}'), r'{"a":"\\u12"}') # \u without four hex digits + self.assertEqual(fix(r'{"a":"\\alpha"}'), r'{"a":"\\alpha"}') # an escaped backslash is skipped as a pair + self.assertEqual(fix("\\"), "\\\\") # a lone trailing backslash + # \b is a valid escape: untouched, so it parses (as a backspace), as it does without the option + self.assertEqual(json.loads(fix(r'{"a":"\beta \alpha"}'))["a"], "\beta \\alpha") + + def test_the_repair_option_reaches_the_responses_format(self): + from serve.responses import text_format + self.assertEqual(text_format({"text": {"format": {"type": "json_object", "repair_latex_escapes": True}}}), + {"type": "json_object", "repair_latex_escapes": True}) + self.assertEqual(text_format({"text": {"format": {"type": "json_object"}}}), {"type": "json_object"}) + def test_rejected_schema_does_not_load_the_engine_or_retry(self): with mock.patch.object(self.svc, "load") as load: code, _ = self.chat(response_format={"type": "json_schema"}) diff --git a/serve/test_tool_name_alias.py b/serve/test_tool_name_alias.py index 1ceda8b8..5efc8365 100644 --- a/serve/test_tool_name_alias.py +++ b/serve/test_tool_name_alias.py @@ -193,5 +193,69 @@ class DriftedMcpNames(unittest.TestCase): self.assertNotIn("namespace", calls[0]) +def plain_tool(name): + return {"name": name, "parameters": {"type": "object", "properties": {"url": {"type": "string"}}}} + + +def call_text(name, param="url", value="https://example.com"): + return f"\n\n\n{value}\n\n\n" + + +def run_parser(text, tools, width=0): + parser = OutputParser(thinking=False, tools=tools, stream_tools=True, declared_only=True) + evs = [] + step = width or len(text) or 1 + for k in range(0, len(text), step): + evs += parser.feed(text[k:k + step]) + evs += parser.finish("stop") + return evs, parser + + +class CollapsedUnderscoreNames(unittest.TestCase): + """#3796: `mcp__server__tool` written as `mcp_server_tool` is a spelling of the declared tool (the same class of + difference as namespace__member). A name that is only similar stays text, and is named for the client.""" + MCP = [plain_tool("mcp__playwright__browser_navigate"), plain_tool("mcp__playwright__browser_snapshot"), + plain_tool("mcp__playwright__browser_tabs"), plain_tool("todo_write")] + + def test_the_collapsed_spelling_is_the_declared_tool(self): + for name in ("browser_navigate", "browser_snapshot", "browser_tabs"): + for width in (0, 1, 5): + with self.subTest(name=name, width=width): + evs, parser = run_parser("Opening it.\n" + call_text("mcp_playwright_" + name), self.MCP, width) + found = [e.call for e in evs if e.kind == "tool_call"] + self.assertEqual([c.name for c in found], ["mcp__playwright__" + name]) # the client gets the name it declared + self.assertEqual(found[0].arguments, {"url": "https://example.com"}) + self.assertEqual(text_of(evs).strip(), "Opening it.") + self.assertEqual((parser.unread, parser.unread_names), (0, [])) + + def test_the_declared_spelling_and_a_plain_tool_are_unchanged(self): + evs, _ = run_parser(call_text("mcp__playwright__browser_tabs") + "\n" + call_text("todo_write"), self.MCP) + self.assertEqual([e.call.name for e in evs if e.kind == "tool_call"], ["mcp__playwright__browser_tabs", "todo_write"]) + + def test_a_tool_declared_in_the_collapsed_spelling_wins(self): + tools = self.MCP + [plain_tool("mcp_playwright_browser_tabs")] + evs, _ = run_parser(call_text("mcp_playwright_browser_tabs"), tools) + self.assertEqual([e.call.name for e in evs if e.kind == "tool_call"], ["mcp_playwright_browser_tabs"]) + + def test_two_tools_with_the_same_collapsed_spelling_are_not_guessed(self): + tools = [plain_tool("a__b_c"), plain_tool("a_b__c")] + evs, parser = run_parser(call_text("a_b_c"), tools) + self.assertEqual([e for e in evs if e.kind == "tool_call"], []) + self.assertIn("a_b_c", text_of(evs)) + self.assertEqual(parser.unread_names, ["a_b_c"]) + + def test_a_reordered_or_renamed_tool_stays_text_and_is_named(self): + """The LibreChat case (`server1_label_values` for `label_values_mcp_server1`) and the bash/shell case: no guessing.""" + for declared, written in (("label_values_mcp_server1", "server1_label_values"), ("shell", "bash"), + ("godot_execute_gdscript", "execute_gdscript")): + for width in (0, 3): + with self.subTest(written=written, width=width): + raw = "Done.\n" + call_text(written) + evs, parser = run_parser(raw, [plain_tool(declared)], width) + self.assertEqual([e for e in evs if e.kind == "tool_call"], []) + self.assertEqual(text_of(evs), raw) # the text is exactly what the model wrote + self.assertEqual((parser.unread, parser.unread_names), (1, [written])) + + if __name__ == "__main__": unittest.main() diff --git a/serve/test_vision_elastic.py b/serve/test_vision_elastic.py index b8516b1a..fa16426c 100644 --- a/serve/test_vision_elastic.py +++ b/serve/test_vision_elastic.py @@ -2,13 +2,15 @@ expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts it on its own.""" +import contextlib +import io import tempfile import time import unittest from pathlib import Path from serve.frontend import ChatTemplate -from serve.server import ByteTokenizer, Service, Vision +from serve.server import ByteTokenizer, EngineDied, Service, Vision from serve.test_vram import VramEngine ROOT = Path(__file__).resolve().parents[1] @@ -99,6 +101,27 @@ class Elastic(unittest.TestCase): self.assertEqual(self.svc._vision_idle_down(), "down") self.assertEqual(self.engine.calls, [2048]) # the refused shrink only: nothing to give back + def test_an_encoder_that_fails_to_start_is_a_503_not_a_dropped_connection(self): + def fail(): + raise RuntimeError("the vision encoder did not start: cudaMalloc failed: out of memory") + self.vision.restart = fail + with self.assertRaises(EngineDied) as e: # the handlers answer EngineDied with a 503 + self.picture() + self.assertIn("the image encoder failed to start", str(e.exception)) + self.svc.last_image_at = 0 + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertEqual(self.engine.calls, [2048, 0]) # the share made for it goes back + + def test_the_stop_is_logged_when_the_cache_never_made_room(self): + self.engine.elastic = False # a layer split: the engine refuses --vram-elastic + self.picture() + self.svc.last_image_at = 0 + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(self.svc._vision_idle_down(), "down") + self.assertIn("the image encoder stopped after 60 s without a picture", out.getvalue()) + self.assertNotIn("expert cache", out.getvalue()) + def test_the_load_never_starts_an_elastic_encoder(self): self.assertFalse(self.svc._vision_down()) self.svc.vision = ElasticVision(tempfile.mkdtemp(), elastic=False) diff --git a/serve/test_vision_elastic_http.py b/serve/test_vision_elastic_http.py new file mode 100644 index 00000000..78b6df73 --- /dev/null +++ b/serve/test_vision_elastic_http.py @@ -0,0 +1,140 @@ +"""Elastic encoder failures reach clients, can be retried, and do not prevent recovery.""" +import json +from pathlib import Path +import sys +import tempfile +import unittest +import urllib.error +import urllib.request + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, Service, Vision, serve +from serve.test_vision_elastic import ElasticVision +from serve.test_vram import VramEngine + + +class EncoderFailureHTTP(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + tok = ByteTokenizer() + self.engine = VramEngine(tok) + self.engine.loaded = True + self.engine.elastic = False # as on a layer split: the cache cannot make room + self.vision = ElasticVision(tmp.name) + self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / 'chat_template.jinja'), + vision=self.vision) + httpd = serve(self.svc, port=0) + self.addCleanup(httpd.server_close) + self.addCleanup(httpd.shutdown) + self.addCleanup(self.drop_embeddings) + self.base = f'http://127.0.0.1:{httpd.server_address[1]}' + self.attempts = 0 + self.original_restart = self.vision.restart + + def drop_embeddings(self): + path = getattr(getattr(self.svc, 'embeddings', None), 'path', None) + if path is not None: + path.unlink(missing_ok=True) + + def post(self, path, body): + req = urllib.request.Request(self.base + path, json.dumps(body).encode(), + {'Content-Type': 'application/json'}) + return urllib.request.urlopen(req, timeout=10) + + @staticmethod + def chat_picture(): + return {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,eA=='}}]}]} + + def fail_with(self, error_type): + def fail(): + self.attempts += 1 + raise error_type('synthetic encoder startup failure') + self.vision.restart = fail + + def assert_503(self, path, body): + with self.assertRaises(urllib.error.HTTPError) as got: + self.post(path, body) + with got.exception as response: + self.assertEqual(response.code, 503) + payload = json.load(response) + self.assertIn('synthetic encoder startup failure', payload['error']['message']) + + def test_start_failure_and_retry_on_all_three_apis(self): + cases = [ + ('/v1/chat/completions', self.chat_picture()), + ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}), + ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [ + {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}), + ] + for error_type in (RuntimeError, OSError): + self.fail_with(error_type) + for path, body in cases: + for stream in (False, True): + for retry in range(2): + with self.subTest(error=error_type.__name__, path=path, stream=stream, retry=retry): + before = self.attempts + self.assert_503(path, {**body, 'stream': stream}) + self.assertEqual(self.attempts, before + 1) + + def test_text_requests_and_image_recovery_after_a_failed_start(self): + self.fail_with(RuntimeError) + text = {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]} + with self.post('/v1/chat/completions', text) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.attempts, 0) + self.assert_503('/v1/chat/completions', self.chat_picture()) + self.assertEqual(self.attempts, 1) + self.vision.restart = self.original_restart + with self.post('/v1/chat/completions', self.chat_picture()) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.vision.starts, 1) + with self.post('/v1/chat/completions', text) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertEqual(self.vision.starts, 1) + + @unittest.skipUnless(sys.platform.startswith('linux'), 'child reaping is checked through /proc') + def test_real_encoder_failure_retries_and_reaps_each_child(self): + with tempfile.TemporaryDirectory() as directory: + started = Path(directory) / 'started-pids' + executable = Path(directory) / 'encoder-exits' + executable.write_text( + '#!' + sys.executable + '\nimport os\n' + 'with open(' + repr(str(started)) + ', "a") as output:\n' + ' output.write(str(os.getpid()) + "\\n")\n' + 'raise SystemExit(71)\n') + executable.chmod(0o700) + vision = Vision({'exe': str(executable), 'mmproj': 'unused', 'model': 'unused', + 'elastic': True}, lazy=True) + self.addCleanup(vision.unload) + self.svc.vision = vision + cases = [ + ('/v1/chat/completions', self.chat_picture()), + ('/v1/messages', {'model': 'm', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': [ + {'type': 'image', 'source': {'type': 'base64', 'media_type': 'image/png', 'data': 'eA=='}}]}]}), + ('/v1/responses', {'model': 'm', 'max_output_tokens': 8, 'input': [{'role': 'user', 'content': [ + {'type': 'input_image', 'image_url': 'data:image/png;base64,eA=='}]}]}), + ] + for path, body in cases: + for stream in (False, True): + for retry in range(2): + with self.subTest(path=path, stream=stream, retry=retry): + previous = started.read_text().splitlines() if started.exists() else [] + with self.assertRaises(urllib.error.HTTPError) as got: + self.post(path, {**body, 'stream': stream}) + with got.exception as response: + self.assertEqual(response.code, 503) + self.assertIn('the image encoder failed to start', json.load(response)['error']['message']) + children = started.read_text().splitlines() + self.assertEqual(len(children), len(previous) + 1) + self.assertFalse(vision.alive()) + self.assertFalse(Path('/proc', children[-1]).exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/serve/test_web_badges.py b/serve/test_web_badges.py new file mode 100644 index 00000000..fcfb8860 --- /dev/null +++ b/serve/test_web_badges.py @@ -0,0 +1,32 @@ +"""serve/test_web_badges.py - the Recent requests table has a badge for every way a request can end (#3991). + +A request that waits past the queue limit ends with finish "timeout"; the Status cell showed the raw word. Reads the page source. +""" +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +APP = Path(__file__).resolve().parent / "web" / "app.js" +SERVER = Path(__file__).resolve().parent / "server.py" + + +class FinishBadges(unittest.TestCase): + def test_a_timed_out_request_has_a_badge(self): + src = APP.read_text(encoding="utf-8") + table = src[src.index("const badge = {stop:"):] + table = table[:table.index("};")] + self.assertRegex(table, r'timeout: \["st-badge--queued", "Timeout"\]') + + def test_every_finish_the_server_stores_has_a_badge(self): + src = APP.read_text(encoding="utf-8") + table = src[src.index("const badge = {stop:"):] + table = table[:table.index("};")] + for finish in ("stop", "length", "cancel", "disconnect", "error", "timeout"): + self.assertRegex(table, rf"\b{finish}:", finish) + self.assertIn('"timeout"', SERVER.read_text(encoding="utf-8")) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_web_follow.py b/serve/test_web_follow.py new file mode 100644 index 00000000..5157ef98 --- /dev/null +++ b/serve/test_web_follow.py @@ -0,0 +1,62 @@ +"""serve/test_web_follow.py - the web chat follows the answer only while the reader has not left (#4014). + +The page used to pull the view back to the bottom on every frame when it was within 120 px of it, so one wheel notch +(about 100 px) could not scroll up while an answer streamed. Pins, with node, the page's own rule and that the wheel, +touch and keyboard listeners are wired. Skipped without node. + + python -m unittest serve.test_web_follow -v +""" +from __future__ import annotations + +import json +import shutil +import subprocess +import unittest +from pathlib import Path + +APP = Path(__file__).resolve().parent / "web" / "app.js" + + +def between(src: str, start: str, end: str) -> str: + a = src.index(start) + return src[a:src.index(end, a)] + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class WebFollow(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.src = APP.read_text(encoding="utf-8") + cls.rule = between(cls.src, "const FOLLOW_SLACK", "function scrollDown") + + def follow(self, distance, was, ms): + js = self.rule + f"\nconsole.log(JSON.stringify(followAfterScroll({distance}, {json.dumps(was)}, {ms})));" + out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30) + self.assertEqual(out.returncode, 0, out.stderr) + return json.loads(out.stdout) + + def test_a_wheel_notch_inside_the_old_band_is_not_pulled_back(self): + self.assertFalse(self.follow(100, True, 20)) + self.assertFalse(self.follow(40, True, 20)) + + def test_back_at_the_bottom_it_follows_again(self): + self.assertTrue(self.follow(0, False, 10_000)) + self.assertTrue(self.follow(24, False, 10_000)) + self.assertFalse(self.follow(25, False, 10_000)) + + def test_the_page_growing_under_a_following_reader_keeps_following(self): + self.assertTrue(self.follow(80, True, 5_000)) + self.assertFalse(self.follow(80, False, 5_000)) + self.assertFalse(self.follow(401, True, 5_000)) + + def test_the_old_120_px_rule_is_gone_and_the_reader_input_is_wired(self): + self.assertNotIn("< 120", between(self.src, "function renderChat", "$(\"chat\").addEventListener(\"click\"")) + watch = between(self.src, "(function watchReader()", "})();") + for event in ("wheel", "touchmove", "pointerdown", "keydown", "scroll"): + self.assertIn(f'"{event}"', watch) + # a wheel up on a chat that cannot scroll must not switch following off + self.assertIn("e.deltaY < 0 && s.scrollTop > 0", watch) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_web_history.js b/serve/test_web_history.js new file mode 100644 index 00000000..74658c24 --- /dev/null +++ b/serve/test_web_history.js @@ -0,0 +1,222 @@ +// The chat history's logic (serve/web/history.js) and the browser store behind the saved-chats list (serve/web/chatstore.js), +// run in Node. The store runs against a small stub of IndexedDB that is faithful where the code depends on it: a read's result +// is on the request and not on the store; a write the browser refuses fires abort on the transaction; a blocked open never +// resolves by itself; a database already at version 1 does not run onupgradeneeded; requests answer on a later tick. +// (The stub and its cases are from PR #1787 by Scotty-Hudson, rebuilt for the split modules.) +// node serve/test_web_history.js (serve/test_web_history.py runs it too and skips when node is missing) +"use strict"; +const assert = require("node:assert/strict"); +const path = require("node:path"); +const H = require(path.join(__dirname, "web", "history.js")); +const {createChatStore} = require(path.join(__dirname, "web", "chatstore.js")); + +const user = (text, extra = {}) => ({role: "user", text, time: 1, ...extra}); +const bot = (text, extra = {}) => ({role: "assistant", text, time: 2, ...extra}); +const tool = {id: "t1", name: "fs__read", result: "secret result", state: "done", round: 0, at: 0}; +const convo = () => [user("q1", {images: [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], files: [{kind: "file", name: "n.txt", text: "notes"}]}), + bot("a1", {reasoning: "thoughts", tools: [tool], meta: "12 tokens", stopped: true, error: "x"}), user("q2"), bot("a2")]; + +const cases = { + titles_and_groups() { + assert.equal(H.chatTitle({title: "Mine", messages: []}), "Mine"); + assert.equal(H.chatTitle({title: "", messages: [user(" first line\nsecond")]}), "first line"); + assert.equal(H.chatTitle({title: "", messages: [user("x".repeat(100))]}).length, H.TITLE_MAX); + assert.equal(H.chatTitle({title: "", messages: []}), "New chat"); + assert.equal(H.chatTitle({title: "", messages: []}, "Neuer Chat"), "Neuer Chat", "the caller's word for an unnamed chat"); + const now = Date.UTC(2026, 9, 26, 12), day = 86400000; + const keys = [0, 0.4, 1.5, 5, 20, 40].map((d) => H.groupKey(now - d * day, now)); + assert.deepEqual(keys, ["today", "today", "yesterday", "week", "month", "older"]); + const a = H.newChat(1, 0.5), b = H.newChat(2, 0.5); + assert.notEqual(a.id, b.id); assert.deepEqual(a.messages, []); + }, + filter_searches_titles_and_text() { + const chats = [{id: "a", title: "the garden", time: 3, messages: [user("watering the tomatoes")]}, + {id: "b", title: "a chat about code", time: 2, messages: [user("nothing here")]}, + {id: "c", title: "tomatoes again", time: 1, messages: [user("a different question")]}]; + assert.deepEqual(H.filterChats(chats, "").map((c) => c.id), ["a", "b", "c"], "newest first"); + assert.deepEqual(H.filterChats(chats, " TOMATOES ").map((c) => c.id), ["a", "c"], "title or text, any case"); + assert.deepEqual(H.filterChats(chats, "nothing here").map((c) => c.id), ["b"]); + assert.deepEqual(H.filterChats(chats, "zzz"), []); + assert.deepEqual(chats.map((c) => c.id), ["a", "b", "c"], "the caller's list is not reordered"); + }, + clean_keeps_names_only() { + const clean = H.cleanMessages(convo()); + assert.deepEqual(clean[0].images, [{name: "a.png"}]); + assert.deepEqual(clean[0].files, [{name: "n.txt"}]); + assert.ok(!JSON.stringify(clean).includes("data:image") && !JSON.stringify(clean).includes("notes"), "no contents in the browser's store"); + assert.equal(clean[1].text, "a1", "the text stays"); + assert.deepEqual(convo()[0].files, [{kind: "file", name: "n.txt", text: "notes"}], "a copy: the screen keeps its contents"); + }, + rewind_a_question() { + const m = convo(); + const plan = H.rewind(m, 2); + assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"]); + assert.equal(plan.hidden, 2, "the question and its answer"); + assert.equal(plan.draft.text, "q2"); assert.equal(plan.draft.lost, 0); + const first = H.rewind(m, 0); + assert.deepEqual(first.keep, [], "the first question: nothing stays, the question goes to the box"); + assert.equal(first.draft.text, "q1"); assert.equal(first.hidden, 4); + assert.deepEqual(first.draft.images, [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], "attachments with contents come back"); + assert.deepEqual(first.draft.files, [{kind: "file", name: "n.txt", text: "notes"}]); + assert.equal(m.length, 4, "the list itself is not changed"); + }, + rewind_an_answer() { + const plan = H.rewind(convo(), 1); + assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"], "the answer stays and the list ends with it"); + assert.equal(plan.draft, null); assert.equal(plan.hidden, 2); + assert.equal(H.rewind(convo(), 3).hidden, 0, "the last answer: nothing to hide"); + assert.equal(H.rewind(convo(), 9), null); + }, + lost_attachments_are_counted() { + const reloaded = H.cleanMessages(convo()); + assert.equal(H.lostAttachments(reloaded[0]), 2); + assert.equal(H.lostAttachments(convo()[0]), 0); + const plan = H.rewind(reloaded, 0); + assert.equal(plan.draft.lost, 2); assert.deepEqual(plan.draft.images, []); assert.deepEqual(plan.draft.files, []); + assert.equal(plan.draft.text, "q1", "the text still comes back"); + }, + regenerate_from_the_question() { + const m = convo(); + assert.deepEqual(H.regenerate(m, 1).keep.map((x) => x.text), ["q1"]); + assert.equal(H.regenerate(m, 1).hidden, 3); + assert.deepEqual(H.regenerate(m, 3).keep.map((x) => x.text), ["q1", "a1", "q2"]); + assert.deepEqual(H.regenerate(m, 2).keep.map((x) => x.text), ["q1", "a1", "q2"], "on the last question itself"); + assert.equal(H.regenerate([bot("orphan")], 0), null, "no question before it"); + }, + edit_an_answer() { + const plan = H.editAnswer(convo(), 1, "corrected", "Edited"); + assert.equal(plan.keep.length, 2); assert.equal(plan.hidden, 2); + const a = plan.keep[1]; + assert.deepEqual(a, {role: "assistant", text: "corrected", time: 2, meta: "Edited"}, "no thinking, tools, error, stop mark or stats"); + assert.equal(H.editAnswer(convo(), 0, "x"), null, "only an answer can be edited"); + }, + branch_is_a_copy_with_a_title_that_stays() { + const original = {id: "c1", title: "", time: 1, messages: convo()}; + const plan = H.rewind(original.messages, 2); + const b = H.branch(original, plan.keep, plan.keep.length, "Branch of q1", 5, 0.25); + assert.deepEqual(b.messages.map((x) => x.text), ["q1", "a1"]); + assert.equal(b.title, "Branch of q1"); assert.deepEqual(b.parent, {id: "c1", title: "q1"}); + assert.notEqual(b.id, "c1"); + b.messages[0].text = "changed"; b.messages[1].tools[0].result = "changed"; + assert.equal(original.messages[0].text, "q1", "the original is untouched"); + assert.equal(original.messages[1].tools[0].result, "secret result"); + assert.equal(H.chatTitle(H.branch(original, [], 0, "Branch of q1"), "x"), "Branch of q1", "a branch at the first message keeps its title"); + }, +}; + +// ---------------------------------------------------------------- the stub IndexedDB +function makeIdb(hooks = {}, seed = {}) { + const data = Object.assign({}, seed), stores = {}, calls = {upgradeneeded: 0, createObjectStore: 0}; + let current = null; + const request = () => ({result: null, error: null, transaction: current, onsuccess: null, onerror: null}); + const store = { + put(value) { + const req = request(); + queueMicrotask(() => { + if (hooks.quota) { req.error = {name: "QuotaExceededError"}; req.onerror && req.onerror(); return; } + if (hooks.abort) return; + data[value.id] = value; req.result = value; req.onsuccess && req.onsuccess(); + }); + return req; + }, + delete(key) { + const req = request(); + queueMicrotask(() => { if (hooks.quota || hooks.abort) return; delete data[key]; req.result = true; req.onsuccess && req.onsuccess(); }); + return req; + }, + getAll() { + const req = request(); + queueMicrotask(() => { if (hooks.abort) return; req.result = Object.values(data); req.onsuccess && req.onsuccess(); }); + return req; + }, + }; + const transaction = () => { + const t = {error: null, oncomplete: null, onerror: null, onabort: null, objectStore: () => store}; + current = t; + queueMicrotask(() => { + if (hooks.quota || hooks.abort) { t.error = {name: hooks.quota ? "QuotaExceededError" : hooks.abort}; t.onabort && t.onabort(); } + else if (t.oncomplete) t.oncomplete(); + }); + return t; + }; + const db = {objectStoreNames: {contains: (n) => n in stores}, createObjectStore: (n) => { calls.createObjectStore++; stores[n] = store; }, transaction}; + return {open: () => { + if (hooks.throws) throw new Error("private mode"); + const r = {result: db, error: null, onupgradeneeded: null, onsuccess: null, onerror: null, onblocked: null}; + queueMicrotask(() => { + if (hooks.blocked) { r.onblocked && r.onblocked(); return; } + if (hooks.newDatabase !== false) { calls.upgradeneeded++; r.onupgradeneeded && r.onupgradeneeded(); } + r.result = db; r.onsuccess && r.onsuccess(); + }); + return r; + }, records: data, calls}; +} +const wait = () => new Promise((r) => setTimeout(r, 10)); +const mk = (hooks, seed) => { + const idb = makeIdb(hooks, seed), problems = []; + return {idb, problems, store: createChatStore({indexedDB: idb, onProblem: (k) => problems.push(k)})}; +}; +const chat = (id, extra = {}) => ({id, title: id, time: 1, messages: [user("hi " + id)], ...extra}); + +Object.assign(cases, { + async store_fresh_database_creates_the_store_and_reads() { + const a = mk({}, {c0: chat("c0"), c1: chat("c1")}); + assert.equal(await a.store.start(), true); + assert.equal(a.idb.calls.upgradeneeded, 1); assert.equal(a.idb.calls.createObjectStore, 1); + assert.deepEqual((await a.store.all()).map((c) => c.id).sort(), ["c0", "c1"], "the result is read from the request"); + assert.deepEqual(a.problems, []); + }, + async store_put_and_remove_touch_one_record() { + const a = mk({}, {c0: chat("c0")}); + await a.store.start(); + a.store.put(chat("c1", {title: "renamed"})); await wait(); + assert.equal(a.idb.records.c1.title, "renamed"); assert.ok(a.idb.records.c0, "the other record is not rewritten"); + a.store.remove("c0"); await wait(); + assert.ok(!("c0" in a.idb.records)); + }, + async store_private_mode_is_memory_only_and_says_so_once() { + const a = mk({throws: true}); + assert.equal(await a.store.start(), false); + assert.deepEqual(a.problems, ["memory"]); + assert.deepEqual(await a.store.all(), []); + a.store.put(chat("x")); a.store.remove("x"); // no store: nothing to do, nothing thrown + await a.store.start(); + assert.deepEqual(a.problems, ["memory"], "told once, not on every try"); + }, + async store_missing_object_store_is_memory_only() { + const a = mk({newDatabase: false}); // a database already at version 1: no upgrade, no store + assert.equal(await a.store.start(), false); + assert.equal(a.idb.calls.createObjectStore, 0); + assert.deepEqual(a.problems, ["memory"]); + }, + async store_blocked_open_does_not_hang() { + const a = mk({blocked: true}); + assert.equal(await a.store.start(), false); + assert.deepEqual(a.problems, ["memory"]); + }, + async store_full_storage_warns_once_with_its_own_message() { + const a = mk({quota: true}); + await a.store.start(); + a.store.put(chat("big")); await wait(); + a.store.put(chat("big2")); await wait(); + assert.deepEqual(a.problems, ["quota"], "one warning, the quota one"); + }, + async store_another_failure_is_not_called_quota() { + const a = mk({abort: "DataError"}); + await a.store.start(); + a.store.put(chat("bad")); await wait(); + assert.deepEqual(a.problems, ["failed"]); + }, + async store_a_read_that_aborts_answers_empty() { + const a = mk({abort: "DataError"}, {c0: chat("c0")}); + await a.store.start(); + assert.deepEqual(await a.store.all(), [], "no hang, no records"); + }, +}); + +(async () => { + const name = process.argv[2]; + const run = name ? [[name, cases[name]]] : Object.entries(cases); + if (name && !cases[name]) throw new Error("unknown test " + name); + for (const [n, fn] of run) { await fn(); console.log("ok " + n); } +})().catch((e) => { console.error(e); process.exitCode = 1; }); diff --git a/serve/test_web_history.py b/serve/test_web_history.py new file mode 100644 index 00000000..15854f2e --- /dev/null +++ b/serve/test_web_history.py @@ -0,0 +1,119 @@ +"""The web page's chat history: saved chats in the browser (#1787), edit / regenerate / rewind with an Undo (#2615), the rewind +choice between "here" and a branch (#3823), and sending while an answer is written (#4004). One design, opt-in, off by default. + +The logic runs in Node (serve/test_web_history.js); what the page does in a real browser is in tools/webtest/browser_test.mjs +(run here when WEBTEST_MODULES is set). These checks read the sources for what must hold whatever the code looks like: +off is the page from before, and nothing about a chat goes to the server.""" +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import unittest +import urllib.error +import urllib.request +from pathlib import Path + +from serve.frontend import ChatTemplate +from serve.server import ByteTokenizer, MockEngine, Service, serve + +ROOT = Path(__file__).resolve().parents[1] +WEB = Path(__file__).parent / "web" + + +@unittest.skipUnless(shutil.which("node"), "node is not installed") +class HistoryInNode(unittest.TestCase): + def test_messages_titles_branches_and_the_browser_store(self): + r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_history.js"))], + capture_output=True, text=True, timeout=60) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + + +class OffIsThePageFromBefore(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.html = (WEB / "index.html").read_text(encoding="utf-8") + cls.app = (WEB / "app.js").read_text(encoding="utf-8") + cls.ui = (WEB / "chats-ui.js").read_text(encoding="utf-8") + cls.store = (WEB / "chatstore.js").read_text(encoding="utf-8") + + def test_the_three_switches_start_off(self): + self.assertIn('chatList: false, chatEdit: false, whileBusy: "wait"', self.app) + for el in ("s-list", "s-edit"): + self.assertIn('aria-checked="false"', re.search(rf']*id="{el}"[^>]*>', self.html).group(0)) + self.assertIn('data-v="wait"', self.html) + self.assertRegex(self.html, r'