Merge f-split-int (a3024ed10) into f-split-qa1: qa2's s3237-s3238 kept, my 21 strings renumbered s3260-s3280
This commit is contained in:
commit
8667a3dbf7
55 files changed
+2234
-316
No files matched your search
Generated
+2
@@ -3526,6 +3526,7 @@ checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7"
|
||||
name = "strata-desktop"
|
||||
version = "0.2.0-beta"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
@@ -3533,6 +3534,7 @@ dependencies = [
|
||||
"tauri-plugin-shell",
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"webkit2gtk",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -6,6 +6,11 @@ edition = "2021"
|
||||
rust-version = "1.77"
|
||||
license = "MIT"
|
||||
|
||||
# Linux: the drop of a file on the window is read straight from the GTK drag signals (see hook_linux_drops in main.rs); the versions are the ones Tauri itself uses.
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
webkit2gtk = "2.0"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
|
||||
@@ -855,7 +855,8 @@ fn run_embedded() {
|
||||
eprintln!("[strata] {e}");
|
||||
Box::<dyn std::error::Error>::from(e)
|
||||
})?;
|
||||
open_window(app, port)?;
|
||||
let shell_token = handle.state::<ShutdownToken>().0.lock().unwrap().clone().unwrap_or_default();
|
||||
open_window(app, port, &shell_token)?;
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
@@ -873,13 +874,17 @@ fn run_embedded() {
|
||||
}
|
||||
|
||||
/// The one window, on the host's own origin so the page and its API share an origin exactly as the browser build does.
|
||||
fn open_window(app: &tauri::App, port: u16) -> Result<(), Box<dyn std::error::Error>> {
|
||||
#[cfg_attr(windows, allow(unused_variables))]
|
||||
fn open_window(app: &tauri::App, port: u16, shell_token: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let origin = format!("http://127.0.0.1:{port}");
|
||||
let url = origin.parse().expect("a valid loopback URL");
|
||||
// The shell's own file-drop handler is off: with it on, Windows hands a dropped file to the shell and the page never sees it, so pictures
|
||||
// could not be dropped on the chat (QA report 1, item 4). With it off the page gets ordinary drag and drop events (apps/host DropZone), the
|
||||
// same as in a browser, on every system.
|
||||
let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url)).title("Strata").inner_size(1440.0, 920.0).min_inner_size(900.0, 600.0).disable_drag_drop_handler();
|
||||
let builder = WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url)).title("Strata").inner_size(1440.0, 920.0).min_inner_size(900.0, 600.0);
|
||||
// Dropping pictures on the chat (QA report 1, item 4). Windows: the shell's own file-drop handler is off, because with it on the system hands
|
||||
// the dropped file to the shell and the page never sees it; with it off the page gets ordinary drag and drop events (apps/host DropZone), as
|
||||
// in a browser. Linux and macOS: the page gets the drag events but WebKit gives it no files, so the handler stays on and the shell passes the
|
||||
// drop on (see drop_script and hand_over_drop below).
|
||||
#[cfg(windows)]
|
||||
let builder = builder.disable_drag_drop_handler();
|
||||
// WebKitGTK (2.50 to 2.52 at least) dereferences a null pointer in AcceleratedBackingStore::update in its UI process when a page calls
|
||||
// document.startViewTransition (the web process asks the UI process to enter accelerated compositing, and the backing store is not
|
||||
// there). The page itself does not call it on that engine (apps/host/src/lib/router.ts), and this line keeps any other script from doing
|
||||
@@ -888,10 +893,173 @@ fn open_window(app: &tauri::App, port: u16) -> Result<(), Box<dyn std::error::Er
|
||||
let builder = builder.initialization_script(
|
||||
"try { Object.defineProperty(Document.prototype, 'startViewTransition', { value: undefined, configurable: true, writable: true }); } catch (e) {}",
|
||||
);
|
||||
builder.build()?;
|
||||
#[cfg_attr(windows, allow(unused_variables))]
|
||||
let window = builder.build()?;
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let target = window.clone();
|
||||
let token = shell_token.to_string();
|
||||
window.on_webview_event(move |event| {
|
||||
if let tauri::WebviewEvent::DragDrop(drag) = event {
|
||||
match drag {
|
||||
tauri::DragDropEvent::Enter { .. } => { let _ = target.eval(&drag_script("enter")); }
|
||||
tauri::DragDropEvent::Leave => { let _ = target.eval(&drag_script("leave")); }
|
||||
tauri::DragDropEvent::Drop { paths, .. } => {
|
||||
let _ = target.eval(&drag_script("leave"));
|
||||
let paths: Vec<String> = paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
hand_over_drop(target.clone(), port, token.clone(), paths);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
hook_linux_drops(&window, port, shell_token);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A file:// address from a drag, as a path (percent-escapes decoded); anything else (http, mailto, text) is not a dropped file.
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
fn file_uri_to_path(uri: &str) -> Option<String> {
|
||||
let rest = uri.trim().strip_prefix("file://")?;
|
||||
// file://host/path: only an empty or local host is a file on this computer
|
||||
let rest = match rest.find('/') { Some(0) => rest, Some(i) if rest[..i].eq_ignore_ascii_case("localhost") => &rest[i..], _ => return None };
|
||||
let bytes = rest.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(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
let path = String::from_utf8(out).ok()?;
|
||||
if path.contains('\0') { None } else { Some(path) }
|
||||
}
|
||||
|
||||
/// Linux: WebKitGTK 2.52 gives the page a file drag without the files, and the window library's own drop handler never sees one, so the
|
||||
/// shell reads the drop itself from the GTK drag signals of the page widget: the file:// addresses arrive with the drag data, the drop hands
|
||||
/// them to the host exactly as the other systems do (hand_over_drop), and the page shows its drop box meanwhile (QA, drop on the chat).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn hook_linux_drops(window: &tauri::WebviewWindow, port: u16, token: &str) {
|
||||
use gtk::prelude::*;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
let target = window.clone();
|
||||
let token = token.to_string();
|
||||
let _ = window.with_webview(move |platform| {
|
||||
let view = platform.inner();
|
||||
let paths: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
|
||||
let hovering = Rc::new(Cell::new(false));
|
||||
let generation = Rc::new(Cell::new(0u32));
|
||||
{
|
||||
let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone());
|
||||
view.connect_drag_data_received(move |_, _, _, _, data, _, _| {
|
||||
let list: Vec<String> = data.uris().iter().filter_map(|u| file_uri_to_path(u.as_str())).collect();
|
||||
if list.is_empty() { return; }
|
||||
*paths.borrow_mut() = list;
|
||||
generation.set(generation.get() + 1);
|
||||
if !hovering.replace(true) { let _ = target.eval(&drag_script("enter")); }
|
||||
});
|
||||
}
|
||||
{
|
||||
// WebKit only accepts a drag when the page says so, and the page is not given the files: once the addresses of a file drag are known,
|
||||
// the shell accepts it (as a copy) itself, so GTK goes on to deliver the drop.
|
||||
let paths = paths.clone();
|
||||
view.connect_drag_motion(move |_, ctx, _, _, time| {
|
||||
if paths.borrow().is_empty() { return false; }
|
||||
ctx.drag_status(gtk::gdk::DragAction::COPY, time);
|
||||
true
|
||||
});
|
||||
}
|
||||
{
|
||||
let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone());
|
||||
let token = token.clone();
|
||||
view.connect_drag_drop(move |_, ctx, _, _, time| {
|
||||
generation.set(generation.get() + 1);
|
||||
let list = std::mem::take(&mut *paths.borrow_mut());
|
||||
if list.is_empty() { return false; } // not a file: the page deals with it
|
||||
hovering.set(false);
|
||||
ctx.drop_finish(true, time);
|
||||
let _ = target.eval(&drag_script("leave"));
|
||||
hand_over_drop(target.clone(), port, token.clone(), list);
|
||||
true
|
||||
});
|
||||
}
|
||||
{
|
||||
let (paths, hovering, target, token) = (paths.clone(), hovering.clone(), target.clone(), token.clone());
|
||||
view.connect_drag_leave(move |widget, _, _| {
|
||||
// WebKit's own handling of a drop never reaches this widget's drop signal, but GTK does say "leave" at the moment of the drop:
|
||||
// a leave with every mouse button already up (and a file drag known) is the drop. A leave with the button still down is the
|
||||
// pointer going out of the window.
|
||||
if hovering.get() && !paths.borrow().is_empty() && pointer_buttons_up(widget) {
|
||||
let list = std::mem::take(&mut *paths.borrow_mut());
|
||||
hovering.set(false);
|
||||
let _ = target.eval(&drag_script("leave"));
|
||||
hand_over_drop(target.clone(), port, token.clone(), list);
|
||||
}
|
||||
});
|
||||
}
|
||||
view.connect_drag_leave(move |_, _, _| {
|
||||
// only a leave that nothing follows ends the drag (a drop is handled above and clears the state)
|
||||
let seen = generation.get();
|
||||
let (paths, hovering, generation, target) = (paths.clone(), hovering.clone(), generation.clone(), target.clone());
|
||||
gtk::glib::idle_add_local_once(move || {
|
||||
if generation.get() == seen && hovering.replace(false) {
|
||||
paths.borrow_mut().clear();
|
||||
let _ = target.eval(&drag_script("leave"));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// True when no mouse button is held down (GTK drag drop: the button is already up when the drop arrives).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn pointer_buttons_up(widget: &webkit2gtk::WebView) -> bool {
|
||||
use gtk::prelude::*;
|
||||
let Some(window) = widget.window() else { return false };
|
||||
let Some(pointer) = gtk::gdk::Display::default().and_then(|d| d.default_seat()).and_then(|s| s.pointer()) else { return false };
|
||||
let (_, _, _, mask) = window.device_position(&pointer);
|
||||
!mask.intersects(gtk::gdk::ModifierType::BUTTON1_MASK | gtk::gdk::ModifierType::BUTTON2_MASK | gtk::gdk::ModifierType::BUTTON3_MASK)
|
||||
}
|
||||
|
||||
/// The script that tells the page a file drag is over the window (`state` is "enter" or "leave"); the page shows its drop box (apps/host DropZone).
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
fn drag_script(state: &str) -> String {
|
||||
format!("window.dispatchEvent(new CustomEvent('strata:native-drag', {{ detail: '{state}' }}));")
|
||||
}
|
||||
|
||||
/// The script that tells the page which dropped files the host holds for it (`files_json` is the host's own JSON array of { id, name, type, size }).
|
||||
#[cfg_attr(windows, allow(dead_code))]
|
||||
fn drop_script(files_json: &str) -> String {
|
||||
format!("window.dispatchEvent(new CustomEvent('strata:native-drop', {{ detail: {files_json} }}));")
|
||||
}
|
||||
|
||||
/// The files of one drop, by path, to the host (which reads them and keeps each for the page to fetch once); then the page is told.
|
||||
/// Off the window's own thread, so the window never waits for a big picture to be read.
|
||||
#[cfg(not(windows))]
|
||||
fn hand_over_drop(window: tauri::WebviewWindow, port: u16, token: String, paths: Vec<String>) {
|
||||
std::thread::spawn(move || {
|
||||
let body = serde_json::json!({ "paths": paths }).to_string();
|
||||
let answer = http_request_body(
|
||||
"POST",
|
||||
&format!("http://127.0.0.1:{port}/api/app/drop"),
|
||||
&[("x-strata-shutdown", token.as_str()), ("content-type", "application/json")],
|
||||
Some(&body),
|
||||
);
|
||||
let files = match answer {
|
||||
Ok((status, text)) if status.contains(" 200") => serde_json::from_str::<serde_json::Value>(&text).ok().and_then(|v| v.get("files").cloned()),
|
||||
Ok((status, _)) => { eprintln!("[strata] the host did not take the dropped files: {status}"); None }
|
||||
Err(e) => { eprintln!("[strata] the dropped files could not be handed to the host: {e}"); None }
|
||||
};
|
||||
let json = files.map(|f| f.to_string()).unwrap_or_else(|| "[]".to_string());
|
||||
let _ = window.eval(&drop_script(&json));
|
||||
});
|
||||
}
|
||||
|
||||
/// Linux window process: shows the page of the host the shell started and registers the app updater with it. It starts no host and
|
||||
/// stops nothing: when the window closes it just exits, and the shell stops the host. If WebKit crashes this process, only this
|
||||
/// process dies; the shell moves to browser mode.
|
||||
@@ -937,7 +1105,7 @@ fn run_window_process() -> ! {
|
||||
eprintln!("[strata] the app updater could not be registered with the host: {e}");
|
||||
}
|
||||
}
|
||||
open_window(app, port)
|
||||
open_window(app, port, &token)
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
if let tauri::WindowEvent::Destroyed = event {
|
||||
@@ -954,6 +1122,24 @@ fn run_window_process() -> ! {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn dropped_file_addresses_become_paths_and_nothing_else_does() {
|
||||
assert_eq!(file_uri_to_path("file:///home/me/My%20Pictures/a%2Bb.png").as_deref(), Some("/home/me/My Pictures/a+b.png"));
|
||||
assert_eq!(file_uri_to_path("file://localhost/tmp/x.txt").as_deref(), Some("/tmp/x.txt"));
|
||||
assert_eq!(file_uri_to_path(" file:///tmp/%C4%8C.txt\r\n").as_deref(), Some("/tmp/\u{10C}.txt"));
|
||||
for bad in ["http://example.com/a.png", "file://otherhost/tmp/x", "mailto:a@b.c", "/tmp/plain", "file://", "file:///tmp/a%00b"] { assert_eq!(file_uri_to_path(bad), None, "{bad}"); }
|
||||
assert_eq!(file_uri_to_path("file:///100%").as_deref(), Some("/100%"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scripts_the_shell_sends_the_page_for_a_file_drop() {
|
||||
assert_eq!(drag_script("enter"), "window.dispatchEvent(new CustomEvent('strata:native-drag', { detail: 'enter' }));");
|
||||
let files = r#"[{"id":"a","name":"x.png","type":"image/png","size":3}]"#;
|
||||
let script = drop_script(files);
|
||||
assert!(script.starts_with("window.dispatchEvent(new CustomEvent('strata:native-drop', { detail: [{"));
|
||||
assert!(script.contains("x.png") && script.ends_with("}));"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_origin_is_stable_unless_the_port_is_taken() {
|
||||
// free (or already ours from a previous run): the same port every launch, so browser storage survives a restart
|
||||
|
||||
@@ -68,7 +68,7 @@ The chat's Mode menu is real Harness behaviour. Each turn the page sends the cha
|
||||
What the person chose is saved by `tools-settings.mjs` (inside the host's settings file) and shown by `src/components/SettingsTools.tsx` (`GET/PUT /api/agent/tools`, `POST/PATCH/DELETE /api/agent/tools/custom[/id]`). A change reaches the agent from the next message: the profile carries a `toolsSignature`, and the bridge restarts the Harness (after the running turns end) when it differs.
|
||||
|
||||
- Tool groups (`tools-catalog.mjs`): each is one switch in plain words and is one or more preset plugins (`withoutDisabled`); `fetch` and `search` are the two halves of the Harness's `tool-web` (both off drops it). Goals off: `/goal` answers that goals are turned off.
|
||||
- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`): a browser User-Agent, one request at a time at least 1.5 s apart, at most 20 a minute, a 10 minute cache per query, a 15 s limit, the lite page as a fallback, and a plain message when DuckDuckGo asks for a human check ("limiting searches from this computer"). **The results come from DuckDuckGo**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous.
|
||||
- Web search needs no account. The default is DuckDuckGo's HTML result page (`../web-search-ddg.mjs`), with Bing's plain result page (`../web-search-bing.mjs`) as the second source. Manners, because DuckDuckGo refuses a program that asks fast (a real box: two searches in 1.2 s answered, the third got HTTP 202 and every DuckDuckGo page refused for many minutes): a browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*), one request at a time per source, 2.5 to 4 s apart (random), at most 8 a minute, a 30 minute session cache per question, a cooldown after a refusal that doubles (1, 2, 4 ... 10 minutes, `Retry-After` honoured) during which that source gets no request, no lite-page follow-up after a refusal, one retry for a timeout or a 5xx, a 15 s limit. When every source refuses, the tool answers one plain sentence (`LIMITED_SENTENCE`: "Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings -> Tools -> Web search.") plus an instruction to the model not to retry; the turn guard in `agent-bridge.mjs` (see Turn guard) stops a model that retries anyway. **The results come from DuckDuckGo or Bing**; they are not ranked or filtered here. The person may switch to Exa, Perplexity or DeepSeek with their own key (`../web-search-keyed.mjs`; DeepSeek uses the Harness's own provider): the key is saved in the settings file, reaches the agent only as the environment variable `STRATA_SEARCH_KEY`, never the profile file and never the screen (it only learns `keySet`). A keyed service without its key falls back to DuckDuckGo. The profile pins `web.searchProvider` to the chosen id so two usable backends cannot make the choice ambiguous.
|
||||
- The browser: Playwright's MCP server (`@playwright/mcp`, staged next to the Harness by `apps/desktop/scripts/stage-harness.mjs`) on the person's own Chrome, Edge or Chromium (`browser-probe.mjs`), `--isolated` so it never sees their profile. Tools appear as `mcp__browser__browser_*`. In Manual, opening a page, clicking, typing, uploading, running a script in the page and closing tabs ask (plain reasons: "Open the web page ...", "Click on the page: ..."); looking (snapshot, screenshot, console, network, waiting, listing tabs) does not. Plan refuses every connected tool. The screen says plainly when no browser, or no tool server, is found.
|
||||
- The person's own tools: `instructions` (the tool returns their text; look-only, never asks), `command` (runs their command with the assistant's text in the `STRATA_INPUT` environment variable, never spliced into the command line; asks in Manual, refused in Plan) and `server` (a web address or a program, added as `mcp__custom-<name>__*`; asks in Manual). Instruction and command tools are served by `custom-tools-mcp.mjs` (stdio MCP) from a JSON file the settings module rewrites on every change, so a switch in Settings is seen without a restart.
|
||||
- `strata-gate.mjs` implements the Manual/Plan rules above (`planDecision`, `browserDecision`, the look-only instruction server).
|
||||
@@ -121,3 +121,13 @@ A model on OpenRouter whose model list names `reasoning` in `supported_parameter
|
||||
## Pictures
|
||||
|
||||
Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag.
|
||||
|
||||
## Turn guard (`turn-guard.mjs`)
|
||||
|
||||
A turn that keeps failing the same way is stopped by the app, never left to the model. Seen on a search-heavy `/plan`: every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%, then the turn ended with no answer and no message.
|
||||
|
||||
- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up).
|
||||
- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step.
|
||||
- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged.
|
||||
- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded.
|
||||
- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network).
|
||||
@@ -28,6 +28,7 @@ import { ChildProjector } from './children.mjs';
|
||||
import { nearestBudget } from './llm-shape.mjs';
|
||||
import { DeliverableTracker, ActivityGroups } from './deliverables.mjs';
|
||||
import { SkillsUsed, skillInfoFrom } from './skills-used.mjs';
|
||||
import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs';
|
||||
import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs';
|
||||
|
||||
/**
|
||||
@@ -90,7 +91,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve
|
||||
* @param {string} [options.nodePath] the Node runtime that runs the Harness
|
||||
* @param {(line:string)=>void} [options.log]
|
||||
*/
|
||||
export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
|
||||
export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) {
|
||||
const root = join(dataDir, 'agent');
|
||||
const home = join(root, 'home');
|
||||
const sessionsFile = join(root, 'sessions.json');
|
||||
@@ -146,7 +147,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
/** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */
|
||||
let shapeTargets = {};
|
||||
function buildProfileNow() {
|
||||
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase });
|
||||
const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock });
|
||||
shapeTargets = profile.shapeTargets ?? {};
|
||||
return profile;
|
||||
}
|
||||
@@ -311,6 +312,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true });
|
||||
// What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary.
|
||||
const written = { all: '', step: '' };
|
||||
// The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known.
|
||||
let guard = null;
|
||||
const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } };
|
||||
// What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends.
|
||||
const tracker = new DeliverableTracker(workspacePath, trackerFolders());
|
||||
@@ -319,7 +322,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
const groups = new ActivityGroups({ emit: raw });
|
||||
const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) });
|
||||
const emit = frame => {
|
||||
if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (hideDeltas) return; }
|
||||
if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; }
|
||||
if (frame.own) { const { own, ...rest } = frame; frame = rest; }
|
||||
if (frame.type === 'delta' && frame.text) groups.text();
|
||||
if (frame.type === 'agent-tool' && frame.tool) {
|
||||
@@ -328,6 +331,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } }
|
||||
raw(frame);
|
||||
if (made) raw(made);
|
||||
if (guard) trip(guard.card(frame.tool));
|
||||
groups.card(frame.tool, made);
|
||||
skills.card(frame.tool);
|
||||
return;
|
||||
@@ -370,6 +374,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
await applyMode(runtime, sessionId, appliedMode);
|
||||
|
||||
const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval });
|
||||
if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess
|
||||
projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); };
|
||||
const turn = {
|
||||
sessionId, projector, route, requestId, live: false, lastSeq: -1,
|
||||
@@ -406,13 +411,19 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
clearInterval(turn.watchdog);
|
||||
turn.follow?.close();
|
||||
for (const child of turn.children.values()) child.follow?.close();
|
||||
if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } };
|
||||
if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } };
|
||||
reporter.clear();
|
||||
const extra = [];
|
||||
try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ }
|
||||
groups.end();
|
||||
if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); }
|
||||
try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ }
|
||||
// The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself).
|
||||
let noteReason = turn.guard ?? null;
|
||||
if (!noteReason && guard && !failure && !turn.stopping && !turn.goalRun) {
|
||||
noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens });
|
||||
}
|
||||
if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); }
|
||||
for (const f of extra) emit(f);
|
||||
const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow });
|
||||
for (const f of frames.slice(0, -1)) emit(f);
|
||||
@@ -425,6 +436,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
c.turn = null;
|
||||
turn.ended.resolve({ reason: projector.ended, failure: failure ?? null });
|
||||
notifyIdle();
|
||||
// A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room.
|
||||
if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId);
|
||||
}
|
||||
|
||||
emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) });
|
||||
@@ -442,6 +455,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
onError: e => finishTurn(`The agent lost the session stream: ${e.message}`),
|
||||
});
|
||||
|
||||
/** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */
|
||||
function trip(reason) {
|
||||
if (!reason || turn.guard || turn.finished || turn.stopping) return;
|
||||
turn.guard = reason;
|
||||
log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`);
|
||||
void stop(chatId).catch(() => {});
|
||||
}
|
||||
|
||||
function handle(item) {
|
||||
if (turn.finished) return;
|
||||
turn.lastActivity = Date.now();
|
||||
@@ -457,6 +478,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
}
|
||||
} else if (!turn.live) return;
|
||||
for (const f of projector.consume(item)) emit(f);
|
||||
if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens));
|
||||
if (item.type === 'event') watchParent(item.event);
|
||||
}
|
||||
|
||||
@@ -566,10 +588,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
/** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */
|
||||
function settlePlan(failure) {
|
||||
if (planTask) {
|
||||
if (failure || turn.stopping) return [];
|
||||
if (failure || (turn.stopping && !turn.guard)) return [];
|
||||
const parsed = parsePlan(written.all, planTask);
|
||||
if (!parsed) return [];
|
||||
const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask });
|
||||
const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) });
|
||||
return [publishPlan('proposed', plan)];
|
||||
}
|
||||
const run = turn.plan;
|
||||
@@ -1094,6 +1116,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
* Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the
|
||||
* Harness acknowledges a cancel as admitted, not as done.
|
||||
*/
|
||||
/** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */
|
||||
async function compactSession(runtime, sessionId) {
|
||||
try {
|
||||
const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] });
|
||||
log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`);
|
||||
} catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); }
|
||||
}
|
||||
|
||||
async function stop(chatId, { waitMs = 20_000 } = {}) {
|
||||
const c = chats.get(chatId);
|
||||
const turn = c?.turn;
|
||||
|
||||
@@ -193,9 +193,9 @@ export class PlanStore {
|
||||
} catch { /* the plan still lives in memory */ }
|
||||
}
|
||||
get(chatId) { return this.plans.get(chatId) ?? null; }
|
||||
create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed' }) {
|
||||
create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed', caution = null }) {
|
||||
const now = new Date().toISOString();
|
||||
const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false };
|
||||
const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false, ...(caution ? { caution } : {}) };
|
||||
this.plans.set(chatId, plan); this.#save();
|
||||
return plan;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,10 @@ export const inject = ['web'];
|
||||
|
||||
export function apply(ctx, config = {}) {
|
||||
const keyOf = () => (config.keyEnv ? process.env[config.keyEnv] ?? '' : '');
|
||||
const provider = config.provider === 'exa' ? createExaSearch({ key: keyOf })
|
||||
// Tests only (the bridge option `searchMock`): the same search code on a pretend web, so nothing leaves the machine.
|
||||
const pretend = config.mock === 'limited' ? { fetch: async url => new Response('<html>please verify you are human: captcha</html>', { status: /duckduckgo/.test(String(url)) ? 202 : 429 }) } : null;
|
||||
const provider = pretend ? createDuckDuckGoSearch(pretend)
|
||||
: config.provider === 'exa' ? createExaSearch({ key: keyOf })
|
||||
: config.provider === 'perplexity' ? createPerplexitySearch({ key: keyOf })
|
||||
: createDuckDuckGoSearch();
|
||||
ctx.web.registerSearchProvider(provider);
|
||||
|
||||
@@ -163,7 +163,7 @@ export function outputBudget(context, maxOutput = null) {
|
||||
/** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */
|
||||
const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } };
|
||||
|
||||
export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null }) {
|
||||
export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null }) {
|
||||
const providers = {};
|
||||
const env = {};
|
||||
const routes = [];
|
||||
@@ -271,7 +271,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools
|
||||
const webRows = !searchOn ? [] : keyed === 'deepseek'
|
||||
? [{ id: 'web', config: { searchProvider: 'deepseek-official', fetchProvider: 'http' } }, { id: 'web-search-deepseek', config: { apiKeyEnv: 'STRATA_SEARCH_KEY' } }]
|
||||
: [{ id: 'web', config: { searchProvider: keyed ?? DDG_PROVIDER_ID, fetchProvider: 'http' } }, { id: 'web-search-deepseek', disabled: true },
|
||||
{ insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY' } }] }];
|
||||
{ insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY', ...(searchMock ? { mock: searchMock } : {}) } }] }];
|
||||
/** The models a helper agent may be started on: the table the model-choice plugin and the Harness's allow-list are written from. */
|
||||
const subagentRoutes = routes.map(r => ({ provider: r.route, model: r.modelId, name: r.name, connection: r.connectionName, local: r.kind === 'local' }));
|
||||
const entries = [
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* The turn guard: a turn that keeps failing the same way, or keeps rewriting the same thing, is stopped by the app and ends with a plain message.
|
||||
* Pure (no I/O); the bridge feeds it what the turn shows and acts on what it answers.
|
||||
*
|
||||
* Why: a search-heavy /plan on a small model searched again after every refusal and rewrote its plan after every search until the context
|
||||
* reached 100%, then the turn ended with no answer and no message. Nothing here relies on the model behaving: the app counts.
|
||||
*
|
||||
* searches-failed this many web searches in a row failed (web search was limited, or could not be reached)
|
||||
* searches this many searches in one turn (a plan or an ordinary answer needs a handful, not dozens)
|
||||
* 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
|
||||
* translates a `delta` frame that carries `key`). Each says what happened and gives one next step.
|
||||
*/
|
||||
|
||||
export const GUARD_LIMITS = Object.freeze({
|
||||
failedSearches: 3,
|
||||
searchesPlan: 10,
|
||||
searchesTurn: 25,
|
||||
planRewrites: 4,
|
||||
contextFraction: 0.93,
|
||||
/** A turn that ends with no words at all and a context this full is "out of room", not "nothing to say". */
|
||||
contextEmptyFraction: 0.85,
|
||||
});
|
||||
|
||||
const SEARCH_TOOLS = new Set(['web_search']);
|
||||
const SEARCH_FAILED = /web search is limited|search could not reach|could not reach the internet|WEB_RATE_LIMITED|WEB_PROVIDER_ERROR|did not accept the key|too many searches/i;
|
||||
|
||||
/** The plain sentences, keyed by reason. `values` are the slots the page fills in. */
|
||||
const NOTES = {
|
||||
'searches-failed': 'Web search is limited right now, so I stopped searching and went on with what I have. Try again in a minute, or add a search key in Settings → Tools → Web search.',
|
||||
searches: 'I searched a lot and stopped so this chat does not fill up. This is what I have so far. Tell me what to look into next.',
|
||||
rewrites: 'I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.',
|
||||
context: 'I ran out of room in this chat, so I stopped. Strata is summarising the older messages to make space. Say “continue” to go on, or start a new chat.',
|
||||
empty: 'I stopped without writing an answer. Send your message again, or say “continue”.',
|
||||
};
|
||||
export const GUARD_NOTES = Object.freeze({ ...NOTES });
|
||||
|
||||
/** A `delta` frame the page shows as ordinary assistant text and translates (`key` is the English sentence). */
|
||||
export function guardNote(reason) {
|
||||
const text = NOTES[reason];
|
||||
return text ? { type: 'delta', own: true, text: `\n\n${text}`, key: text, noteReason: reason } : null;
|
||||
}
|
||||
|
||||
export class TurnGuard {
|
||||
/**
|
||||
* @param {{plan?: boolean, contextMax?: number, limits?: Partial<typeof GUARD_LIMITS>}} [options]
|
||||
*/
|
||||
constructor({ plan = false, contextMax = 0, limits = {} } = {}) {
|
||||
this.plan = plan; this.contextMax = Number(contextMax) || 0;
|
||||
this.limits = { ...GUARD_LIMITS, ...limits };
|
||||
this.seen = new Set();
|
||||
this.searches = 0; this.failedInARow = 0; this.failedTotal = 0;
|
||||
this.rewrites = 0; this.written = '';
|
||||
this.reason = null;
|
||||
}
|
||||
|
||||
#fire(reason) { this.reason ??= reason; return this.reason; }
|
||||
|
||||
/** A tool card frame (`agent-tool`). Counts a search once, when it has finished. Returns the reason to stop, or null. */
|
||||
card(tool) {
|
||||
if (this.reason || !tool || !SEARCH_TOOLS.has(tool.name)) return this.reason;
|
||||
const done = tool.state === 'done' || tool.state === 'error' || tool.state === 'denied';
|
||||
if (!done || this.seen.has(tool.id)) return this.reason;
|
||||
this.seen.add(tool.id);
|
||||
this.searches += 1;
|
||||
const failed = tool.state === 'error' || SEARCH_FAILED.test(String(tool.result ?? ''));
|
||||
if (failed) { this.failedInARow += 1; this.failedTotal += 1; } else this.failedInARow = 0;
|
||||
if (this.failedInARow >= this.limits.failedSearches) return this.#fire('searches-failed');
|
||||
if (this.searches >= (this.plan ? this.limits.searchesPlan : this.limits.searchesTurn)) return this.#fire(this.failedTotal >= this.searches / 2 ? 'searches-failed' : 'searches');
|
||||
return this.reason;
|
||||
}
|
||||
|
||||
/** Text the assistant wrote (not our own lines). A plan turn that starts its numbered list again and again is rewriting. */
|
||||
text(delta) {
|
||||
if (this.reason || !this.plan || !delta) return this.reason;
|
||||
this.written += delta;
|
||||
if (this.written.length > 200_000) this.written = this.written.slice(-100_000);
|
||||
if (!delta.includes('\n') && !/\d[.)]\s/.test(delta)) return this.reason;
|
||||
this.rewrites = (this.written.match(/(?:^|\n)[ \t]{0,3}1[.)][ \t]+\S/g) ?? []).length;
|
||||
if (this.rewrites >= this.limits.planRewrites) return this.#fire('rewrites');
|
||||
return this.reason;
|
||||
}
|
||||
|
||||
/** What the context holds now (tokens of the last request). */
|
||||
context(tokens) {
|
||||
if (this.reason || !this.contextMax || !Number.isFinite(tokens)) return this.reason;
|
||||
if (tokens / this.contextMax >= this.limits.contextFraction) return this.#fire('context');
|
||||
return this.reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn is over. If the person has seen no words from it, which sentence do they get? `ended` is the Harness's turn end reason,
|
||||
* `wrote` whether any answer text was shown, `acted` whether tool cards were shown, `contextTokens` the last request's size. Returns a reason or null.
|
||||
*/
|
||||
silent({ ended, wrote, contextTokens, acted = false, stoppedByPerson = false }) {
|
||||
if (this.reason) return this.reason;
|
||||
if (stoppedByPerson || wrote) return null;
|
||||
const kind = ended?.kind;
|
||||
if (kind !== 'completed' && kind !== 'max-tokens') return null; // an error says why by itself; Stop is the person's own
|
||||
if (this.contextMax && Number(contextTokens) / this.contextMax >= this.limits.contextEmptyFraction) return 'context';
|
||||
return acted ? null : 'empty'; // cards of work done are an answer of a kind; no cards and no words is not
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Anthropic clients add `/v1/messages` to the base URL themselves, so the base URL they are given is the server root (no `/v1`).
|
||||
* A base URL copied from an OpenAI-style setup ends in `/v1`, and the client then posts `/v1/v1/messages`. That one path means the
|
||||
* same as the real one; nothing else is aliased (an OpenAI client never adds `/v1` on its own).
|
||||
*/
|
||||
const ALIASES = new Map([['/v1/v1/messages', '/v1/messages'], ['/v1/v1/messages/count_tokens', '/v1/messages/count_tokens']]);
|
||||
|
||||
export function apiPath(path) {
|
||||
const clean = path.length > 1 ? path.replace(/\/+$/, '') : path;
|
||||
return ALIASES.get(clean) ?? path;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ import { CONTEXT_TOKENS, VARIANTS, localModels, variant } from './catalog.mjs';
|
||||
import { browseLocalModels, inspectLocalModel } from './local-models.mjs';
|
||||
import { EventHub, error, json, readBody, readRaw, uid } from './util.mjs';
|
||||
import { createUploads } from './chat-uploads.mjs';
|
||||
import { createNativeDrops } from './native-drop.mjs';
|
||||
import { createVisionProbe, effectiveVision, readsPicturesByDefault } from './vision-probe.mjs';
|
||||
import { RequestQueue } from './request-queue.mjs';
|
||||
import { selectSkills, skillInstructions } from './skill-selection.mjs';
|
||||
@@ -69,6 +70,7 @@ import { forbidden as acquisitionForbidden } from './acquisition.mjs';
|
||||
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
import { nativeGateway } from './native-gateway.mjs';
|
||||
import { proxyCompletion } from './inference.mjs';
|
||||
import { apiPath } from './api-paths.mjs';
|
||||
import { validateChatImages } from './chat-images.mjs';
|
||||
import { createTimeSkip, measureFolder, timeskipRevisionMessage, imageTypeOf } from './timeskip.mjs';
|
||||
|
||||
@@ -464,6 +466,7 @@ function loadWorkspaces() {
|
||||
let workspaces = loadWorkspaces();
|
||||
/* The folder each chat works in ("Select a folder"): the agent's working folder and sandbox for that chat. */
|
||||
const chatAttachments = createAttachments();
|
||||
const nativeDrops = createNativeDrops();
|
||||
const uploads = createUploads({ dir: join(store.DATA_DIR, 'uploads'), folderOf: chatId => chatFolders.get(chatId) ?? workspaces[0]?.path ?? WORKSPACE, attachments: chatAttachments });
|
||||
try { uploads.sweep(); } catch { /* best effort */ }
|
||||
const chatFolders = createChatFolders({ file: join(store.DATA_DIR, 'chat-folders.json') });
|
||||
@@ -926,7 +929,7 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (path.startsWith('/v1/')) {
|
||||
if (storageChanging && method !== 'GET') return error(res, 409, 'Wait for the model folder check to finish.');
|
||||
return await openai(req, res, path, method);
|
||||
return await openai(req, res, apiPath(path), method);
|
||||
}
|
||||
return await staticFile(req, res, path);
|
||||
} catch (err) {
|
||||
@@ -1271,6 +1274,18 @@ async function api(req, res, path, method, url) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Files dropped on the app window (Linux, macOS): the shell hands over the paths, the page fetches each file once (native-drop.mjs).
|
||||
if (path === '/api/app/drop' && method === 'POST') {
|
||||
if (!fromShell()) return error(res, 403, 'Not allowed.');
|
||||
try { return json(res, 200, { files: await nativeDrops.add((await readBody(req)).paths) }); } catch (err) { return error(res, 400, err.message); }
|
||||
}
|
||||
const dropGet = /^\/api\/app\/drop\/([0-9a-f-]{36})$/.exec(path);
|
||||
if (dropGet && method === 'GET') {
|
||||
const file = nativeDrops.take(dropGet[1]);
|
||||
if (!file) return error(res, 404, 'That file is no longer available. Drop it again.');
|
||||
res.writeHead(200, { 'content-type': file.type, 'content-length': file.bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); res.end(file.bytes); return undefined;
|
||||
}
|
||||
|
||||
if (path === '/api/setup' && method === 'GET') return json(res, 200, setupState());
|
||||
if (path === '/api/updates/check' && method === 'GET' && control?.updateCheck) return json(res, 200, await checkComponentUpdates({ control, appUpdater, appVersion: process.env.STRATA_APP_VERSION || null }));
|
||||
if (path === '/api/updates/check' && method === 'GET') return json(res, 200, await checkUpdates({ appVersion:appVersionToShow(setupState().app.version,native.state().version), engineVersion:native.state().available?(native.state().installed?.engine?.version??null):(await engine.config()).engine.version }));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** A separate, key-protected listener for inference only. Never serves the UI or host APIs. */
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import { apiPath } from './api-paths.mjs';
|
||||
export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0.0.0.0', port = 8792 }) {
|
||||
let listener = null, active = false;
|
||||
const address = () => Object.values(os.networkInterfaces()).flat().find(n => n?.family === 'IPv4' && !n.internal)?.address ?? '127.0.0.1';
|
||||
@@ -10,7 +11,7 @@ export function createLocalShare({ handle, hasKey, changed = () => {}, host = '0
|
||||
if (listener) throw new Error('Sharing is already starting.');
|
||||
if (!hasKey()) throw new Error('Set an API key before sharing with other devices.');
|
||||
listener = http.createServer(async (req, res) => {
|
||||
const path = new URL(req.url ?? '/', 'http://localhost').pathname;
|
||||
const path = apiPath(new URL(req.url ?? '/', 'http://localhost').pathname);
|
||||
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'); }
|
||||
catch { if (!res.headersSent) res.writeHead(500); res.end('Request failed'); }
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Files dropped on the app window (Linux and macOS).
|
||||
*
|
||||
* The page cannot read a dragged file there: WebKit gives it the drag events but no files. The app shell sees the drop with the real paths and
|
||||
* hands them to the host with its shell secret (POST /api/app/drop); the host reads the files and keeps them for a short time under
|
||||
* unguessable ids; the page asks for each id once (GET /api/app/drop/<id>) and attaches the files as if they had been dropped in a browser.
|
||||
* Only regular files up to MAX_BYTES, at most MAX_FILES per drop; folders and anything else are skipped.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { readFile, stat } from 'node:fs/promises';
|
||||
import { basename, extname, isAbsolute } from 'node:path';
|
||||
|
||||
export const MAX_FILES = 10, MAX_BYTES = 25 * 1024 * 1024, KEEP_MS = 2 * 60_000;
|
||||
|
||||
const TYPES = {
|
||||
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp',
|
||||
txt: 'text/plain', md: 'text/markdown', markdown: 'text/markdown', csv: 'text/csv', json: 'application/json', log: 'text/plain',
|
||||
html: 'text/html', htm: 'text/html', xml: 'text/xml', yaml: 'text/yaml', yml: 'text/yaml', pdf: 'application/pdf',
|
||||
};
|
||||
export const typeOfName = name => TYPES[extname(String(name)).slice(1).toLowerCase()] ?? 'application/octet-stream';
|
||||
|
||||
export function createNativeDrops({ now = Date.now, read = readFile, info = stat } = {}) {
|
||||
const held = new Map(); // id -> { name, type, bytes, at }
|
||||
const sweep = () => { for (const [id, f] of held) if (now() - f.at > KEEP_MS) held.delete(id); };
|
||||
return {
|
||||
/** Read the dropped paths; answer what the page may ask for: [{ id, name, type, size }]. */
|
||||
async add(paths) {
|
||||
sweep();
|
||||
const out = [];
|
||||
for (const raw of (Array.isArray(paths) ? paths : []).slice(0, MAX_FILES)) {
|
||||
const path = typeof raw === 'string' ? raw : '';
|
||||
if (!path || path.includes('\0') || !isAbsolute(path)) continue;
|
||||
try {
|
||||
const st = await info(path);
|
||||
if (!st.isFile() || st.size > MAX_BYTES) continue;
|
||||
const bytes = await read(path);
|
||||
const id = randomUUID();
|
||||
const name = basename(path);
|
||||
held.set(id, { name, type: typeOfName(name), bytes, at: now() });
|
||||
out.push({ id, name, type: typeOfName(name), size: bytes.length });
|
||||
} catch { /* an unreadable file is skipped, the rest still arrive */ }
|
||||
}
|
||||
return out;
|
||||
},
|
||||
/** One use per id. */
|
||||
take(id) { sweep(); const f = held.get(id); if (f) held.delete(id); return f ?? null; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* The second keyless source for the agent's web search: Bing's plain result page, used only when DuckDuckGo refuses.
|
||||
*
|
||||
* It is read the way a browser reads it (an ordinary User-Agent, the page's own request shape, nothing hidden) and is held to the same
|
||||
* manners as DuckDuckGo (see web-search-ddg.mjs): one request at a time, spaced out, a cooldown after a refusal. Results are not ranked or
|
||||
* filtered here. Pure parsing lives in this file so it can be tested on saved pages.
|
||||
*/
|
||||
|
||||
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/', '#183': '·' };
|
||||
const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => {
|
||||
if (key[0] === '#') {
|
||||
const code = key[1].toLowerCase() === 'x' ? parseInt(key.slice(2), 16) : parseInt(key.slice(1), 10);
|
||||
return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : whole;
|
||||
}
|
||||
return ENTITIES[key.toLowerCase()] ?? whole;
|
||||
});
|
||||
const plain = html => decode(String(html).replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim();
|
||||
|
||||
export const BING_URL = 'https://www.bing.com/search';
|
||||
|
||||
/** Bing wraps every result link in its own redirect (`/ck/a?...&u=a1<base64url of the real address>`). */
|
||||
export function bingTarget(href) {
|
||||
const value = decode(href).trim();
|
||||
try {
|
||||
const url = new URL(value, 'https://www.bing.com/');
|
||||
if (/(^|\.)bing\.com$/i.test(url.hostname)) {
|
||||
const u = url.searchParams.get('u');
|
||||
if (u && /^a1/.test(u)) {
|
||||
const target = Buffer.from(u.slice(2).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
|
||||
const real = new URL(target);
|
||||
return /^https?:$/.test(real.protocol) ? real.href : null;
|
||||
}
|
||||
return null; // Bing's own page (images, maps, "more results")
|
||||
}
|
||||
return /^https?:$/.test(url.protocol) ? url.href : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** The result list of the page. Tolerant: a result needs a link and a title; the snippet is optional. */
|
||||
export function parseBingResults(html) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
const blocks = String(html).split(/<li\b[^>]*\bclass="[^"]*\bb_algo\b[^"]*"/i).slice(1);
|
||||
for (const block of blocks) {
|
||||
const end = block.search(/<li\b[^>]*\bclass="[^"]*\bb_(?:algo|ans|ad|pag)\b/i);
|
||||
const body = end > 0 ? block.slice(0, end) : block;
|
||||
const h2 = /<h2\b[^>]*>\s*<a\b([^>]*)>([\s\S]*?)<\/a>/i.exec(body);
|
||||
if (!h2) continue;
|
||||
const href = /\bhref="([^"]*)"/i.exec(h2[1])?.[1];
|
||||
const url = href ? bingTarget(href) : null;
|
||||
const title = plain(h2[2]);
|
||||
if (!url || !title || seen.has(url)) continue;
|
||||
const snippetMatch = /<p\b[^>]*class="[^"]*\bb_lineclamp\d*\b[^"]*"[^>]*>([\s\S]*?)<\/p>/i.exec(body)
|
||||
?? /<div\b[^>]*class="[^"]*\bb_caption\b[^"]*"[^>]*>[\s\S]*?<p\b[^>]*>([\s\S]*?)<\/p>/i.exec(body);
|
||||
const snippet = snippetMatch ? plain(snippetMatch[1]) : '';
|
||||
seen.add(url);
|
||||
out.push({ url, title, ...(snippet ? { snippet } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Bing serves a challenge page, or a refusal, instead of results. A page with results is never "blocked". */
|
||||
export function bingLooksBlocked(status, html) {
|
||||
if (status === 403 || status === 429 || status === 503) return true;
|
||||
const text = String(html).slice(0, 80000);
|
||||
if (/\bclass="[^"]*\bb_algo\b/.test(text)) return false;
|
||||
return /captcha|unusual traffic|are you a robot|verify you are (?:a )?human|\bcf-chl|challenge-platform/i.test(text);
|
||||
}
|
||||
@@ -1,28 +1,39 @@
|
||||
/**
|
||||
* Web search with no account and no key: DuckDuckGo's own web-page search results.
|
||||
* Web search with no account and no key: DuckDuckGo's own web-page search results, with Bing's plain result page as the second source.
|
||||
*
|
||||
* The Harness has three search backends and all of them need a paid service key. This is the fourth: it asks DuckDuckGo's plain
|
||||
* HTML search page the way a browser does and reads the result list out of the page. It is the default for the agent's
|
||||
* `web_search` tool; the person can switch to a keyed service in Settings -> Tools.
|
||||
*
|
||||
* Being polite is part of the design:
|
||||
* - an ordinary browser User-Agent and the page's own request shape (nothing hidden, nothing faked beyond the User-Agent);
|
||||
* - at most one request every 1.5 s and 20 a minute from this program, with the same query answered from a 10 minute cache;
|
||||
* - a 15 s time limit, no retries in a loop; when DuckDuckGo asks for a human check or refuses, the answer says so in plain
|
||||
* words and the model is told to carry on without search.
|
||||
* Results come from DuckDuckGo; they are not ranked or filtered here.
|
||||
* Being polite is part of the design, because DuckDuckGo refuses a program that asks too fast (2026-10-18, a Linux box: two searches in
|
||||
* 1.2 s were answered, the third got HTTP 202 "anomaly" and every DuckDuckGo page then refused for minutes):
|
||||
* - an ordinary browser User-Agent and the page's own request shape (Referer, Origin, Sec-Fetch-*; nothing hidden);
|
||||
* - one request at a time per source, 2.5 to 4 s apart (random, so it does not look like a clock), at most 8 a minute;
|
||||
* - the same question is answered from a session cache (30 minutes), so a model that repeats itself costs nothing;
|
||||
* - when a source refuses (HTTP 202/403/429 or a challenge page) it is left alone for a cooldown that doubles every time it refuses
|
||||
* again (1, 2, 4 ... up to 10 minutes; a Retry-After header is honoured) instead of being asked again, which only extends a block;
|
||||
* - a refused DuckDuckGo page is not followed by the lite page (same refusal, one more strike): the next source is tried instead;
|
||||
* - a timeout or a server error gets one retry after a short pause, then the next source;
|
||||
* - when every source refuses the answer is one plain sentence that also tells the model not to retry (see LIMITED_MESSAGE).
|
||||
* Results come from DuckDuckGo or Bing; they are not ranked or filtered here.
|
||||
*
|
||||
* Nothing in this file touches the Harness, so it can be tested alone. `strata-search.mjs` is the plugin that registers it.
|
||||
*/
|
||||
import { BING_URL, bingLooksBlocked, parseBingResults } from './web-search-bing.mjs';
|
||||
|
||||
export const DDG_PROVIDER_ID = 'strata-duckduckgo';
|
||||
|
||||
const HTML_URL = 'https://html.duckduckgo.com/html/';
|
||||
const LITE_URL = 'https://lite.duckduckgo.com/lite/';
|
||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36';
|
||||
const CACHE_MS = 10 * 60 * 1000;
|
||||
const MIN_GAP_MS = 1500;
|
||||
const PER_MINUTE = 20;
|
||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
|
||||
const CACHE_MS = 30 * 60 * 1000;
|
||||
const CACHE_SIZE = 120;
|
||||
const GAP_MS = 2500;
|
||||
const JITTER_MS = 1500;
|
||||
const PER_MINUTE = 8;
|
||||
const COOLDOWN_MS = 60_000;
|
||||
const COOLDOWN_MAX_MS = 10 * 60_000;
|
||||
const RETRY_PAUSE_MS = 1500;
|
||||
|
||||
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'", '#x27': "'", '#x2F': '/' };
|
||||
const decode = text => String(text).replace(/&(#x?[0-9a-f]+|[a-z]+);/gi, (whole, key) => {
|
||||
@@ -106,83 +117,148 @@ export function looksBlocked(status, html) {
|
||||
&& !/class="[^"]*\bresult__a\b/.test(html);
|
||||
}
|
||||
|
||||
|
||||
export class SearchUnavailable extends Error {
|
||||
constructor(message, code = 'WEB_PROVIDER_ERROR', options) { super(message, options); this.name = 'WebError'; this.code = code; }
|
||||
}
|
||||
|
||||
export const BLOCKED_MESSAGE = 'DuckDuckGo is limiting searches from this computer right now. Try again in a few minutes, or add a search key in Settings, Tools.';
|
||||
/** The one plain sentence for the person. The words "Settings → Tools → Web search" are where the key goes in the app. */
|
||||
export const LIMITED_SENTENCE = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search.';
|
||||
/** What the tool answers: the sentence, then what the model should do (it must not keep searching). */
|
||||
export const BLOCKED_MESSAGE = `${LIMITED_SENTENCE} Do not retry this search: go on with what you know and tell the person, in one plain sentence, that web search was limited.`;
|
||||
export const UNREACHABLE_MESSAGE = 'The search could not reach the internet. Check the connection and try again. Do not retry this search now: go on with what you know and say that search was unavailable.';
|
||||
|
||||
/**
|
||||
* @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise<void>}} [deps]
|
||||
*/
|
||||
export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)) } = {}) {
|
||||
const cache = new Map();
|
||||
const starts = [];
|
||||
let last = 0;
|
||||
let chain = Promise.resolve();
|
||||
|
||||
/** One request at a time, spaced out, and at most PER_MINUTE a minute. */
|
||||
function turn(signal) {
|
||||
const run = chain.then(async () => {
|
||||
/** One request at a time, spaced out with a little randomness, and at most PER_MINUTE a minute. */
|
||||
class Pacer {
|
||||
constructor({ now, sleep, random, gap = GAP_MS, jitter = JITTER_MS, perMinute = PER_MINUTE }) {
|
||||
Object.assign(this, { now, sleep, random, gap, jitter, perMinute });
|
||||
this.starts = []; this.last = 0; this.chain = Promise.resolve();
|
||||
}
|
||||
turn(signal) {
|
||||
const run = this.chain.then(async () => {
|
||||
const spacing = this.gap + Math.floor(this.random() * this.jitter);
|
||||
for (;;) {
|
||||
signal?.throwIfAborted();
|
||||
const t = now();
|
||||
while (starts.length && t - starts[0] > 60_000) starts.shift();
|
||||
const wait = Math.max(MIN_GAP_MS - (t - last), starts.length >= PER_MINUTE ? 60_000 - (t - starts[0]) : 0);
|
||||
if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED');
|
||||
const t = this.now();
|
||||
while (this.starts.length && t - this.starts[0] > 60_000) this.starts.shift();
|
||||
const wait = this.last ? Math.max(spacing - (t - this.last), this.starts.length >= this.perMinute ? 60_000 - (t - this.starts[0]) : 0) : 0;
|
||||
if (wait <= 0) break;
|
||||
if (wait > 30_000) throw new SearchUnavailable('Too many searches in a short time. Try again in a minute.', 'WEB_RATE_LIMITED');
|
||||
await sleep(wait);
|
||||
if (wait > 30_000) throw new SearchUnavailable(LIMITED_SENTENCE, 'WEB_RATE_LIMITED');
|
||||
await this.sleep(wait);
|
||||
}
|
||||
last = now();
|
||||
starts.push(last);
|
||||
this.last = this.now();
|
||||
this.starts.push(this.last);
|
||||
});
|
||||
chain = run.catch(() => {});
|
||||
this.chain = run.catch(() => {});
|
||||
return run;
|
||||
}
|
||||
}
|
||||
|
||||
async function ask(url, query, signal) {
|
||||
const REFUSED = Symbol('refused');
|
||||
const retryAfterMs = res => {
|
||||
const v = Number(res?.headers?.get?.('retry-after'));
|
||||
return Number.isFinite(v) && v > 0 ? Math.min(v * 1000, COOLDOWN_MAX_MS) : 0;
|
||||
};
|
||||
const serverError = status => status >= 500 && status < 600;
|
||||
const queryKey = query => query.toLowerCase().replace(/\s+/g, ' ').trim();
|
||||
|
||||
/**
|
||||
* @param {{fetch?: typeof fetch, now?: () => number, sleep?: (ms: number) => Promise<void>, random?: () => number}} [deps]
|
||||
*/
|
||||
export function createDuckDuckGoSearch({ fetch: fetchImpl = globalThis.fetch, now = Date.now, sleep = ms => new Promise(r => setTimeout(r, ms)), random = Math.random } = {}) {
|
||||
const cache = new Map();
|
||||
|
||||
/** A source: its pacing, and what to do after it refuses. */
|
||||
const source = (id, name) => ({ id, name, pacer: new Pacer({ now, sleep, random }), blockedUntil: 0, strikes: 0, refusals: 0 });
|
||||
const ddg = source('duckduckgo', 'DuckDuckGo');
|
||||
const bing = source('bing', 'Bing');
|
||||
const refuse = (s, res) => {
|
||||
s.strikes += 1; s.refusals += 1;
|
||||
s.blockedUntil = now() + Math.max(retryAfterMs(res), Math.min(COOLDOWN_MS * 2 ** (s.strikes - 1), COOLDOWN_MAX_MS));
|
||||
};
|
||||
const accepted = s => { s.strikes = 0; s.blockedUntil = 0; };
|
||||
|
||||
const headers = (origin, extra = {}) => ({
|
||||
'user-agent': USER_AGENT, accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'accept-language': 'en-US,en;q=0.9',
|
||||
'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'same-origin', 'sec-fetch-user': '?1',
|
||||
...(origin ? { referer: `${origin}/`, origin } : {}), ...extra,
|
||||
});
|
||||
|
||||
async function get(url, init, signal) {
|
||||
const timeout = AbortSignal.timeout(15_000);
|
||||
const res = await fetchImpl(url, {
|
||||
method: 'POST', redirect: 'follow',
|
||||
headers: { 'user-agent': USER_AGENT, 'content-type': 'application/x-www-form-urlencoded', accept: 'text/html,application/xhtml+xml', 'accept-language': 'en-US,en;q=0.8' },
|
||||
body: new URLSearchParams({ q: query, b: '' }).toString(),
|
||||
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
||||
});
|
||||
const html = await res.text();
|
||||
return { status: res.status, html };
|
||||
const res = await fetchImpl(url, { redirect: 'follow', ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
|
||||
return { res, status: res.status, html: await res.text() };
|
||||
}
|
||||
|
||||
/** One page request with one retry after a pause for a timeout, a network error or a server error. Throws SearchUnavailable only for cancel. */
|
||||
async function ask(s, makeRequest, signal) {
|
||||
let failure;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
await s.pacer.turn(signal);
|
||||
try {
|
||||
const page = await get(...makeRequest(), signal);
|
||||
if (!serverError(page.status)) return page;
|
||||
failure = new Error(`HTTP ${page.status}`);
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error });
|
||||
failure = error;
|
||||
}
|
||||
if (attempt === 0) await sleep(RETRY_PAUSE_MS + Math.floor(random() * 1000));
|
||||
}
|
||||
return { failure };
|
||||
}
|
||||
|
||||
async function searchDuckDuckGo(query, signal) {
|
||||
const form = new URLSearchParams({ q: query, b: '', kl: 'wt-wt', df: '' }).toString();
|
||||
const post = (url, origin) => () => [url, { method: 'POST', headers: headers(origin, { 'content-type': 'application/x-www-form-urlencoded' }), body: form }];
|
||||
let reachedOnce = false;
|
||||
for (const [url, origin, parse] of [[HTML_URL, 'https://html.duckduckgo.com', parseHtmlResults], [LITE_URL, 'https://lite.duckduckgo.com', parseLiteResults]]) {
|
||||
const page = await ask(ddg, post(url, origin), signal);
|
||||
if (page.failure) return { failure: page.failure };
|
||||
reachedOnce = true;
|
||||
// A refusal on the first page is a refusal for the whole address: the lite page would only add one more strike.
|
||||
if (looksBlocked(page.status, page.html)) { refuse(ddg, page.res); return { refused: true }; }
|
||||
const sources = parse(page.html);
|
||||
if (sources.length) { accepted(ddg); return { sources }; }
|
||||
}
|
||||
if (reachedOnce) accepted(ddg);
|
||||
return { sources: [] };
|
||||
}
|
||||
|
||||
async function searchBing(query, signal) {
|
||||
const url = `${BING_URL}?${new URLSearchParams({ q: query, setlang: 'en' })}`;
|
||||
const page = await ask(bing, () => [url, { method: 'GET', headers: headers(null) }], signal);
|
||||
if (page.failure) return { failure: page.failure };
|
||||
if (bingLooksBlocked(page.status, page.html)) { refuse(bing, page.res); return { refused: true }; }
|
||||
accepted(bing);
|
||||
return { sources: parseBingResults(page.html) };
|
||||
}
|
||||
|
||||
return {
|
||||
id: DDG_PROVIDER_ID,
|
||||
available: () => typeof fetchImpl === 'function',
|
||||
/** What happened so far, for tests and for the status line in the app's log. */
|
||||
status: () => ({ duckduckgo: { strikes: ddg.strikes, refusals: ddg.refusals, blockedForMs: Math.max(0, ddg.blockedUntil - now()) }, bing: { strikes: bing.strikes, refusals: bing.refusals, blockedForMs: Math.max(0, bing.blockedUntil - now()) }, cached: cache.size }),
|
||||
async search(request, signal) {
|
||||
const query = String(request.query ?? '').trim().slice(0, 400);
|
||||
if (!query) throw new SearchUnavailable('Type what to search for.', 'WEB_PROVIDER_ERROR');
|
||||
const key = query.toLowerCase();
|
||||
const key = queryKey(query);
|
||||
const want = request.maxResults ?? 10;
|
||||
const hit = cache.get(key);
|
||||
if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, request.maxResults ?? 10), truncated: false };
|
||||
let sources = [];
|
||||
let blocked = false;
|
||||
for (const [url, parse] of [[HTML_URL, parseHtmlResults], [LITE_URL, parseLiteResults]]) {
|
||||
await turn(signal);
|
||||
let page;
|
||||
try { page = await ask(url, query, signal); }
|
||||
catch (error) {
|
||||
if (signal?.aborted) throw new SearchUnavailable('The search was cancelled.', 'WEB_ABORTED', { cause: error });
|
||||
if (error?.name === 'TimeoutError') throw new SearchUnavailable('The search took too long. Try again.', 'WEB_TIMEOUT', { cause: error });
|
||||
throw new SearchUnavailable('The search could not reach DuckDuckGo. Check the internet connection and try again.', 'WEB_PROVIDER_ERROR', { cause: error });
|
||||
}
|
||||
if (looksBlocked(page.status, page.html)) { blocked = true; continue; }
|
||||
sources = parse(page.html);
|
||||
if (sources.length) { blocked = false; break; }
|
||||
if (hit && now() - hit.at < CACHE_MS) return { sources: hit.sources.slice(0, want), truncated: false };
|
||||
let limited = false, unreachable = false;
|
||||
for (const [s, run] of [[ddg, searchDuckDuckGo], [bing, searchBing]]) {
|
||||
if (s.blockedUntil > now()) { limited = true; continue; } // asked again too soon: that only extends a block
|
||||
const result = await run(query, signal);
|
||||
if (result.refused) { limited = true; continue; }
|
||||
if (result.failure) { unreachable = true; continue; }
|
||||
if (!result.sources.length) return { sources: [], truncated: false }; // a real search with no results is an answer, not an error
|
||||
cache.set(key, { at: now(), sources: result.sources });
|
||||
if (cache.size > CACHE_SIZE) cache.delete(cache.keys().next().value);
|
||||
return { sources: result.sources.slice(0, want), truncated: false };
|
||||
}
|
||||
if (!sources.length) {
|
||||
if (blocked) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED');
|
||||
return { sources: [], truncated: false }; // a real search with no results is an answer, not an error
|
||||
}
|
||||
cache.set(key, { at: now(), sources });
|
||||
if (cache.size > 60) cache.delete(cache.keys().next().value);
|
||||
return { sources: sources.slice(0, request.maxResults ?? 10), truncated: false };
|
||||
if (limited) throw new SearchUnavailable(BLOCKED_MESSAGE, 'WEB_RATE_LIMITED');
|
||||
throw new SearchUnavailable(unreachable ? UNREACHABLE_MESSAGE : BLOCKED_MESSAGE, unreachable ? 'WEB_PROVIDER_ERROR' : 'WEB_RATE_LIMITED');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useRef, useState, type ReactNode } from 'react';
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { NATIVE_DRAG_EVENT, NATIVE_DROP_EVENT, dragHasFiles, fetchDropped, readDroppedRefs } from '../lib/native-drop';
|
||||
import { pushToast } from '../lib/store';
|
||||
import { tr } from '../lib/i18n';
|
||||
import { Icon } from './ui';
|
||||
|
||||
@@ -16,10 +18,32 @@ export function pastedFiles(data: DataTransfer | null | undefined): File[] {
|
||||
}
|
||||
const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files');
|
||||
|
||||
/** A file dropped outside the chat must not take the window to that file: the page ignores it (called once at start). */
|
||||
export function installDropGuard() {
|
||||
const guard = (e: DragEvent) => { if (!e.defaultPrevented && dragHasFiles(e.dataTransfer?.types)) e.preventDefault(); };
|
||||
window.addEventListener('dragover', guard);
|
||||
window.addEventListener('drop', guard);
|
||||
}
|
||||
|
||||
/** The conversation column, with a calm highlight while something is dragged over it. */
|
||||
export function DropZone({ children, className }: { children: ReactNode; className?: string }) {
|
||||
const [over, setOver] = useState(false);
|
||||
const depth = useRef(0);
|
||||
// Linux and macOS: the app shell reports the drag and the drop (the page is not given the files there).
|
||||
useEffect(() => {
|
||||
const drag = (e: Event) => setOver((e as CustomEvent).detail === 'enter');
|
||||
const drop = (e: Event) => {
|
||||
setOver(false); depth.current = 0;
|
||||
const refs = readDroppedRefs((e as CustomEvent).detail);
|
||||
if (!refs.length) return;
|
||||
void fetchDropped(refs).then(files => {
|
||||
if (files.length) window.dispatchEvent(new CustomEvent(DROP_EVENT, { detail: files }));
|
||||
else pushToast('error', tr('The file was not added'), tr('Try dropping it again.'));
|
||||
});
|
||||
};
|
||||
window.addEventListener(NATIVE_DRAG_EVENT, drag); window.addEventListener(NATIVE_DROP_EVENT, drop);
|
||||
return () => { window.removeEventListener(NATIVE_DRAG_EVENT, drag); window.removeEventListener(NATIVE_DROP_EVENT, drop); };
|
||||
}, []);
|
||||
return <div className={className} data-dropping={over || undefined}
|
||||
onDragEnter={e => { if (!hasFiles(e)) return; e.preventDefault(); depth.current++; setOver(true); }}
|
||||
onDragOver={e => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }}
|
||||
|
||||
@@ -59,6 +59,7 @@ export function PlanCard({ chatId, planId }: { chatId: string | null | undefined
|
||||
return <section className="plan" data-state={plan.state} aria-label={tr("Plan")}>
|
||||
<div className="plan__head"><b>{tr("Plan")}</b><span>{planCount(plan)}</span></div>
|
||||
<PlanSteps plan={plan}/>
|
||||
{plan.caution ? <p className="plan__note" role="status">{tr(plan.caution)}</p> : null}
|
||||
{proposed ? <p className="plan__note">{tr("Nothing runs until you approve.")}</p> : null}
|
||||
{proposed ? <div className="plan__acts">
|
||||
<Btn size="sm" variant="primary" icon="check" disabled={busy || streaming} onClick={() => void run(() => approvePlan(chatId, plan.id))}>{tr("Approve")}</Btn>
|
||||
|
||||
@@ -130,7 +130,7 @@ export function SettingsTools({ preview }: { preview?: ToolsState }) {
|
||||
<section className="settings-section">
|
||||
<h2 className="h4" style={{ marginBottom: 10 }}>{tr('Web search')}</h2>
|
||||
<div className="st-card st-card--flush">
|
||||
<Field label={tr('Where results come from')} hint={tr(keyed ? 'Searches use your own account with this service.' : 'Results come from DuckDuckGo. You do not need an account or a key.')}>
|
||||
<Field label={tr('Where results come from')} hint={tr(keyed ? 'Searches use your own account with this service.' : 'Results come from DuckDuckGo, or from Bing when DuckDuckGo is busy. You do not need an account or a key.')}>
|
||||
<Select ariaLabel={tr('Where results come from')} value={state.search.provider} options={SEARCH_CHOICES} onChange={value => { setKey(''); void save({ search: { provider: value } }); }} />
|
||||
</Field>
|
||||
{keyed ? <Field label={tr('Your key')} hint={tr(state.search.keySet ? 'A key is saved on this computer. Enter a new one to replace it.' : 'Saved on this computer only. Strata never shows it again.')}>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* The address an app is given depends on who builds the final request URL.
|
||||
*
|
||||
* OpenAI-style clients (Chat Completions, Responses) are given the base that ends in /v1 and add /chat/completions or /responses.
|
||||
* Anthropic-style clients (Claude Code, the Anthropic SDKs) add /v1/messages themselves, so they are given the server root. With
|
||||
* the /v1 base they post /v1/v1/messages.
|
||||
*/
|
||||
export type ConnectProtocol = 'openai' | 'responses' | 'anthropic';
|
||||
|
||||
/** The server root: the base address without its trailing /v1. */
|
||||
export function serverRoot(baseUrl: string): string {
|
||||
return String(baseUrl ?? '').trim().replace(/\/+$/, '').replace(/\/v1$/i, '');
|
||||
}
|
||||
|
||||
/** The address to type into an app that speaks this protocol. */
|
||||
export function appBaseUrl(baseUrl: string, protocol: ConnectProtocol): string {
|
||||
return protocol === 'anthropic' ? serverRoot(baseUrl) : String(baseUrl ?? '').trim().replace(/\/+$/, '');
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { tr } from './i18n';
|
||||
import { LOOP_MAX_FAILURES, LOOP_MAX_RUNS, judgeAnswer, loopEndNote, loopEvery, loopLimitNote, withStopRule, type LoopLimits, type LoopStop } from './loop';
|
||||
|
||||
/**
|
||||
* The /loop scheduler. It owns the timer, the count, the time limit and the "the answer says it is done" rule, so a stop condition
|
||||
* is enforced here, in the app, and never left to the model: once a loop has ended nothing is sent again.
|
||||
*
|
||||
* Everything outside (sending the message, reading the answer, adding a line to the chat, the clock) is passed in, so the same code
|
||||
* runs in the app (store.ts) and in the tests with a scripted model and a fake clock.
|
||||
*/
|
||||
export interface LoopHost {
|
||||
/** Send the message as an ordinary chat turn and resolve when the answer is complete. `answered` is false when nothing was sent (the chat was busy). */
|
||||
send(sessionId: string, message: { text: string; shown: string }): Promise<{ answered: boolean; text: string; failed: boolean }>;
|
||||
/** A line from the app itself in the chat (never sent to the model). */
|
||||
note(sessionId: string, text: string): void;
|
||||
/** False when the chat was deleted: the loop ends quietly. */
|
||||
exists(sessionId: string): boolean;
|
||||
/** True when this chat is open and nothing is being answered. */
|
||||
ready(sessionId: string): boolean;
|
||||
now(): number;
|
||||
setTimer(fn: () => void, ms: number): unknown;
|
||||
clearTimer(handle: unknown): void;
|
||||
}
|
||||
|
||||
export interface LoopStart extends LoopLimits { everyMs: number; prompt: string }
|
||||
|
||||
interface LoopState extends LoopStart {
|
||||
answers: number;
|
||||
failures: number;
|
||||
startedAt: number;
|
||||
timer: unknown;
|
||||
running: boolean;
|
||||
}
|
||||
|
||||
export class LoopScheduler {
|
||||
private readonly loops = new Map<string, LoopState>();
|
||||
/** How long to wait before looking again when the chat is busy or not open. */
|
||||
busyRetryMs = 15_000;
|
||||
|
||||
constructor(private readonly host: LoopHost) {}
|
||||
|
||||
isRunning(sessionId: string | null): boolean { return !!sessionId && this.loops.has(sessionId); }
|
||||
|
||||
/** What the person is told for /loop with nothing after it. */
|
||||
describe(sessionId: string): string | null {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return null;
|
||||
const limit = loopLimitNote(loop);
|
||||
return tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : '');
|
||||
}
|
||||
|
||||
stop(sessionId: string): boolean {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return false;
|
||||
if (loop.timer) this.host.clearTimer(loop.timer);
|
||||
this.loops.delete(sessionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Start a loop and send its first message now. Returns false (and says why in the chat) when the chat already has one. */
|
||||
async start(sessionId: string, command: LoopStart): Promise<boolean> {
|
||||
if (this.loops.has(sessionId)) { this.host.note(sessionId, tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return false; }
|
||||
const loop: LoopState = { ...command, answers: 0, failures: 0, startedAt: this.host.now(), timer: null, running: false };
|
||||
this.loops.set(sessionId, loop);
|
||||
const limit = loopLimitNote(loop);
|
||||
this.host.note(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [loop.prompt, loopEvery(loop.everyMs)]) + (limit ? ' ' + limit : ''));
|
||||
await this.run(sessionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Send once, judge the answer, then either end the loop with a plain note or wait for the next time. */
|
||||
private async run(sessionId: string): Promise<void> {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop || loop.running) return;
|
||||
loop.running = true;
|
||||
let why: LoopStop | null = null;
|
||||
try {
|
||||
const result = await this.host.send(sessionId, { text: withStopRule(loop.prompt, loop.stopWhen), shown: loop.prompt });
|
||||
// The person may have typed /loop stop while the answer was coming: nothing more happens then.
|
||||
if (this.loops.get(sessionId) !== loop) return;
|
||||
if (result.answered) {
|
||||
if (result.failed) loop.failures += 1; else { loop.failures = 0; loop.answers += 1; }
|
||||
why = judgeAnswer(loop, loop, result, this.host.now());
|
||||
}
|
||||
} catch {
|
||||
if (this.loops.get(sessionId) !== loop) return;
|
||||
loop.failures += 1;
|
||||
if (loop.failures >= LOOP_MAX_FAILURES) why = 'failures';
|
||||
} finally {
|
||||
loop.running = false;
|
||||
}
|
||||
if (why) { this.finish(sessionId, loop, why); return; }
|
||||
this.schedule(sessionId, loop.everyMs);
|
||||
}
|
||||
|
||||
private finish(sessionId: string, loop: LoopState, why: LoopStop) {
|
||||
this.stop(sessionId);
|
||||
this.host.note(sessionId, loopEndNote(why, loop.answers));
|
||||
}
|
||||
|
||||
private schedule(sessionId: string, ms: number) {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
loop.timer = this.host.setTimer(() => void this.tick(sessionId), ms);
|
||||
}
|
||||
|
||||
private async tick(sessionId: string): Promise<void> {
|
||||
const loop = this.loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
loop.timer = null;
|
||||
if (!this.host.exists(sessionId)) { this.stop(sessionId); return; }
|
||||
// The time is up, or the count is reached: never fire again, even if the last answer was not judged (a busy chat).
|
||||
if (loop.maxMs !== undefined && this.host.now() - loop.startedAt >= loop.maxMs) { this.finish(sessionId, loop, 'time'); return; }
|
||||
if (loop.maxRuns !== undefined && loop.answers >= loop.maxRuns) { this.finish(sessionId, loop, 'count'); return; }
|
||||
if (loop.answers >= LOOP_MAX_RUNS) { this.finish(sessionId, loop, 'cap'); return; }
|
||||
// Wait for a quiet moment: this chat is open and nothing is being answered.
|
||||
if (!this.host.ready(sessionId)) { this.schedule(sessionId, this.busyRetryMs); return; }
|
||||
await this.run(sessionId);
|
||||
}
|
||||
}
|
||||
+128
-6
@@ -3,20 +3,29 @@ import { tr } from './i18n';
|
||||
/**
|
||||
* /loop: send the same message again and again, every few minutes, while this chat is open.
|
||||
*
|
||||
* /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes)
|
||||
* /loop stop stop
|
||||
* /loop say whether a loop is running
|
||||
* /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes)
|
||||
* /loop 5m say hi, stop after 3 answers stops by itself after the 3rd answer (a count in words works too)
|
||||
* /loop 10m check the build for the next 2 hours stops by itself when the time is up
|
||||
* /loop 5m check the build, stop when it passes stops when the answer says it is done
|
||||
* /loop stop stop
|
||||
* /loop say whether a loop is running
|
||||
*
|
||||
* The loop lives in the app window: it waits for the chat to be idle, and it stops when the window closes.
|
||||
* For work that must go on with the app closed, a task on the Tasks screen is the right tool.
|
||||
*
|
||||
* A stop condition is the scheduler's job, not the model's: the count and the time are read when the loop is created and are
|
||||
* enforced by the scheduler (loop-runner.ts), and the scheduler also ends the loop when an answer says the work is done or stopped.
|
||||
* The model is never left to keep answering "stopped" every minute.
|
||||
*/
|
||||
|
||||
export const LOOP_MIN_MS = 60_000;
|
||||
export const LOOP_MAX_MS = 24 * 3_600_000;
|
||||
export const LOOP_MAX_RUNS = 100;
|
||||
/** This many answers in a row that failed (no model, an error) end the loop, so it does not retry a broken thing all day. */
|
||||
export const LOOP_MAX_FAILURES = 3;
|
||||
|
||||
export type LoopCommand =
|
||||
| { kind: 'start'; everyMs: number; prompt: string }
|
||||
| { kind: 'start'; everyMs: number; prompt: string; maxRuns?: number; maxMs?: number; stopWhen?: string }
|
||||
| { kind: 'stop' }
|
||||
| { kind: 'status' }
|
||||
| { kind: 'help'; problem: string };
|
||||
@@ -24,7 +33,53 @@ export type LoopCommand =
|
||||
const UNITS: Record<string, number> = { s: 1000, sec: 1000, second: 1000, seconds: 1000, m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000, h: 3_600_000, hr: 3_600_000, hour: 3_600_000, hours: 3_600_000 };
|
||||
|
||||
/** The words shown when a /loop line is not understood. */
|
||||
export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Use /loop stop to stop.';
|
||||
export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add "stop after 3 answers" to end it by itself. Use /loop stop to stop.';
|
||||
|
||||
const NUMBER_WORDS: Record<string, number> = { a: 1, an: 1, one: 1, once: 1, two: 2, twice: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, fifteen: 15, twenty: 20, thirty: 30, fifty: 50 };
|
||||
const NUM = '(\\d{1,4}|[a-z]+)';
|
||||
const THINGS = '(?:answers?|repl(?:y|ies)|responses?|runs?|times?|messages?|rounds?|checks?|iterations?|turns?|updates?|reports?|passes|tries|attempts?|loops?)';
|
||||
const STOP_VERB = '(?:stop|end|quit|finish|halt|cancel|exit)';
|
||||
const number = (word: string): number | null => {
|
||||
const n = /^\d+$/.test(word) ? Number(word) : NUMBER_WORDS[word.toLowerCase()];
|
||||
return Number.isFinite(n) && n >= 1 ? n : null;
|
||||
};
|
||||
/** A clause with its comma or "and" in front and its full stop behind, so removing it leaves a clean sentence. */
|
||||
const clause = (body: string) => new RegExp(`(?:[,;.]\\s*|\\s+(?:and|then)\\s+|\\s+)?(?:please\\s+)?${body}(?=\\s*[,;.!]|\\s+(?:and|then)\\b|\\s*$)[,;.!]?`, 'i');
|
||||
|
||||
interface Limits { prompt: string; maxRuns?: number; maxMs?: number; stopWhen?: string }
|
||||
|
||||
/** The count, the time and the condition the person put in words, with those words taken out of the message the model gets. */
|
||||
export function readLimits(text: string): Limits {
|
||||
let prompt = text.trim();
|
||||
let maxRuns: number | undefined;
|
||||
let maxMs: number | undefined;
|
||||
let stopWhen: string | undefined;
|
||||
const take = (re: RegExp, use: (m: RegExpMatchArray) => boolean) => {
|
||||
const m = prompt.match(re);
|
||||
if (!m || !use(m)) return;
|
||||
prompt = (prompt.slice(0, m.index) + ' ' + prompt.slice((m.index ?? 0) + m[0].length)).replace(/\s+/g, ' ').replace(/\s+([,.;!])/g, '$1').replace(/^[\s,;.]+|[\s,;]+$/g, '').trim();
|
||||
};
|
||||
const setRuns = (n: number | null) => { if (n === null) return false; maxRuns = Math.min(n, LOOP_MAX_RUNS); return true; };
|
||||
// "stop after 3 answers", "stop the loop after three replies", "stop after the 3rd run", "end after 5 more checks"
|
||||
take(clause(`${STOP_VERB}(?:\\s+(?:the\\s+)?(?:loop|looping|it|this|all))?\\s+after\\s+(?:the\\s+)?${NUM}(?:st|nd|rd|th)?\\s+(?:more\\s+)?${THINGS}`), m => setRuns(number(m[1])));
|
||||
// "only 3 times", "just 3 answers", "3 times only", "3 times", "for 3 answers", "up to 3 runs", "at most 3 times", "max 3 runs", "run it 3 times"
|
||||
if (maxRuns === undefined) take(clause(`(?:only|just|exactly|up\\s+to|at\\s+most|no\\s+more\\s+than|max(?:imum)?(?:\\s+of)?|for|do\\s+this|do\\s+it|repeat(?:\\s+this|\\s+it)?|run(?:\\s+this|\\s+it)?|send(?:\\s+this|\\s+it)?|ask(?:\\s+me)?)\\s+${NUM}\\s+${THINGS}(?:\\s+only)?`), m => setRuns(number(m[1])));
|
||||
if (maxRuns === undefined) take(clause(`${NUM}\\s+${THINGS}\\s+(?:only|in\\s+total|total|at\\s+most)`), m => setRuns(number(m[1])));
|
||||
if (maxRuns === undefined) take(clause(`${NUM}\\s+times`), m => setRuns(number(m[1])));
|
||||
if (maxRuns === undefined) take(clause(`(?:${STOP_VERB}\\s+)?(?:for\\s+)?(?:the\\s+)?(?:first|next)\\s+${NUM}\\s+${THINGS}`), m => setRuns(number(m[1])));
|
||||
// "for the next 2 hours", "for 30 minutes", "stop after 2 hours", "for an hour"
|
||||
const span = (m: RegExpMatchArray) => {
|
||||
const n = number(m[1]); const unit = UNITS[m[2].toLowerCase()];
|
||||
if (n === null || !unit || unit < 60_000) return false;
|
||||
maxMs = Math.min(n * unit, LOOP_MAX_MS);
|
||||
return true;
|
||||
};
|
||||
take(clause(`${STOP_VERB}(?:\\s+(?:the\\s+)?(?:loop|it|this))?\\s+after\\s+(?:about\\s+)?${NUM}\\s*(minutes?|mins?|hours?|hrs?|[mh])\\b`), span);
|
||||
if (maxMs === undefined) take(clause(`(?:for|over)\\s+(?:the\\s+)?(?:next\\s+)?(?:about\\s+)?${NUM}\\s*(minutes?|mins?|hours?|hrs?)\\b`), span);
|
||||
// "stop when the build passes", "stop once it is green", "until the file exists": the model judges it; the scheduler stops on its word
|
||||
take(clause(`(?:${STOP_VERB}\\s+(?:the\\s+loop\\s+)?(?:when|once|as\\s+soon\\s+as|if|the\\s+moment)|until)\\s+([^.;!]{3,160})`), m => { stopWhen = m[1].trim(); return true; });
|
||||
return { prompt, ...(maxRuns !== undefined ? { maxRuns } : {}), ...(maxMs !== undefined ? { maxMs } : {}), ...(stopWhen ? { stopWhen } : {}) };
|
||||
}
|
||||
|
||||
/** null means the text is an ordinary message. */
|
||||
export function parseLoop(text: string): LoopCommand | null {
|
||||
@@ -39,7 +94,9 @@ export function parseLoop(text: string): LoopCommand | null {
|
||||
const everyMs = Math.round(Number(timed[1]) * unit);
|
||||
if (everyMs < LOOP_MIN_MS) return { kind: 'help', problem: 'The shortest time between runs is 1 minute, so the model has time to finish each one.' };
|
||||
if (everyMs > LOOP_MAX_MS) return { kind: 'help', problem: 'The longest time between runs is 24 hours. For longer waits, use a task on the Tasks screen.' };
|
||||
return { kind: 'start', everyMs, prompt: timed[3].trim() };
|
||||
const limits = readLimits(timed[3]);
|
||||
if (!limits.prompt) return { kind: 'help', problem: 'Say what to do each time, not only when to stop.' };
|
||||
return { kind: 'start', everyMs, ...limits };
|
||||
}
|
||||
|
||||
/** "every 10 minutes", "every hour". */
|
||||
@@ -48,3 +105,68 @@ export function loopEvery(ms: number): string {
|
||||
const m = Math.round(ms / 60_000);
|
||||
return m === 1 ? tr('every minute') : tr('every {0} minutes', [m]);
|
||||
}
|
||||
|
||||
/** The line added to a message that carries a stop condition in words, so the model can say it is met (it is not shown in the chat). */
|
||||
export const LOOP_DONE_WORD = 'DONE';
|
||||
export function withStopRule(prompt: string, stopWhen?: string): string {
|
||||
return stopWhen ? `${prompt}\n\n(This repeats on a timer. If this is finished or "${stopWhen}" is true, begin your reply with the word ${LOOP_DONE_WORD} and say so in one sentence. Otherwise just answer.)` : prompt;
|
||||
}
|
||||
|
||||
const plain = (text: string) => text.replace(/[*_`#>~]/g, '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
/**
|
||||
* Does this reply say the work is finished or stopped? The scheduler ends the loop on it.
|
||||
*
|
||||
* Always: the model's own marker ("DONE ...", "LOOP DONE", "LOOP STOPPED") or a reply that is only "stopped" / "done" / "finished".
|
||||
* When the person stated a stop condition (a count, a time or a condition in words), also the short ways a model closes the job:
|
||||
* "Stopped.", "The loop is stopped.", "I have stopped as requested.", "Done, the build passes."
|
||||
*/
|
||||
export function replySaysDone(reply: string, stated: boolean): boolean {
|
||||
const text = plain(reply);
|
||||
if (!text) return false;
|
||||
if (/\bLOOP[ _-]?(?:DONE|STOPPED|STOP|COMPLETE|FINISHED|ENDED)\b/i.test(text)) return true;
|
||||
if (new RegExp(`^${LOOP_DONE_WORD}\\b`).test(text)) return true;
|
||||
const bare = text.replace(/[.!\s]+$/g, '').toLowerCase();
|
||||
if (/^(?:ok(?:ay)?[,. ]+)?(?:stopped|done|finished|complete|completed|all done|ended|stopping)$/.test(bare)) return true;
|
||||
if (!stated || text.length > 280) return false;
|
||||
return /^(?:ok(?:ay)?[,. ]+|sure[,. ]+|yes[,. ]+)?(?:the\s+)?(?:loop\s+(?:is\s+|has\s+)?(?:now\s+)?)?(?:stopped|done|finished|complete(?:d)?|ended|stopping|all done)\b/i.test(text)
|
||||
|| /\b(?:loop|repeat\w*|schedule\w*)\s+(?:is\s+|has\s+been\s+|was\s+)?(?:now\s+)?(?:stopped|finished|complete(?:d)?|ended|over|done)\b/i.test(text)
|
||||
|| /\bi(?:'ve|\s+have|'m|\s+am)?\s+(?:now\s+)?(?:stopped|stopping|done|finished)\b/i.test(text)
|
||||
|| /\b(?:stop|end)\s+condition\s+(?:is\s+|has\s+been\s+)?met\b/i.test(text)
|
||||
|| /\bnothing\s+(?:more|else|left)\s+to\s+(?:do|check|report)\b/i.test(text);
|
||||
}
|
||||
|
||||
export interface LoopLimits { maxRuns?: number; maxMs?: number; stopWhen?: string }
|
||||
export interface LoopProgress { answers: number; failures: number; startedAt: number }
|
||||
export type LoopStop = 'count' | 'said-done' | 'time' | 'failures' | 'cap';
|
||||
|
||||
/** After an answer: should the loop end, and why? `reply` is the model's text of that run; `failed` is an answer that did not work. */
|
||||
export function judgeAnswer(limits: LoopLimits, progress: LoopProgress, reply: { text: string; failed: boolean }, now: number): LoopStop | null {
|
||||
if (reply.failed) return progress.failures >= LOOP_MAX_FAILURES ? 'failures' : null;
|
||||
const stated = limits.maxRuns !== undefined || limits.maxMs !== undefined || !!limits.stopWhen;
|
||||
if (replySaysDone(reply.text, stated)) return 'said-done';
|
||||
if (limits.maxRuns !== undefined && progress.answers >= limits.maxRuns) return 'count';
|
||||
if (limits.maxMs !== undefined && now - progress.startedAt >= limits.maxMs) return 'time';
|
||||
if (progress.answers >= LOOP_MAX_RUNS) return 'cap';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Plain words for the person when a loop ends by itself. */
|
||||
export function loopEndNote(why: LoopStop, answers: number): string {
|
||||
switch (why) {
|
||||
case 'count': return tr('The loop is done: it ran {0} times, as you asked. Type /loop to start another.', [answers]);
|
||||
case 'said-done': return tr('The loop stopped because the last answer said the work is done. Type /loop to start another.');
|
||||
case 'time': return tr('The loop stopped because the time you set is up. Type /loop to start another.');
|
||||
case 'failures': return tr('The loop stopped because {0} runs in a row did not work. Check the model, then type /loop to start it again.', [LOOP_MAX_FAILURES]);
|
||||
default: return tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS]);
|
||||
}
|
||||
}
|
||||
|
||||
/** The part of the "Loop started" note that says how it ends by itself ('' when it only ends when the person stops it). */
|
||||
export function loopLimitNote(limits: LoopLimits): string {
|
||||
const parts: string[] = [];
|
||||
if (limits.maxRuns !== undefined) parts.push(limits.maxRuns === 1 ? tr('It stops by itself after the first answer.') : tr('It stops by itself after {0} answers.', [limits.maxRuns]));
|
||||
if (limits.maxMs !== undefined) parts.push(tr('It stops by itself after {0} minutes.', [Math.max(1, Math.round(limits.maxMs / 60_000))]));
|
||||
if (limits.stopWhen) parts.push(tr('It stops by itself when an answer says the work is done.'));
|
||||
return parts.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Files dropped on the app window on Linux and macOS. The page gets the drag events there but not the files (WebKit hides them), so the app
|
||||
* shell reads the drop, hands the paths to the host, and tells the page with these two events (apps/desktop/src-tauri/src/main.rs):
|
||||
* strata:native-drag detail 'enter' | 'leave' the drop box shows or goes away
|
||||
* strata:native-drop detail [{ id, name, type }] the host holds each file once under its id
|
||||
*/
|
||||
export const NATIVE_DRAG_EVENT = 'strata:native-drag';
|
||||
export const NATIVE_DROP_EVENT = 'strata:native-drop';
|
||||
export interface DroppedRef { id: string; name: string; type: string }
|
||||
|
||||
/** The files the shell announced; anything that is not a well-formed entry is left out. */
|
||||
export function readDroppedRefs(detail: unknown): DroppedRef[] {
|
||||
if (!Array.isArray(detail)) return [];
|
||||
return detail.flatMap(x => {
|
||||
const r = x as Record<string, unknown>;
|
||||
return typeof r?.id === 'string' && /^[0-9a-f-]{36}$/.test(r.id) && typeof r.name === 'string' && r.name
|
||||
? [{ id: r.id, name: r.name, type: typeof r.type === 'string' ? r.type : 'application/octet-stream' }] : [];
|
||||
}).slice(0, 10);
|
||||
}
|
||||
|
||||
/** Fetch each announced file from the host and make it a File, the way a browser drop would have delivered it. A file that cannot be fetched is skipped. */
|
||||
export async function fetchDropped(refs: DroppedRef[], fetcher: (url: string) => Promise<{ ok: boolean; blob(): Promise<Blob> }> = url => fetch(url)): Promise<File[]> {
|
||||
const files: File[] = [];
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
const response = await fetcher(`/api/app/drop/${ref.id}`);
|
||||
if (response.ok) files.push(new File([await response.blob()], ref.name, { type: ref.type }));
|
||||
} catch { /* skipped */ }
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/** True for a drag that carries files, as far as the page can tell (WebKit lists them as text/uri-list, others as Files). */
|
||||
export const dragHasFiles = (types: ArrayLike<string> | null | undefined) => Array.from(types ?? []).some(t => t === 'Files' || t === 'text/uri-list');
|
||||
@@ -10,7 +10,7 @@ import { api, ApiError } from './client';
|
||||
export type PlanState = 'proposed' | 'approved' | 'rejected' | 'running' | 'paused' | 'done' | 'stopped';
|
||||
export type StepState = 'pending' | 'running' | 'done' | 'failed' | 'skipped';
|
||||
export interface PlanStep { id: string; text: string; detail?: string; summary?: string; state: StepState }
|
||||
export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[] }
|
||||
export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[]; /** A plain sentence (an interface string) when the app stopped the planning turn early. */ caution?: string }
|
||||
export interface QueuedMessage { id: string; text: string; deliverAt: 'step' | 'end' }
|
||||
|
||||
const PLAN_STATES = ['proposed', 'approved', 'rejected', 'running', 'paused', 'done', 'stopped'];
|
||||
|
||||
+26
-40
@@ -1,7 +1,8 @@
|
||||
import { plainFailure, plainFailureText } from './plain-errors';
|
||||
import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase';
|
||||
import { updateAgent } from './agents';
|
||||
import { LOOP_MAX_RUNS, LOOP_USAGE, loopEvery, parseLoop, type LoopCommand } from './loop';
|
||||
import { LOOP_USAGE, parseLoop, type LoopCommand } from './loop';
|
||||
import { LoopScheduler } from './loop-runner';
|
||||
import { applyStatusFrame, clearStatus } from './live-status';
|
||||
import { applyGoalFrame } from './goal';
|
||||
import { tidyAnswer } from './answer-text';
|
||||
@@ -1448,9 +1449,8 @@ export function exportConversation() {
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- /loop
|
||||
The same message, again and again, while the chat is open. See lib/loop.ts. */
|
||||
interface LoopState { everyMs: number; prompt: string; runs: number; timer: ReturnType<typeof setTimeout> | null }
|
||||
const loops = new Map<string, LoopState>();
|
||||
The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is
|
||||
lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */
|
||||
|
||||
/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */
|
||||
function addNote(sessionId: string, content: string) {
|
||||
@@ -1458,50 +1458,34 @@ function addNote(sessionId: string, content: string) {
|
||||
patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] }));
|
||||
}
|
||||
|
||||
export function loopIsRunning(sessionId: string | null): boolean { return !!sessionId && loops.has(sessionId); }
|
||||
const lastAnswer = (sessionId: string) => [...(state.sessions.find(s => s.id === sessionId)?.messages ?? [])].reverse().find(m => m.role === 'assistant' && !m.local);
|
||||
|
||||
function stopLoop(sessionId: string): boolean {
|
||||
const loop = loops.get(sessionId);
|
||||
if (!loop) return false;
|
||||
if (loop.timer) clearTimeout(loop.timer);
|
||||
loops.delete(sessionId);
|
||||
return true;
|
||||
}
|
||||
const loopScheduler = new LoopScheduler({
|
||||
async send(sessionId, { text, shown }) {
|
||||
const before = lastAnswer(sessionId)?.id;
|
||||
await sendMessage(text, { fromLoop: true, shown, title: shown.length > 48 ? shown.slice(0, 47).trimEnd() + '…' : shown });
|
||||
const answer = lastAnswer(sessionId);
|
||||
if (!answer || answer.id === before || answer.streaming) return { answered: false, text: '', failed: false };
|
||||
return { answered: true, text: answer.content ?? '', failed: !!answer.error };
|
||||
},
|
||||
note: addNote,
|
||||
exists: sessionId => state.sessions.some(s => s.id === sessionId),
|
||||
ready: sessionId => state.activeSession === sessionId && !state.streaming,
|
||||
now: () => Date.now(),
|
||||
setTimer: (fn, ms) => setTimeout(fn, ms),
|
||||
clearTimer: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
||||
});
|
||||
|
||||
function scheduleLoop(sessionId: string) {
|
||||
const loop = loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
loop.timer = setTimeout(() => void tickLoop(sessionId), loop.everyMs);
|
||||
}
|
||||
|
||||
async function tickLoop(sessionId: string) {
|
||||
const loop = loops.get(sessionId);
|
||||
if (!loop) return;
|
||||
if (!state.sessions.some(s => s.id === sessionId)) { stopLoop(sessionId); return; }
|
||||
// Wait for a quiet moment: this chat is open and nothing is being answered.
|
||||
if (state.activeSession !== sessionId || state.streaming) { loop.timer = setTimeout(() => void tickLoop(sessionId), 15_000); return; }
|
||||
loop.runs += 1;
|
||||
if (loop.runs > LOOP_MAX_RUNS) { stopLoop(sessionId); addNote(sessionId, tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS])); return; }
|
||||
await sendMessage(loop.prompt, { fromLoop: true });
|
||||
scheduleLoop(sessionId);
|
||||
}
|
||||
export function loopIsRunning(sessionId: string | null): boolean { return loopScheduler.isRunning(sessionId); }
|
||||
|
||||
async function runLoopCommand(command: LoopCommand) {
|
||||
const sessionId = state.activeSession ?? newSession().id;
|
||||
const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); };
|
||||
if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; }
|
||||
if (command.kind === 'status') {
|
||||
const loop = loops.get(sessionId);
|
||||
say(loop ? tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) : tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE));
|
||||
return;
|
||||
}
|
||||
if (command.kind === 'stop') { say(stopLoop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }
|
||||
if (loops.has(sessionId)) { say(tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return; }
|
||||
loops.set(sessionId, { everyMs: command.everyMs, prompt: command.prompt, runs: 1, timer: null });
|
||||
addNote(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [command.prompt, loopEvery(command.everyMs)]));
|
||||
if (command.kind === 'status') { say(loopScheduler.describe(sessionId) ?? tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); return; }
|
||||
if (command.kind === 'stop') { say(loopScheduler.stop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; }
|
||||
go('chat', sessionId);
|
||||
await sendMessage(command.prompt, { fromLoop: true });
|
||||
scheduleLoop(sessionId);
|
||||
await loopScheduler.start(sessionId, command);
|
||||
}
|
||||
|
||||
/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */
|
||||
@@ -1623,6 +1607,8 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g
|
||||
workspaceId: state.activeWorkspace,
|
||||
},
|
||||
(frame) => {
|
||||
// A line from the app itself carries `key` (the English sentence): shown in the person's language.
|
||||
if (frame.type === 'delta' && typeof frame.key === 'string') frame = { ...frame, text: tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) };
|
||||
const type = frame.type as string;
|
||||
if (type === 'start' && frame.agent === true) { const turn = liveTurns.get(sessionId); if (turn) turn.agent = true; }
|
||||
if (type === 'queued') {
|
||||
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Die Ergebnisse kommen von DuckDuckGo, oder von Bing, wenn DuckDuckGo ausgelastet ist. Sie brauchen kein Konto und keinen Schlüssel.",
|
||||
"s7321": "Die Websuche ist gerade eingeschränkt, deshalb habe ich die Suche beendet und mit dem weitergemacht, was ich habe. Versuchen Sie es in einer Minute erneut oder fügen Sie unter Einstellungen → Tools → Websuche einen Suchschlüssel hinzu.",
|
||||
"s7322": "Ich habe viel gesucht und aufgehört, damit dieser Chat nicht überläuft. Das ist mein Stand bisher. Sagen Sie mir, was ich als Nächstes nachschlagen soll.",
|
||||
"s7323": "Ich habe den Plan immer wieder umgeschrieben und höre hier mit der letzten Fassung auf. Sagen Sie mir, was ich ändern soll, oder genehmigen Sie ihn.",
|
||||
"s7324": "In diesem Chat ist mir der Platz ausgegangen, deshalb habe ich angehalten. Strata fasst die älteren Nachrichten zusammen, um Platz zu schaffen. Schreiben Sie „weiter“, um fortzufahren, oder starten Sie einen neuen Chat.",
|
||||
"s7325": "Ich habe angehalten, ohne eine Antwort zu schreiben. Senden Sie Ihre Nachricht erneut oder schreiben Sie „weiter“.",
|
||||
"s7301": "Tippen Sie /loop, wie oft und dann, was zu tun ist. Zum Beispiel: /loop 10m prüfe, ob der Build besteht. Mit „stop after 3 answers“ endet es von selbst. Mit /loop stop halten Sie es an.",
|
||||
"s7302": "Sagen Sie, was jedes Mal zu tun ist, nicht nur, wann es endet.",
|
||||
"s7303": "Die Schleife ist fertig: Sie lief {0}-mal, wie gewünscht. Mit /loop starten Sie eine neue.",
|
||||
"s7304": "Die Schleife wurde beendet, weil die letzte Antwort sagte, dass die Arbeit erledigt ist. Mit /loop starten Sie eine neue.",
|
||||
"s7305": "Die Schleife wurde beendet, weil die von Ihnen gesetzte Zeit abgelaufen ist. Mit /loop starten Sie eine neue.",
|
||||
"s7306": "Die Schleife wurde beendet, weil {0} Durchläufe hintereinander nicht funktioniert haben. Prüfen Sie das Modell und starten Sie sie mit /loop neu.",
|
||||
"s7307": "Es endet von selbst nach der ersten Antwort.",
|
||||
"s7308": "Es endet von selbst nach {0} Antworten.",
|
||||
"s7309": "Es endet von selbst nach {0} Minuten.",
|
||||
"s7310": "Es endet von selbst, wenn eine Antwort sagt, dass die Arbeit erledigt ist.",
|
||||
"s7311": "Anthropic-Apps hängen /v1/messages selbst an, deshalb steht am Ende dieser Adresse kein /v1. In Claude Code setzen Sie ANTHROPIC_BASE_URL darauf.",
|
||||
"s0002": "(optional)",
|
||||
"s0003": ", Kontextcache passt nicht in den Speicher",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "Der Screenshot wurde nicht gespeichert",
|
||||
"s3235": "Versuche es noch einmal oder mache stattdessen einen Screenshot dieses Fensters.",
|
||||
"s3236": "Das Ordnerfenster hat sich nicht geöffnet. Gib stattdessen den Ordnerpfad ein.",
|
||||
"s3237": "NVFP4 (Strata-Version)",
|
||||
"s3238": "NVFP4 (NVIDIA-Version)",
|
||||
"s3239": "NVFP4 (NVIDIA, für FP4 trainiert)",
|
||||
"s3240": "Strata-eigene Umwandlung. Die beste Qualität unter den NVFP4-Versionen.",
|
||||
"s3241": "NVIDIAs eigener NVFP4-Checkpoint, für Strata umgewandelt. Gleiche Größe und Geschwindigkeit.",
|
||||
"s3242": "NVIDIAs für FP4 trainierter Checkpoint. Bei kurzen Eingaben etwas schneller.",
|
||||
"s3243": "Alle anderen Versionen",
|
||||
"s3244": "Weitere Versionen",
|
||||
"s3245": "Modelldateien werden heruntergeladen · Teil {0} von {1}",
|
||||
"s3246": "Die Bildleser-Dateien werden heruntergeladen…",
|
||||
"s3247": "Die Engine für diesen PC wird heruntergeladen…",
|
||||
"s3248": "{0} wird vorbereitet",
|
||||
"s3249": "Teile des Downloads",
|
||||
"s3250": "Bildleser",
|
||||
"s3251": "Gemeinsame Dateien",
|
||||
"s3252": "Von mehr als einem Modell genutzt",
|
||||
"s3253": "Diese Dateien liegen in deinem eigenen Ordner und bleiben dort. Nur der Eintrag in Strata wird entfernt.",
|
||||
"s3254": "Das laufende Modell wird entladen.",
|
||||
"s3255": "Lokal",
|
||||
"s3256": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell wird trotzdem heruntergeladen, läuft aber möglicherweise erst, wenn die richtige Engine installiert ist (Einstellungen → Engine).",
|
||||
"s3257": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell ist heruntergeladen, läuft aber erst, wenn die richtige Engine installiert ist. Öffne Einstellungen → Engine."
|
||||
"s3237": "Die Datei wurde nicht hinzugefügt",
|
||||
"s3238": "Versuche, sie noch einmal abzulegen.",
|
||||
"s3260": "NVFP4 (Strata-Version)",
|
||||
"s3261": "NVFP4 (NVIDIA-Version)",
|
||||
"s3262": "NVFP4 (NVIDIA, für FP4 trainiert)",
|
||||
"s3263": "Strata-eigene Umwandlung. Die beste Qualität unter den NVFP4-Versionen.",
|
||||
"s3264": "NVIDIAs eigener NVFP4-Checkpoint, für Strata umgewandelt. Gleiche Größe und Geschwindigkeit.",
|
||||
"s3265": "NVIDIAs für FP4 trainierter Checkpoint. Bei kurzen Eingaben etwas schneller.",
|
||||
"s3266": "Alle anderen Versionen",
|
||||
"s3267": "Weitere Versionen",
|
||||
"s3268": "Modelldateien werden heruntergeladen · Teil {0} von {1}",
|
||||
"s3269": "Die Bildleser-Dateien werden heruntergeladen…",
|
||||
"s3270": "Die Engine für diesen PC wird heruntergeladen…",
|
||||
"s3271": "{0} wird vorbereitet",
|
||||
"s3272": "Teile des Downloads",
|
||||
"s3273": "Bildleser",
|
||||
"s3274": "Gemeinsame Dateien",
|
||||
"s3275": "Von mehr als einem Modell genutzt",
|
||||
"s3276": "Diese Dateien liegen in deinem eigenen Ordner und bleiben dort. Nur der Eintrag in Strata wird entfernt.",
|
||||
"s3277": "Das laufende Modell wird entladen.",
|
||||
"s3278": "Lokal",
|
||||
"s3279": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell wird trotzdem heruntergeladen, läuft aber möglicherweise erst, wenn die richtige Engine installiert ist (Einstellungen → Engine).",
|
||||
"s3280": "Strata hat für diesen Computer keine passende Engine erkannt. Das Modell ist heruntergeladen, läuft aber erst, wenn die richtige Engine installiert ist. Öffne Einstellungen → Engine."
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Results come from DuckDuckGo, or from Bing when DuckDuckGo is busy. You do not need an account or a key.",
|
||||
"s7321": "Web search is limited right now, so I stopped searching and went on with what I have. Try again in a minute, or add a search key in Settings → Tools → Web search.",
|
||||
"s7322": "I searched a lot and stopped so this chat does not fill up. This is what I have so far. Tell me what to look into next.",
|
||||
"s7323": "I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.",
|
||||
"s7324": "I ran out of room in this chat, so I stopped. Strata is summarising the older messages to make space. Say “continue” to go on, or start a new chat.",
|
||||
"s7325": "I stopped without writing an answer. Send your message again, or say “continue”.",
|
||||
"s7301": "Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add \"stop after 3 answers\" to end it by itself. Use /loop stop to stop.",
|
||||
"s7302": "Say what to do each time, not only when to stop.",
|
||||
"s7303": "The loop is done: it ran {0} times, as you asked. Type /loop to start another.",
|
||||
"s7304": "The loop stopped because the last answer said the work is done. Type /loop to start another.",
|
||||
"s7305": "The loop stopped because the time you set is up. Type /loop to start another.",
|
||||
"s7306": "The loop stopped because {0} runs in a row did not work. Check the model, then type /loop to start it again.",
|
||||
"s7307": "It stops by itself after the first answer.",
|
||||
"s7308": "It stops by itself after {0} answers.",
|
||||
"s7309": "It stops by itself after {0} minutes.",
|
||||
"s7310": "It stops by itself when an answer says the work is done.",
|
||||
"s7311": "Anthropic apps add /v1/messages themselves, so this address has no /v1 at the end. In Claude Code, set ANTHROPIC_BASE_URL to it.",
|
||||
"s0002": "(optional)",
|
||||
"s0003": ", context cache does not fit",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "The screenshot was not saved",
|
||||
"s3235": "Try again, or take a screenshot of this window instead.",
|
||||
"s3236": "The folder window did not open. Type the folder path instead.",
|
||||
"s3237": "NVFP4 (Strata’s version)",
|
||||
"s3238": "NVFP4 (NVIDIA’s version)",
|
||||
"s3239": "NVFP4 (NVIDIA, trained for FP4)",
|
||||
"s3240": "Strata’s own conversion. The best quality of the NVFP4 versions.",
|
||||
"s3241": "NVIDIA’s own NVFP4 checkpoint, converted for Strata. Same size and speed.",
|
||||
"s3242": "NVIDIA’s FP4 checkpoint, trained for FP4. Slightly faster on short prompts.",
|
||||
"s3243": "All other versions",
|
||||
"s3244": "More versions",
|
||||
"s3245": "Downloading model files · part {0} of {1}",
|
||||
"s3246": "Downloading the picture reader…",
|
||||
"s3247": "Downloading the engine for this PC…",
|
||||
"s3248": "Preparing {0}",
|
||||
"s3249": "Download parts",
|
||||
"s3250": "Picture reader",
|
||||
"s3251": "Shared files",
|
||||
"s3252": "Used by more than one model",
|
||||
"s3253": "These files are in your own folder, so they stay there. Only the entry in Strata is removed.",
|
||||
"s3254": "The running model will be unloaded.",
|
||||
"s3255": "Local",
|
||||
"s3256": "Strata didn’t recognise an engine for this computer. The model will download, but it may not run until the right engine is installed (Settings → Engine).",
|
||||
"s3257": "Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine."
|
||||
"s3237": "The file was not added",
|
||||
"s3238": "Try dropping it again.",
|
||||
"s3260": "NVFP4 (Strata’s version)",
|
||||
"s3261": "NVFP4 (NVIDIA’s version)",
|
||||
"s3262": "NVFP4 (NVIDIA, trained for FP4)",
|
||||
"s3263": "Strata’s own conversion. The best quality of the NVFP4 versions.",
|
||||
"s3264": "NVIDIA’s own NVFP4 checkpoint, converted for Strata. Same size and speed.",
|
||||
"s3265": "NVIDIA’s FP4 checkpoint, trained for FP4. Slightly faster on short prompts.",
|
||||
"s3266": "All other versions",
|
||||
"s3267": "More versions",
|
||||
"s3268": "Downloading model files · part {0} of {1}",
|
||||
"s3269": "Downloading the picture reader…",
|
||||
"s3270": "Downloading the engine for this PC…",
|
||||
"s3271": "Preparing {0}",
|
||||
"s3272": "Download parts",
|
||||
"s3273": "Picture reader",
|
||||
"s3274": "Shared files",
|
||||
"s3275": "Used by more than one model",
|
||||
"s3276": "These files are in your own folder, so they stay there. Only the entry in Strata is removed.",
|
||||
"s3277": "The running model will be unloaded.",
|
||||
"s3278": "Local",
|
||||
"s3279": "Strata didn’t recognise an engine for this computer. The model will download, but it may not run until the right engine is installed (Settings → Engine).",
|
||||
"s3280": "Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine."
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Los resultados vienen de DuckDuckGo, o de Bing cuando DuckDuckGo está ocupado. No necesitas cuenta ni clave.",
|
||||
"s7321": "La búsqueda web está limitada ahora mismo, así que dejé de buscar y seguí con lo que tengo. Inténtalo de nuevo en un minuto o añade una clave de búsqueda en Ajustes → Herramientas → Búsqueda web.",
|
||||
"s7322": "Busqué mucho y me detuve para que este chat no se llene. Esto es lo que tengo hasta ahora. Dime qué quieres que investigue después.",
|
||||
"s7323": "Seguí reescribiendo el plan, así que me detuve aquí con la última versión. Dime qué cambiar o apruébalo.",
|
||||
"s7324": "Me quedé sin espacio en este chat, así que me detuve. Strata está resumiendo los mensajes antiguos para liberar espacio. Escribe “continúa” para seguir o empieza un chat nuevo.",
|
||||
"s7325": "Me detuve sin escribir una respuesta. Envía tu mensaje de nuevo o escribe “continúa”.",
|
||||
"s7301": "Escribe /loop, cada cuánto y luego qué hacer. Por ejemplo: /loop 10m comprueba si la compilación pasa. Añade \"stop after 3 answers\" para que termine solo. Usa /loop stop para pararlo.",
|
||||
"s7302": "Indica qué hacer cada vez, no solo cuándo parar.",
|
||||
"s7303": "El bucle terminó: se ejecutó {0} veces, como pediste. Escribe /loop para iniciar otro.",
|
||||
"s7304": "El bucle se detuvo porque la última respuesta dijo que el trabajo está terminado. Escribe /loop para iniciar otro.",
|
||||
"s7305": "El bucle se detuvo porque se acabó el tiempo que indicaste. Escribe /loop para iniciar otro.",
|
||||
"s7306": "El bucle se detuvo porque {0} ejecuciones seguidas no funcionaron. Revisa el modelo y escribe /loop para iniciarlo de nuevo.",
|
||||
"s7307": "Se detiene solo después de la primera respuesta.",
|
||||
"s7308": "Se detiene solo después de {0} respuestas.",
|
||||
"s7309": "Se detiene solo después de {0} minutos.",
|
||||
"s7310": "Se detiene solo cuando una respuesta dice que el trabajo está terminado.",
|
||||
"s7311": "Las apps de Anthropic añaden /v1/messages por sí mismas, así que esta dirección no termina en /v1. En Claude Code, pon esta dirección en ANTHROPIC_BASE_URL.",
|
||||
"s0002": "(opcional)",
|
||||
"s0003": ", la caché de contexto no cabe",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "No se guardó la captura",
|
||||
"s3235": "Inténtalo de nuevo o haz una captura de esta ventana.",
|
||||
"s3236": "La ventana de carpetas no se abrió. Escribe la ruta de la carpeta.",
|
||||
"s3237": "NVFP4 (versión de Strata)",
|
||||
"s3238": "NVFP4 (versión de NVIDIA)",
|
||||
"s3239": "NVFP4 (NVIDIA, entrenada para FP4)",
|
||||
"s3240": "Conversión propia de Strata. La mejor calidad de las versiones NVFP4.",
|
||||
"s3241": "El punto de control NVFP4 propio de NVIDIA, convertido para Strata. Mismo tamaño y velocidad.",
|
||||
"s3242": "El punto de control de NVIDIA entrenado para FP4. Algo más rápido con mensajes cortos.",
|
||||
"s3243": "Todas las demás versiones",
|
||||
"s3244": "Más versiones",
|
||||
"s3245": "Descargando los archivos del modelo · parte {0} de {1}",
|
||||
"s3246": "Descargando el lector de imágenes…",
|
||||
"s3247": "Descargando el motor para este PC…",
|
||||
"s3248": "Preparando {0}",
|
||||
"s3249": "Partes de la descarga",
|
||||
"s3250": "Lector de imágenes",
|
||||
"s3251": "Archivos compartidos",
|
||||
"s3252": "Los usa más de un modelo",
|
||||
"s3253": "Estos archivos están en tu propia carpeta y se quedan allí. Solo se quita la entrada en Strata.",
|
||||
"s3254": "El modelo en ejecución se descargará de la memoria.",
|
||||
"s3255": "Local",
|
||||
"s3256": "Strata no reconoció un motor para este equipo. El modelo se descargará, pero puede que no funcione hasta que se instale el motor adecuado (Ajustes → Motor).",
|
||||
"s3257": "Strata no reconoció un motor para este equipo. El modelo está descargado, pero no podrá funcionar hasta que se instale el motor adecuado. Abre Ajustes → Motor."
|
||||
"s3237": "No se añadió el archivo",
|
||||
"s3238": "Inténtalo de nuevo soltándolo otra vez.",
|
||||
"s3260": "NVFP4 (versión de Strata)",
|
||||
"s3261": "NVFP4 (versión de NVIDIA)",
|
||||
"s3262": "NVFP4 (NVIDIA, entrenada para FP4)",
|
||||
"s3263": "Conversión propia de Strata. La mejor calidad de las versiones NVFP4.",
|
||||
"s3264": "El punto de control NVFP4 propio de NVIDIA, convertido para Strata. Mismo tamaño y velocidad.",
|
||||
"s3265": "El punto de control de NVIDIA entrenado para FP4. Algo más rápido con mensajes cortos.",
|
||||
"s3266": "Todas las demás versiones",
|
||||
"s3267": "Más versiones",
|
||||
"s3268": "Descargando los archivos del modelo · parte {0} de {1}",
|
||||
"s3269": "Descargando el lector de imágenes…",
|
||||
"s3270": "Descargando el motor para este PC…",
|
||||
"s3271": "Preparando {0}",
|
||||
"s3272": "Partes de la descarga",
|
||||
"s3273": "Lector de imágenes",
|
||||
"s3274": "Archivos compartidos",
|
||||
"s3275": "Los usa más de un modelo",
|
||||
"s3276": "Estos archivos están en tu propia carpeta y se quedan allí. Solo se quita la entrada en Strata.",
|
||||
"s3277": "El modelo en ejecución se descargará de la memoria.",
|
||||
"s3278": "Local",
|
||||
"s3279": "Strata no reconoció un motor para este equipo. El modelo se descargará, pero puede que no funcione hasta que se instale el motor adecuado (Ajustes → Motor).",
|
||||
"s3280": "Strata no reconoció un motor para este equipo. El modelo está descargado, pero no podrá funcionar hasta que se instale el motor adecuado. Abre Ajustes → Motor."
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "結果は DuckDuckGo から取得し、DuckDuckGo が混み合っているときは Bing から取得します。アカウントもキーも不要です。",
|
||||
"s7321": "ウェブ検索が現在制限されているため、検索をやめて手元の情報で進めました。1分ほど待ってからもう一度試すか、「設定 → ツール → ウェブ検索」で検索キーを追加してください。",
|
||||
"s7322": "検索を重ねたため、このチャットがいっぱいにならないよう止めました。ここまでの内容は以上です。次に調べることを教えてください。",
|
||||
"s7323": "計画を何度も書き直していたため、最新の版でここで止めました。変更したい点を教えるか、承認してください。",
|
||||
"s7324": "このチャットの空きがなくなったため、止めました。Strata が古いメッセージを要約して空きを作っています。続けるには「続けて」と送るか、新しいチャットを始めてください。",
|
||||
"s7325": "回答を書かずに止まってしまいました。もう一度メッセージを送るか、「続けて」と送ってください。",
|
||||
"s7301": "/loop、間隔、やることの順に入力します。例:/loop 10m ビルドが通るか確認する。「stop after 3 answers」を付けると自動で止まります。止めるときは /loop stop。",
|
||||
"s7302": "止める条件だけでなく、毎回やることも書いてください。",
|
||||
"s7303": "ループが終わりました。ご指定どおり {0} 回実行しました。もう一度始めるには /loop と入力します。",
|
||||
"s7304": "直前の回答が作業の完了を伝えたため、ループを止めました。もう一度始めるには /loop と入力します。",
|
||||
"s7305": "設定した時間になったため、ループを止めました。もう一度始めるには /loop と入力します。",
|
||||
"s7306": "{0} 回続けて失敗したため、ループを止めました。モデルを確認してから /loop と入力してやり直してください。",
|
||||
"s7307": "最初の回答のあとで自動的に止まります。",
|
||||
"s7308": "{0} 回答えたあとで自動的に止まります。",
|
||||
"s7309": "{0} 分後に自動的に止まります。",
|
||||
"s7310": "回答が作業の完了を伝えたときに自動的に止まります。",
|
||||
"s7311": "Anthropic 系のアプリは /v1/messages を自分で付け足すため、このアドレスの末尾に /v1 はありません。Claude Code では ANTHROPIC_BASE_URL にこのアドレスを設定します。",
|
||||
"s0002": "(任意)",
|
||||
"s0003": "、コンテキストキャッシュが収まりません",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "スクリーンショットを保存できませんでした",
|
||||
"s3235": "もう一度試すか、このウィンドウのスクリーンショットを撮ってください。",
|
||||
"s3236": "フォルダーの画面が開きませんでした。代わりにフォルダーのパスを入力してください。",
|
||||
"s3237": "NVFP4(Strata 版)",
|
||||
"s3238": "NVFP4(NVIDIA 版)",
|
||||
"s3239": "NVFP4(NVIDIA、FP4 向けに学習)",
|
||||
"s3240": "Strata 独自の変換版です。NVFP4 の中で最も高品質です。",
|
||||
"s3241": "NVIDIA 自身の NVFP4 チェックポイントを Strata 用に変換したものです。サイズと速度は同じです。",
|
||||
"s3242": "NVIDIA が FP4 向けに学習したチェックポイントです。短いプロンプトでは少し高速です。",
|
||||
"s3243": "その他のすべてのバージョン",
|
||||
"s3244": "その他のバージョン",
|
||||
"s3245": "モデルファイルをダウンロード中 · {1} 個中 {0} 個目",
|
||||
"s3246": "画像読み取りファイルをダウンロード中…",
|
||||
"s3247": "このパソコン用のエンジンをダウンロード中…",
|
||||
"s3248": "{0} を準備中",
|
||||
"s3249": "ダウンロードの内訳",
|
||||
"s3250": "画像読み取り",
|
||||
"s3251": "共有ファイル",
|
||||
"s3252": "複数のモデルで使われています",
|
||||
"s3253": "これらのファイルはあなた自身のフォルダーにあるため、そのまま残ります。Strata 上の項目だけが削除されます。",
|
||||
"s3254": "動作中のモデルの読み込みを解除します。",
|
||||
"s3255": "ローカル",
|
||||
"s3256": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロードされますが、適切なエンジンをインストールするまで動作しない場合があります(設定 → エンジン)。",
|
||||
"s3257": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロード済みですが、適切なエンジンをインストールするまで動作しません。設定 → エンジン を開いてください。"
|
||||
"s3237": "ファイルを追加できませんでした",
|
||||
"s3238": "もう一度ドロップしてみてください。",
|
||||
"s3260": "NVFP4(Strata 版)",
|
||||
"s3261": "NVFP4(NVIDIA 版)",
|
||||
"s3262": "NVFP4(NVIDIA、FP4 向けに学習)",
|
||||
"s3263": "Strata 独自の変換版です。NVFP4 の中で最も高品質です。",
|
||||
"s3264": "NVIDIA 自身の NVFP4 チェックポイントを Strata 用に変換したものです。サイズと速度は同じです。",
|
||||
"s3265": "NVIDIA が FP4 向けに学習したチェックポイントです。短いプロンプトでは少し高速です。",
|
||||
"s3266": "その他のすべてのバージョン",
|
||||
"s3267": "その他のバージョン",
|
||||
"s3268": "モデルファイルをダウンロード中 · {1} 個中 {0} 個目",
|
||||
"s3269": "画像読み取りファイルをダウンロード中…",
|
||||
"s3270": "このパソコン用のエンジンをダウンロード中…",
|
||||
"s3271": "{0} を準備中",
|
||||
"s3272": "ダウンロードの内訳",
|
||||
"s3273": "画像読み取り",
|
||||
"s3274": "共有ファイル",
|
||||
"s3275": "複数のモデルで使われています",
|
||||
"s3276": "これらのファイルはあなた自身のフォルダーにあるため、そのまま残ります。Strata 上の項目だけが削除されます。",
|
||||
"s3277": "動作中のモデルの読み込みを解除します。",
|
||||
"s3278": "ローカル",
|
||||
"s3279": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロードされますが、適切なエンジンをインストールするまで動作しない場合があります(設定 → エンジン)。",
|
||||
"s3280": "Strata がこのパソコン用のエンジンを認識できませんでした。モデルはダウンロード済みですが、適切なエンジンをインストールするまで動作しません。設定 → エンジン を開いてください。"
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "결과는 DuckDuckGo에서 가져오며, DuckDuckGo가 바쁠 때는 Bing에서 가져옵니다. 계정이나 키는 필요하지 않습니다.",
|
||||
"s7321": "웹 검색이 지금 제한되어 있어서 검색을 멈추고 가진 정보로 이어갔습니다. 1분 뒤에 다시 시도하거나 설정 → 도구 → 웹 검색에서 검색 키를 추가하세요.",
|
||||
"s7322": "검색을 많이 해서 이 대화가 가득 차지 않도록 멈췄습니다. 지금까지 알아낸 내용입니다. 다음에 무엇을 찾아볼지 알려 주세요.",
|
||||
"s7323": "계획을 계속 다시 쓰고 있어서 최신 버전으로 여기서 멈췄습니다. 바꿀 부분을 알려 주시거나 승인해 주세요.",
|
||||
"s7324": "이 대화의 공간이 다 차서 멈췄습니다. Strata가 오래된 메시지를 요약해 공간을 만들고 있습니다. 계속하려면 “계속해”라고 보내거나 새 대화를 시작하세요.",
|
||||
"s7325": "답변을 쓰지 못하고 멈췄습니다. 메시지를 다시 보내거나 “계속해”라고 보내 주세요.",
|
||||
"s7301": "/loop, 얼마나 자주, 그리고 할 일을 순서대로 입력하세요. 예: /loop 10m 빌드가 통과하는지 확인. \"stop after 3 answers\"를 붙이면 저절로 끝납니다. 멈추려면 /loop stop.",
|
||||
"s7302": "멈출 때만이 아니라 매번 할 일도 적어 주세요.",
|
||||
"s7303": "반복이 끝났습니다. 요청하신 대로 {0}번 실행했습니다. 다시 시작하려면 /loop를 입력하세요.",
|
||||
"s7304": "마지막 답변에서 작업이 끝났다고 해서 반복을 멈췄습니다. 다시 시작하려면 /loop를 입력하세요.",
|
||||
"s7305": "설정한 시간이 다 되어 반복을 멈췄습니다. 다시 시작하려면 /loop를 입력하세요.",
|
||||
"s7306": "{0}번 연속으로 실행이 되지 않아 반복을 멈췄습니다. 모델을 확인한 뒤 /loop를 입력해 다시 시작하세요.",
|
||||
"s7307": "첫 번째 답변 뒤에 저절로 멈춥니다.",
|
||||
"s7308": "답변이 {0}번 나온 뒤에 저절로 멈춥니다.",
|
||||
"s7309": "{0}분 뒤에 저절로 멈춥니다.",
|
||||
"s7310": "답변에서 작업이 끝났다고 하면 저절로 멈춥니다.",
|
||||
"s7311": "Anthropic 앱은 /v1/messages를 스스로 붙이므로 이 주소 끝에는 /v1이 없습니다. Claude Code에서는 ANTHROPIC_BASE_URL에 이 주소를 넣으세요.",
|
||||
"s0002": "(선택 사항)",
|
||||
"s0003": ", 컨텍스트 캐시를 저장할 공간이 부족함",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "스크린샷을 저장하지 못했습니다",
|
||||
"s3235": "다시 시도하거나 이 창을 직접 캡처하세요.",
|
||||
"s3236": "폴더 창이 열리지 않았습니다. 대신 폴더 경로를 입력하세요.",
|
||||
"s3237": "NVFP4 (Strata 버전)",
|
||||
"s3238": "NVFP4 (NVIDIA 버전)",
|
||||
"s3239": "NVFP4 (NVIDIA, FP4용으로 학습)",
|
||||
"s3240": "Strata가 직접 변환한 버전입니다. NVFP4 버전 중 품질이 가장 좋습니다.",
|
||||
"s3241": "NVIDIA가 직접 만든 NVFP4 체크포인트를 Strata용으로 변환했습니다. 크기와 속도는 같습니다.",
|
||||
"s3242": "NVIDIA가 FP4용으로 학습한 체크포인트입니다. 짧은 입력에서 조금 더 빠릅니다.",
|
||||
"s3243": "다른 모든 버전",
|
||||
"s3244": "더 많은 버전",
|
||||
"s3245": "모델 파일 다운로드 중 · {1}개 중 {0}번째",
|
||||
"s3246": "이미지 읽기 파일 다운로드 중…",
|
||||
"s3247": "이 PC용 엔진 다운로드 중…",
|
||||
"s3248": "{0} 준비 중",
|
||||
"s3249": "다운로드 구성",
|
||||
"s3250": "이미지 읽기",
|
||||
"s3251": "공유 파일",
|
||||
"s3252": "여러 모델에서 함께 사용",
|
||||
"s3253": "이 파일들은 내 폴더에 있으므로 그대로 남습니다. Strata의 항목만 삭제됩니다.",
|
||||
"s3254": "실행 중인 모델을 해제합니다.",
|
||||
"s3255": "로컬",
|
||||
"s3256": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되지만 올바른 엔진을 설치하기 전에는 실행되지 않을 수 있습니다(설정 → 엔진).",
|
||||
"s3257": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되었지만 올바른 엔진을 설치하기 전에는 실행할 수 없습니다. 설정 → 엔진을 열어 주세요."
|
||||
"s3237": "파일을 추가하지 못했습니다",
|
||||
"s3238": "다시 끌어다 놓아 보세요.",
|
||||
"s3260": "NVFP4 (Strata 버전)",
|
||||
"s3261": "NVFP4 (NVIDIA 버전)",
|
||||
"s3262": "NVFP4 (NVIDIA, FP4용으로 학습)",
|
||||
"s3263": "Strata가 직접 변환한 버전입니다. NVFP4 버전 중 품질이 가장 좋습니다.",
|
||||
"s3264": "NVIDIA가 직접 만든 NVFP4 체크포인트를 Strata용으로 변환했습니다. 크기와 속도는 같습니다.",
|
||||
"s3265": "NVIDIA가 FP4용으로 학습한 체크포인트입니다. 짧은 입력에서 조금 더 빠릅니다.",
|
||||
"s3266": "다른 모든 버전",
|
||||
"s3267": "더 많은 버전",
|
||||
"s3268": "모델 파일 다운로드 중 · {1}개 중 {0}번째",
|
||||
"s3269": "이미지 읽기 파일 다운로드 중…",
|
||||
"s3270": "이 PC용 엔진 다운로드 중…",
|
||||
"s3271": "{0} 준비 중",
|
||||
"s3272": "다운로드 구성",
|
||||
"s3273": "이미지 읽기",
|
||||
"s3274": "공유 파일",
|
||||
"s3275": "여러 모델에서 함께 사용",
|
||||
"s3276": "이 파일들은 내 폴더에 있으므로 그대로 남습니다. Strata의 항목만 삭제됩니다.",
|
||||
"s3277": "실행 중인 모델을 해제합니다.",
|
||||
"s3278": "로컬",
|
||||
"s3279": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되지만 올바른 엔진을 설치하기 전에는 실행되지 않을 수 있습니다(설정 → 엔진).",
|
||||
"s3280": "Strata가 이 컴퓨터용 엔진을 인식하지 못했습니다. 모델은 다운로드되었지만 올바른 엔진을 설치하기 전에는 실행할 수 없습니다. 설정 → 엔진을 열어 주세요."
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Os resultados vêm do DuckDuckGo, ou do Bing quando o DuckDuckGo está ocupado. Você não precisa de conta nem de chave.",
|
||||
"s7321": "A pesquisa na web está limitada agora, então parei de pesquisar e segui com o que tenho. Tente de novo em um minuto ou adicione uma chave de pesquisa em Configurações → Ferramentas → Pesquisa na web.",
|
||||
"s7322": "Pesquisei bastante e parei para que este chat não encha. Isto é o que tenho até agora. Diga o que devo investigar em seguida.",
|
||||
"s7323": "Fiquei reescrevendo o plano, então parei aqui com a versão mais recente. Diga o que mudar ou aprove.",
|
||||
"s7324": "Fiquei sem espaço neste chat, então parei. O Strata está resumindo as mensagens antigas para abrir espaço. Diga “continue” para seguir ou comece um chat novo.",
|
||||
"s7325": "Parei sem escrever uma resposta. Envie sua mensagem de novo ou diga “continue”.",
|
||||
"s7301": "Digite /loop, com que frequência e depois o que fazer. Por exemplo: /loop 10m verifique se a compilação passa. Acrescente \"stop after 3 answers\" para terminar sozinho. Use /loop stop para parar.",
|
||||
"s7302": "Diga o que fazer a cada vez, não só quando parar.",
|
||||
"s7303": "O loop terminou: rodou {0} vezes, como você pediu. Digite /loop para iniciar outro.",
|
||||
"s7304": "O loop parou porque a última resposta disse que o trabalho está concluído. Digite /loop para iniciar outro.",
|
||||
"s7305": "O loop parou porque o tempo que você definiu acabou. Digite /loop para iniciar outro.",
|
||||
"s7306": "O loop parou porque {0} execuções seguidas não funcionaram. Verifique o modelo e digite /loop para iniciar de novo.",
|
||||
"s7307": "Ele para sozinho depois da primeira resposta.",
|
||||
"s7308": "Ele para sozinho depois de {0} respostas.",
|
||||
"s7309": "Ele para sozinho depois de {0} minutos.",
|
||||
"s7310": "Ele para sozinho quando uma resposta disser que o trabalho está concluído.",
|
||||
"s7311": "Os apps da Anthropic acrescentam /v1/messages sozinhos, por isso este endereço não termina em /v1. No Claude Code, defina ANTHROPIC_BASE_URL com ele.",
|
||||
"s0002": "(opcional)",
|
||||
"s0003": ", o cache de contexto não cabe",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "A captura de tela não foi salva",
|
||||
"s3235": "Tente de novo ou tire uma captura desta janela.",
|
||||
"s3236": "A janela de pastas não abriu. Digite o caminho da pasta.",
|
||||
"s3237": "NVFP4 (versão da Strata)",
|
||||
"s3238": "NVFP4 (versão da NVIDIA)",
|
||||
"s3239": "NVFP4 (NVIDIA, treinada para FP4)",
|
||||
"s3240": "Conversão própria da Strata. A melhor qualidade entre as versões NVFP4.",
|
||||
"s3241": "O checkpoint NVFP4 da própria NVIDIA, convertido para a Strata. Mesmo tamanho e velocidade.",
|
||||
"s3242": "O checkpoint da NVIDIA treinado para FP4. Um pouco mais rápido com mensagens curtas.",
|
||||
"s3243": "Todas as outras versões",
|
||||
"s3244": "Mais versões",
|
||||
"s3245": "Baixando arquivos do modelo · parte {0} de {1}",
|
||||
"s3246": "Baixando o leitor de imagens…",
|
||||
"s3247": "Baixando o mecanismo para este PC…",
|
||||
"s3248": "Preparando {0}",
|
||||
"s3249": "Partes do download",
|
||||
"s3250": "Leitor de imagens",
|
||||
"s3251": "Arquivos compartilhados",
|
||||
"s3252": "Usados por mais de um modelo",
|
||||
"s3253": "Esses arquivos estão na sua própria pasta e continuam lá. Só a entrada no Strata é removida.",
|
||||
"s3254": "O modelo em execução será descarregado.",
|
||||
"s3255": "Local",
|
||||
"s3256": "A Strata não reconheceu um mecanismo para este computador. O modelo será baixado, mas pode não funcionar até que o mecanismo certo seja instalado (Configurações → Mecanismo).",
|
||||
"s3257": "A Strata não reconheceu um mecanismo para este computador. O modelo foi baixado, mas não vai funcionar até que o mecanismo certo seja instalado. Abra Configurações → Mecanismo."
|
||||
"s3237": "O arquivo não foi adicionado",
|
||||
"s3238": "Tente soltá-lo de novo.",
|
||||
"s3260": "NVFP4 (versão da Strata)",
|
||||
"s3261": "NVFP4 (versão da NVIDIA)",
|
||||
"s3262": "NVFP4 (NVIDIA, treinada para FP4)",
|
||||
"s3263": "Conversão própria da Strata. A melhor qualidade entre as versões NVFP4.",
|
||||
"s3264": "O checkpoint NVFP4 da própria NVIDIA, convertido para a Strata. Mesmo tamanho e velocidade.",
|
||||
"s3265": "O checkpoint da NVIDIA treinado para FP4. Um pouco mais rápido com mensagens curtas.",
|
||||
"s3266": "Todas as outras versões",
|
||||
"s3267": "Mais versões",
|
||||
"s3268": "Baixando arquivos do modelo · parte {0} de {1}",
|
||||
"s3269": "Baixando o leitor de imagens…",
|
||||
"s3270": "Baixando o mecanismo para este PC…",
|
||||
"s3271": "Preparando {0}",
|
||||
"s3272": "Partes do download",
|
||||
"s3273": "Leitor de imagens",
|
||||
"s3274": "Arquivos compartilhados",
|
||||
"s3275": "Usados por mais de um modelo",
|
||||
"s3276": "Esses arquivos estão na sua própria pasta e continuam lá. Só a entrada no Strata é removida.",
|
||||
"s3277": "O modelo em execução será descarregado.",
|
||||
"s3278": "Local",
|
||||
"s3279": "A Strata não reconheceu um mecanismo para este computador. O modelo será baixado, mas pode não funcionar até que o mecanismo certo seja instalado (Configurações → Mecanismo).",
|
||||
"s3280": "A Strata não reconheceu um mecanismo para este computador. O modelo foi baixado, mas não vai funcionar até que o mecanismo certo seja instalado. Abra Configurações → Mecanismo."
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "Результаты берутся из DuckDuckGo, а когда он перегружен, из Bing. Учётная запись и ключ не нужны.",
|
||||
"s7321": "Веб-поиск сейчас ограничен, поэтому я прекратил поиск и продолжил с тем, что есть. Повторите через минуту или добавьте ключ поиска в Настройки → Инструменты → Поиск в интернете.",
|
||||
"s7322": "Я много искал и остановился, чтобы этот чат не переполнился. Вот что у меня есть на данный момент. Скажите, что искать дальше.",
|
||||
"s7323": "Я всё время переписывал план, поэтому остановился на последней версии. Скажите, что изменить, или одобрите его.",
|
||||
"s7324": "В этом чате закончилось место, поэтому я остановился. Strata сжимает старые сообщения, чтобы освободить место. Напишите «продолжай», чтобы идти дальше, или начните новый чат.",
|
||||
"s7325": "Я остановился, не написав ответ. Отправьте сообщение ещё раз или напишите «продолжай».",
|
||||
"s7301": "Введите /loop, как часто и что делать. Например: /loop 10m проверь, проходит ли сборка. Добавьте «stop after 3 answers», чтобы цикл закончился сам. Чтобы остановить, введите /loop stop.",
|
||||
"s7302": "Напишите, что делать каждый раз, а не только когда остановиться.",
|
||||
"s7303": "Цикл завершён: он выполнился {0} раз, как вы просили. Введите /loop, чтобы запустить новый.",
|
||||
"s7304": "Цикл остановлен: в последнем ответе сказано, что работа закончена. Введите /loop, чтобы запустить новый.",
|
||||
"s7305": "Цикл остановлен: заданное вами время вышло. Введите /loop, чтобы запустить новый.",
|
||||
"s7306": "Цикл остановлен: {0} запусков подряд не удались. Проверьте модель и введите /loop, чтобы начать заново.",
|
||||
"s7307": "Он остановится сам после первого ответа.",
|
||||
"s7308": "Он остановится сам после {0} ответов.",
|
||||
"s7309": "Он остановится сам через {0} мин.",
|
||||
"s7310": "Он остановится сам, когда в ответе будет сказано, что работа закончена.",
|
||||
"s7311": "Приложения Anthropic сами добавляют /v1/messages, поэтому в конце этого адреса нет /v1. В Claude Code укажите его в ANTHROPIC_BASE_URL.",
|
||||
"s0002": "(необязательно)",
|
||||
"s0003": ", кеш контекста не помещается",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "Снимок экрана не сохранён",
|
||||
"s3235": "Попробуйте ещё раз или сделайте снимок этого окна.",
|
||||
"s3236": "Окно выбора папки не открылось. Введите путь к папке вручную.",
|
||||
"s3237": "NVFP4 (версия Strata)",
|
||||
"s3238": "NVFP4 (версия NVIDIA)",
|
||||
"s3239": "NVFP4 (NVIDIA, обучена для FP4)",
|
||||
"s3240": "Собственная конвертация Strata. Лучшее качество среди версий NVFP4.",
|
||||
"s3241": "Собственный NVFP4-чекпойнт NVIDIA, конвертированный для Strata. Тот же размер и скорость.",
|
||||
"s3242": "Чекпойнт NVIDIA, обученный для FP4. Немного быстрее на коротких запросах.",
|
||||
"s3243": "Все остальные версии",
|
||||
"s3244": "Другие версии",
|
||||
"s3245": "Скачивание файлов модели · часть {0} из {1}",
|
||||
"s3246": "Скачивание модуля чтения изображений…",
|
||||
"s3247": "Скачивание движка для этого компьютера…",
|
||||
"s3248": "Подготовка: {0}",
|
||||
"s3249": "Части загрузки",
|
||||
"s3250": "Чтение изображений",
|
||||
"s3251": "Общие файлы",
|
||||
"s3252": "Используются несколькими моделями",
|
||||
"s3253": "Эти файлы лежат в вашей папке и останутся там. Из Strata удаляется только запись.",
|
||||
"s3254": "Работающая модель будет выгружена.",
|
||||
"s3255": "Локальная",
|
||||
"s3256": "Strata не распознала движок для этого компьютера. Модель всё равно скачается, но может не запуститься, пока не будет установлен нужный движок (Настройки → Движок).",
|
||||
"s3257": "Strata не распознала движок для этого компьютера. Модель скачана, но не запустится, пока не будет установлен нужный движок. Откройте Настройки → Движок."
|
||||
"s3237": "Файл не добавлен",
|
||||
"s3238": "Попробуйте перетащить его ещё раз.",
|
||||
"s3260": "NVFP4 (версия Strata)",
|
||||
"s3261": "NVFP4 (версия NVIDIA)",
|
||||
"s3262": "NVFP4 (NVIDIA, обучена для FP4)",
|
||||
"s3263": "Собственная конвертация Strata. Лучшее качество среди версий NVFP4.",
|
||||
"s3264": "Собственный NVFP4-чекпойнт NVIDIA, конвертированный для Strata. Тот же размер и скорость.",
|
||||
"s3265": "Чекпойнт NVIDIA, обученный для FP4. Немного быстрее на коротких запросах.",
|
||||
"s3266": "Все остальные версии",
|
||||
"s3267": "Другие версии",
|
||||
"s3268": "Скачивание файлов модели · часть {0} из {1}",
|
||||
"s3269": "Скачивание модуля чтения изображений…",
|
||||
"s3270": "Скачивание движка для этого компьютера…",
|
||||
"s3271": "Подготовка: {0}",
|
||||
"s3272": "Части загрузки",
|
||||
"s3273": "Чтение изображений",
|
||||
"s3274": "Общие файлы",
|
||||
"s3275": "Используются несколькими моделями",
|
||||
"s3276": "Эти файлы лежат в вашей папке и останутся там. Из Strata удаляется только запись.",
|
||||
"s3277": "Работающая модель будет выгружена.",
|
||||
"s3278": "Локальная",
|
||||
"s3279": "Strata не распознала движок для этого компьютера. Модель всё равно скачается, но может не запуститься, пока не будет установлен нужный движок (Настройки → Движок).",
|
||||
"s3280": "Strata не распознала движок для этого компьютера. Модель скачана, но не запустится, пока не будет установлен нужный движок. Откройте Настройки → Движок."
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
{
|
||||
"s0001": "% PCIe",
|
||||
"s7331": "结果来自 DuckDuckGo;DuckDuckGo 繁忙时来自 Bing。不需要账号或密钥。",
|
||||
"s7321": "网络搜索目前受到限制,所以我停止了搜索,用已有的信息继续。请一分钟后再试,或在“设置 → 工具 → 网络搜索”中添加搜索密钥。",
|
||||
"s7322": "我搜索了很多次,为了不让这次对话被占满而停下了。以上是目前的结果。请告诉我接下来要查什么。",
|
||||
"s7323": "我一直在重写计划,所以停在这里,保留了最新版本。请告诉我要改什么,或直接批准。",
|
||||
"s7324": "这次对话的空间用完了,所以我停了下来。Strata 正在总结较早的消息来腾出空间。说“继续”即可接着做,或者开始新的对话。",
|
||||
"s7325": "我停了下来,但没有写出回答。请再发一次消息,或说“继续”。",
|
||||
"s7301": "输入 /loop,再写多久一次,然后写要做什么。例如:/loop 10m 检查构建是否通过。加上“stop after 3 answers”可让它自动结束。用 /loop stop 停止。",
|
||||
"s7302": "请写明每次要做什么,而不只是何时停止。",
|
||||
"s7303": "循环已完成:按你的要求运行了 {0} 次。输入 /loop 可再开始一个。",
|
||||
"s7304": "循环已停止,因为上一条回答说工作已完成。输入 /loop 可再开始一个。",
|
||||
"s7305": "循环已停止,因为你设定的时间到了。输入 /loop 可再开始一个。",
|
||||
"s7306": "循环已停止,因为连续 {0} 次运行都没有成功。请检查模型,然后输入 /loop 重新开始。",
|
||||
"s7307": "第一条回答之后会自动停止。",
|
||||
"s7308": "{0} 条回答之后会自动停止。",
|
||||
"s7309": "{0} 分钟后会自动停止。",
|
||||
"s7310": "当某条回答说工作已完成时,会自动停止。",
|
||||
"s7311": "Anthropic 类应用会自己加上 /v1/messages,所以这个地址末尾没有 /v1。在 Claude Code 中,把 ANTHROPIC_BASE_URL 设为这个地址。",
|
||||
"s0002": "(可选)",
|
||||
"s0003": ",上下文缓存无法容纳",
|
||||
"s0004": "-y @modelcontextprotocol/server-filesystem /your/folder",
|
||||
@@ -3230,25 +3247,27 @@
|
||||
"s3234": "截图未能保存",
|
||||
"s3235": "请重试,或改为对此窗口截屏。",
|
||||
"s3236": "文件夹窗口没有打开。请改为输入文件夹路径。",
|
||||
"s3237": "NVFP4(Strata 版本)",
|
||||
"s3238": "NVFP4(NVIDIA 版本)",
|
||||
"s3239": "NVFP4(NVIDIA,为 FP4 训练)",
|
||||
"s3240": "Strata 自己的转换版本,是 NVFP4 各版本中质量最好的。",
|
||||
"s3241": "NVIDIA 自己的 NVFP4 检查点,已为 Strata 转换。大小和速度相同。",
|
||||
"s3242": "NVIDIA 为 FP4 训练的检查点。短提示下速度略快。",
|
||||
"s3243": "其他所有版本",
|
||||
"s3244": "更多版本",
|
||||
"s3245": "正在下载模型文件 · 第 {0} 部分,共 {1} 部分",
|
||||
"s3246": "正在下载图片读取组件…",
|
||||
"s3247": "正在下载适用于此电脑的引擎…",
|
||||
"s3248": "正在准备 {0}",
|
||||
"s3249": "下载分段",
|
||||
"s3250": "图片读取组件",
|
||||
"s3251": "共享文件",
|
||||
"s3252": "被多个模型共用",
|
||||
"s3253": "这些文件在你自己的文件夹中,会保留在原处,只会从 Strata 中移除该条目。",
|
||||
"s3254": "将卸载运行中的模型。",
|
||||
"s3255": "本地",
|
||||
"s3256": "Strata 没有识别出适用于这台电脑的引擎。模型仍会下载,但在安装正确的引擎之前可能无法运行(设置 → 引擎)。",
|
||||
"s3257": "Strata 没有识别出适用于这台电脑的引擎。模型已下载,但在安装正确的引擎之前无法运行。请打开 设置 → 引擎。"
|
||||
"s3237": "文件未能添加",
|
||||
"s3238": "请再拖放一次。",
|
||||
"s3260": "NVFP4(Strata 版本)",
|
||||
"s3261": "NVFP4(NVIDIA 版本)",
|
||||
"s3262": "NVFP4(NVIDIA,为 FP4 训练)",
|
||||
"s3263": "Strata 自己的转换版本,是 NVFP4 各版本中质量最好的。",
|
||||
"s3264": "NVIDIA 自己的 NVFP4 检查点,已为 Strata 转换。大小和速度相同。",
|
||||
"s3265": "NVIDIA 为 FP4 训练的检查点。短提示下速度略快。",
|
||||
"s3266": "其他所有版本",
|
||||
"s3267": "更多版本",
|
||||
"s3268": "正在下载模型文件 · 第 {0} 部分,共 {1} 部分",
|
||||
"s3269": "正在下载图片读取组件…",
|
||||
"s3270": "正在下载适用于此电脑的引擎…",
|
||||
"s3271": "正在准备 {0}",
|
||||
"s3272": "下载分段",
|
||||
"s3273": "图片读取组件",
|
||||
"s3274": "共享文件",
|
||||
"s3275": "被多个模型共用",
|
||||
"s3276": "这些文件在你自己的文件夹中,会保留在原处,只会从 Strata 中移除该条目。",
|
||||
"s3277": "将卸载运行中的模型。",
|
||||
"s3278": "本地",
|
||||
"s3279": "Strata 没有识别出适用于这台电脑的引擎。模型仍会下载,但在安装正确的引擎之前可能无法运行(设置 → 引擎)。",
|
||||
"s3280": "Strata 没有识别出适用于这台电脑的引擎。模型已下载,但在安装正确的引擎之前无法运行。请打开 设置 → 引擎。"
|
||||
}
|
||||
@@ -4,10 +4,13 @@ import './styles/kit/tokens.css';
|
||||
import './styles/kit/components.css';
|
||||
import './styles/app.css';
|
||||
import { App } from './app/App';
|
||||
import { installDropGuard } from './components/DropZone';
|
||||
|
||||
const el = document.getElementById('root');
|
||||
if (!el) throw new Error('#root missing');
|
||||
|
||||
installDropGuard();
|
||||
|
||||
createRoot(el).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
|
||||
@@ -151,7 +151,7 @@ function LegacyMonitorScreen({ native }: {
|
||||
const multipleScope = selection === 'all' && (runtime?.instances.length ?? 0) > 1;
|
||||
const chooseInstance = (id: string) => { setInstanceSelection(id); setGpuSelection(id !== 'all' && (runtime?.instances.find(instance => instance.id === id)?.gpuIds.length ?? 0) > 0 ? 'assigned' : 'all'); };
|
||||
const overview = <div className="stack stack--lg monitor-capture monitor-dashboard" ref={snapshotRef}>
|
||||
{tr(frozen ? <header className="section-toolbar"><div><div className="snapshot__brand-title"><Brand variant="lockup" height={24} decorative/><h1 className="h2">{tr("Monitor")}</h1></div><p className="small muted">{tr(frozen.modelLabel)} · {tr(frozen.time)}</p></div></header> : null)}
|
||||
{tr(frozen ? <header className="section-toolbar"><div><div className="snapshot__brand-title"><Brand variant="lockup" height={24} decorative/></div><p className="small muted">{tr(frozen.modelLabel)} · {tr(frozen.time)}</p></div></header> : null)}
|
||||
{tr(multipleModels ? <section className="st-card"><h2 className="h4">{tr("Model performance")}</h2><div className="st-tablewrap"><table className="st-table native-performance-table"><thead><tr><th>{tr("Model / device")}</th><th>{tr("Generating tok/s")}</th><th>{tr("Reading tok/s")}</th><th>{tr("State")}</th><th>{tr("Active / queued")}</th></tr></thead><tbody>{tr(runtime?.instances.map(i => { const recent = (data.requests ?? []).find(r => r.instanceId === i.id); const writing = i.phase === 'generating' || i.phase === 'thinking', reading = i.phase === 'reading'; return <tr key={i.id}><td><button className="text-btn strong" onClick={() => chooseInstance(i.id)}>{tr(instanceLabel(i))}</button><small>{tr(deviceLabel(i.gpuIds, inventory))}</small></td><td>{tr(number(writing ? i.outputTps : recent?.tps, 1))}<small>{tr(writing ? 'Now' : recent ? 'Last request' : 'No request yet')}</small></td><td>{tr(number(reading ? i.promptTps : recent?.promptTps, 0))}<small>{tr(reading ? 'Now' : recent ? 'Last request' : 'No request yet')}</small></td><td>{tr(i.phase)}{tr(runtime.mode === 'simulated' ? <small>{tr("Illustrative")}</small> : null)}</td><td>{tr(number(i.active))} / {tr(number(i.queued))}</td></tr>; }))}</tbody></table></div></section> : null)}
|
||||
{tr(multipleModels ? <p className="xs muted monitor-scope-note">{tr(selectedInstance ? selectedInstance.gpuIds.length ? 'Requests, context and speed are scoped to this model. GPU readings include all work on the selected devices.' : 'CPU-only model. Requests and context are scoped to this model; system metrics are shared host measurements.' : 'Select a model for its context and speed. GPU readings and system RAM are shared host measurements.')}</p> : null)}
|
||||
<section className="st-card monitor-state" aria-label={tr("Model state")} data-snapshot-skip>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tr } from '../lib/i18n';
|
||||
import { appBaseUrl } from '../lib/connect-urls';
|
||||
import { deviceLabel, instanceLabel } from '../lib/runtime-models';
|
||||
import { nativeRouting, useNative } from '../lib/native';
|
||||
/** Connection facts first. Instructions and request details open only on demand. */
|
||||
@@ -94,7 +95,7 @@ export function ServingScreen() {
|
||||
{tr(requests.length ? <div className="st-tablewrap"><table className="st-table"><thead><tr><th aria-sort={sort === 'at' ? 'descending' : 'none'}><button className="st-btn st-btn--ghost st-btn--sm" onClick={() => setSort('at')}>{tr("Time")}</button></th><th>{tr("Client / endpoint")}</th>{tr(multipleModels ? <th>{tr("Model")}</th> : null)}<th>{tr("Status")}</th><th>{tr("Tokens in / out")}</th><th aria-sort={sort === 'durationMs' ? 'descending' : 'none'}><button className="st-btn st-btn--ghost st-btn--sm" onClick={() => setSort('durationMs')}>{tr("Duration")}</button></th></tr></thead><tbody>{tr(requests.map(r => <tr key={r.id}><td><button className="st-btn st-btn--ghost st-btn--sm" aria-label={tr("View request {0}", [r.id])} onClick={() => setSelectedId(r.id)}>{tr(clockTime(r.at))}</button></td><td>{tr(r.client)}<div className="xs muted">{tr(r.endpoint)}</div></td>{tr(multipleModels ? <td><code className="xs">{r.model}</code></td> : null)}<td>{tr(<span className="request-status" data-state={r.state}>{tr(r.cancelRequested ? r.cancellable ? 'Cancelling…' : 'Cancelled' : r.state.charAt(0).toUpperCase() + r.state.slice(1))}</span>)}</td><td className="num">{tr(tokens(r.tokensIn))} / {tr(tokens(r.tokensOut))}<div className="xs muted">{tr(r.usageSource === 'demo' ? 'Simulated' : r.usageSource === 'reported' ? 'Reported by model' : 'Usage unavailable')}</div></td><td className="num">{tr(r.durationMs ? duration(r.durationMs) : '—')}</td></tr>))}</tbody></table></div> : <Empty icon="link" title={tr(serving.requests.length ? 'No matching requests' : 'No requests yet')} body={serving.requests.length ? 'Try another filter or client name.' : 'Requests appear here when a client or Strata chat uses the API.'} action={tr(serving.requests.length ? <Btn onClick={() => { setQuery(''); setFilter('all'); setModelFilter('all'); }}>{tr("Clear filters")}</Btn> : <Btn onClick={() => setGuide(true)}>{tr("Connect an app")}</Btn>)}/>)}</section>
|
||||
|
||||
{tr(error ? <ErrorNotice message={error}/> : null)}
|
||||
</div><Dialog open={guide} title={tr("Connect Strata to an app")} onClose={() => setGuide(false)} headerActions={<div className="protocol-switch"><Seg panelId="api-protocol-panel" value={protocol} ariaLabel={tr("API protocol")} options={[{ value: 'openai', label: 'Chat Completions' }, { value: 'responses', label: 'Responses' }, { value: 'anthropic', label: 'Anthropic' }]} onChange={setProtocol}/></div>} sheet><div className="stack">{tr(multipleModels ? <label className="input-field"><span>{tr("Model for this app")}</span><Select ariaLabel={tr("Connection guide model")} value={loaded?.apiModelId ?? ''} options={modelOptions} disabled={!modelOptions.length} onChange={setGuideModel}/></label> : null)}<ol><li>{tr("In your client, choose a compatible provider.")}</li><li>{tr("Set its base URL to ")}<code>{serving.baseUrl}</code>.</li><li>{tr("Use model ID ")}<code>{loaded?.apiModelId ?? 'from the Models screen after loading'}</code>.</li><li>{tr(serving.access.apiKeySet ? 'Enter your existing API key in the client.' : 'This local API has no key configured.')}</li></ol>{tr(protocol === 'responses' && (!native?.instances.some(i => i.status === 'ready') || native.capabilities.responses === false) ? <p className="small muted">{tr("Responses requires a running native model and a Strata version that supports this API. Update the native installation in Settings \u2192 About if needed.")}</p> : null)}<div id="api-protocol-panel" role="tabpanel" aria-labelledby={`api-protocol-panel-tab-${protocol}`} tabIndex={0}><div className="st-code"><div className="st-code__head"><span>{tr("curl")}</span><IconBtn name="copy" title={tr("Copy request template")} onClick={() => void navigator.clipboard.writeText(code)}/></div><pre>{code}</pre></div><p className="xs muted">{tr("Model list: ")}{tr(serving.baseUrl)}{tr(serving.endpoints.models)}{tr(". Network access depends on the host\u2019s listen address and your firewall.")}</p></div></div></Dialog>
|
||||
</div><Dialog open={guide} title={tr("Connect Strata to an app")} onClose={() => setGuide(false)} headerActions={<div className="protocol-switch"><Seg panelId="api-protocol-panel" value={protocol} ariaLabel={tr("API protocol")} options={[{ value: 'openai', label: 'Chat Completions' }, { value: 'responses', label: 'Responses' }, { value: 'anthropic', label: 'Anthropic' }]} onChange={setProtocol}/></div>} sheet><div className="stack">{tr(multipleModels ? <label className="input-field"><span>{tr("Model for this app")}</span><Select ariaLabel={tr("Connection guide model")} value={loaded?.apiModelId ?? ''} options={modelOptions} disabled={!modelOptions.length} onChange={setGuideModel}/></label> : null)}<ol><li>{tr("In your client, choose a compatible provider.")}</li><li>{tr("Set its base URL to ")}<code>{appBaseUrl(serving.baseUrl, protocol)}</code>.</li><li>{tr("Use model ID ")}<code>{loaded?.apiModelId ?? 'from the Models screen after loading'}</code>.</li><li>{tr(serving.access.apiKeySet ? 'Enter your existing API key in the client.' : 'This local API has no key configured.')}</li></ol>{tr(protocol === 'anthropic' ? <p className="small muted">{tr("Anthropic apps add /v1/messages themselves, so this address has no /v1 at the end. In Claude Code, set ANTHROPIC_BASE_URL to it.")}</p> : null)}{tr(protocol === 'responses' && (!native?.instances.some(i => i.status === 'ready') || native.capabilities.responses === false) ? <p className="small muted">{tr("Responses requires a running native model and a Strata version that supports this API. Update the native installation in Settings \u2192 About if needed.")}</p> : null)}<div id="api-protocol-panel" role="tabpanel" aria-labelledby={`api-protocol-panel-tab-${protocol}`} tabIndex={0}><div className="st-code"><div className="st-code__head"><span>{tr("curl")}</span><IconBtn name="copy" title={tr("Copy request template")} onClick={() => void navigator.clipboard.writeText(code)}/></div><pre>{code}</pre></div><p className="xs muted">{tr("Model list: ")}{tr(serving.baseUrl)}{tr(serving.endpoints.models)}{tr(". Network access depends on the host\u2019s listen address and your firewall.")}</p></div></div></Dialog>
|
||||
<Dialog open={!!selectedId} title={tr("Request details")} onClose={() => setSelectedId(null)} sheet>{tr(selected ? <><dl className="summary-list"><div><dt>{tr("ID")}</dt><dd className="mono">{tr(selected.id)}</dd></div><div><dt>{tr("State")}</dt><dd>{tr(selected.cancelRequested ? selected.cancellable ? 'Cancelling…' : 'Cancelled' : selected.state)}</dd></div><div><dt>{tr("Model")}</dt><dd>{tr(selected.model)}</dd></div><div><dt>{tr("Tokens in / out")}</dt><dd>{tr(tokens(selected.tokensIn))} / {tr(tokens(selected.tokensOut))}</dd></div><div><dt>{tr("Usage source")}</dt><dd>{tr(selected.usageSource === 'demo' ? 'Simulated' : selected.usageSource === 'reported' ? 'Reported by model' : 'Unavailable')}</dd></div><div><dt>{tr("Recorded duration")}</dt><dd>{tr(selected.durationMs ? duration(selected.durationMs) : 'Not yet available')}</dd></div></dl>{tr(selected.error ? <div ref={cancelResult} tabIndex={-1}><ErrorNotice message={selected.error} next={tr("Check the client connection and try the request again.")}/></div> : null)}<p className="small muted">{tr("Prompt content and historical queue position are not retained. This view updates while the request runs.")}</p>{tr(selected.cancellable !== false && ['queued', 'generating'].includes(selected.state) ? <Btn disabled={pending || selected.cancelRequested} onClick={() => { requestedCancel.current = selected.id; void operation(() => cancelRequest(selected.id)); }}>{tr(selected.cancelRequested ? 'Cancelling…' : 'Cancel request')}</Btn> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</> : <p>{tr("This request is no longer retained in the session log.")}</p>)}</Dialog>
|
||||
<Dialog open={sharingOpen} title={tr("Local sharing")} onClose={() => !pending && setSharingOpen(false)} actions={<><Btn disabled={pending} onClick={() => setSharingOpen(false)}>{tr("Close")}</Btn><Btn variant="primary" disabled={pending || !serving.access.apiKeySet} onClick={() => void operation(async () => { await setLocalSharing(!serving.sharing?.active); setSharingOpen(false); })}>{tr(pending ? 'Updating…' : serving.sharing?.active ? 'Stop sharing' : 'Start sharing')}</Btn></>}><div className="form-stack"><span className="dialog-feature-icon"><Icon name="link" size={28}/></span><p>{tr(serving.sharing?.active ? 'Your inference API is available to devices on this network.' : 'Let another device on your network use your loaded models.')}</p><p className="small muted">{tr("Only the inference API is shared. Clients need your API key. Use a trusted local network; this connection uses HTTP.")}</p>{tr(serving.sharing?.active ? <div className="row"><code className="key-url">{serving.sharing.url}</code><IconBtn name="copy" title={tr("Copy local network URL")} onClick={() => void navigator.clipboard.writeText(serving.sharing!.url!)}/></div> : null)}{tr(!serving.access.apiKeySet ? <Btn onClick={() => { generateKey(); setSharingOpen(false); setKeyOpen(true); }}>{tr("Create an API key first")}</Btn> : <p className="small muted"><Icon name="shield" size={16}/>{tr(" API key required")}</p>)}{tr(error ? <ErrorNotice message={error}/> : null)}</div></Dialog>
|
||||
<Dialog open={keyOpen} className="serving-key-dialog" title={tr(serving.access.apiKeySet ? 'Change API key' : 'Create an API key')} onClose={() => {
|
||||
|
||||
@@ -186,12 +186,13 @@ test('search: a human check or a refusal is told in plain words, and a real sear
|
||||
assert.equal(looksBlocked(200, '<div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too</div>'), true);
|
||||
assert.equal(looksBlocked(200, HTML), false);
|
||||
const sleeps = [];
|
||||
const blocked = createDuckDuckGoSearch({ fetch: async () => new Response('<html>captcha anomaly-modal</html>', { status: 200 }), sleep: async ms => { sleeps.push(ms); } });
|
||||
const tick = () => { let t = 1_000_000; return { now: () => t, sleep: async ms => { sleeps.push(ms); t += ms; } }; };
|
||||
const blocked = createDuckDuckGoSearch({ ...tick(), fetch: async () => new Response('<html>captcha anomaly-modal</html>', { status: 200 }) });
|
||||
await assert.rejects(blocked.search({ query: 'x' }), e => e.message === BLOCKED_MESSAGE && e.code === 'WEB_RATE_LIMITED');
|
||||
const empty = createDuckDuckGoSearch({ fetch: async () => new Response('<html><body>No results.</body></html>', { status: 200 }), sleep: async () => {} });
|
||||
const empty = createDuckDuckGoSearch({ ...tick(), fetch: async () => new Response('<html><body>No results.</body></html>', { status: 200 }) });
|
||||
assert.deepEqual(await empty.search({ query: 'zzzz' }), { sources: [], truncated: false });
|
||||
const offline = createDuckDuckGoSearch({ fetch: async () => { throw new TypeError('fetch failed'); }, sleep: async () => {} });
|
||||
await assert.rejects(offline.search({ query: 'x' }), /could not reach DuckDuckGo/);
|
||||
const offline = createDuckDuckGoSearch({ ...tick(), fetch: async () => { throw new TypeError('fetch failed'); } });
|
||||
await assert.rejects(offline.search({ query: 'x' }), /could not reach the internet/);
|
||||
});
|
||||
|
||||
test('search: polite by design: one request at a time, spaced out, a minute limit, and the same query is answered from a short cache', async () => {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
// The turn guard: a search-heavy /plan that keeps failing searches and rewriting its plan is stopped by the app and ends with a plain message;
|
||||
// a context at 100% never ends silently. The pure counting always runs; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and
|
||||
// run the real search code on a pretend web that refuses (no network).
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { TurnGuard, GUARD_LIMITS, GUARD_NOTES, guardNote } from '../server/agent/turn-guard.mjs';
|
||||
import { startScriptedWorker } from './helpers/scripted-worker.mjs';
|
||||
import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
|
||||
import { resolveHarness } from '../server/agent/harness-runtime.mjs';
|
||||
|
||||
const HARNESS = process.env.STRATA_HARNESS_DIR;
|
||||
const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
|
||||
|
||||
const search = (id, state, result = '') => ({ id, name: 'web_search', state, result });
|
||||
const LIMITED = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search. Do not retry this search';
|
||||
|
||||
test('three failed searches in a row stop the turn; a search that worked starts the count again', () => {
|
||||
const g = new TurnGuard({ plan: true, contextMax: 32768 });
|
||||
assert.equal(g.card(search('a', 'running')), null, 'a running search is not counted yet');
|
||||
assert.equal(g.card(search('a', 'error', LIMITED)), null);
|
||||
assert.equal(g.card(search('a', 'error', LIMITED)), null, 'the same card twice is one search');
|
||||
assert.equal(g.card(search('b', 'done', 'three results')), null);
|
||||
assert.equal(g.card(search('c', 'error', LIMITED)), null);
|
||||
assert.equal(g.card(search('d', 'done', LIMITED)), null, 'a refusal that arrives as a normal result still counts');
|
||||
assert.equal(g.card(search('e', 'error', LIMITED)), 'searches-failed');
|
||||
assert.equal(g.card(search('f', 'error', LIMITED)), 'searches-failed', 'once stopped it stays stopped');
|
||||
assert.equal(g.searches, 5);
|
||||
});
|
||||
|
||||
test('other tools are not searches; too many searches in one turn stop it even when they work', () => {
|
||||
const g = new TurnGuard({ plan: true });
|
||||
for (let i = 0; i < 50; i++) assert.equal(g.card({ id: `r${i}`, name: 'read', state: 'done' }), null);
|
||||
for (let i = 0; i < GUARD_LIMITS.searchesPlan - 1; i++) assert.equal(g.card(search(`s${i}`, 'done', 'ok')), null);
|
||||
assert.equal(g.card(search('last', 'done', 'ok')), 'searches');
|
||||
const t = new TurnGuard({ plan: false });
|
||||
for (let i = 0; i < GUARD_LIMITS.searchesTurn - 1; i++) assert.equal(t.card(search(`s${i}`, 'done', 'ok')), null);
|
||||
assert.equal(t.card(search('last', 'done', 'ok')), 'searches');
|
||||
});
|
||||
|
||||
test('a plan turn that writes its numbered plan from 1. again and again is stopped; a single plan is not', () => {
|
||||
const g = new TurnGuard({ plan: true });
|
||||
const plan = '## Plan\n\n1. First\n2. Second\n3. Third\n\n';
|
||||
let reason = null;
|
||||
for (let i = 0; i < GUARD_LIMITS.planRewrites - 1; i++) reason ??= g.text(plan);
|
||||
assert.equal(reason, null, `${GUARD_LIMITS.planRewrites - 1} versions are fine`);
|
||||
assert.equal(g.text(plan), 'rewrites');
|
||||
const one = new TurnGuard({ plan: true });
|
||||
for (const piece of ['Some looking around.\n\n## Plan\n\n', '1. First\n', '2. Second\n', ' 1. a sub point\n', '3. Third\n']) assert.equal(one.text(piece), null, piece);
|
||||
const ordinary = new TurnGuard({ plan: false });
|
||||
for (let i = 0; i < 10; i++) assert.equal(ordinary.text(plan), null, 'only a plan turn counts rewrites');
|
||||
});
|
||||
|
||||
test('a nearly full context stops the turn; a normal one does not', () => {
|
||||
const g = new TurnGuard({ contextMax: 10000 });
|
||||
assert.equal(g.context(5000), null);
|
||||
assert.equal(g.context(9200), null);
|
||||
assert.equal(g.context(9300), 'context');
|
||||
assert.equal(new TurnGuard({ contextMax: 0 }).context(1e9), null, 'an unknown window is never guessed');
|
||||
});
|
||||
|
||||
test('a turn that ends with no words always gets a plain message: out of room, or nothing written', () => {
|
||||
const g = new TurnGuard({ contextMax: 10000 });
|
||||
const done = { kind: 'completed' };
|
||||
assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700 }), 'context');
|
||||
assert.equal(g.silent({ ended: { kind: 'max-tokens' }, wrote: false, contextTokens: 9000 }), 'context');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 3000 }), 'empty');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 3000 }), null, 'cards of finished work are an answer of a kind');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 9700 }), 'context', 'but a full context is never silent');
|
||||
assert.equal(g.silent({ ended: done, wrote: true, contextTokens: 9700 }), null, 'there are words: nothing to add');
|
||||
assert.equal(g.silent({ ended: { kind: 'error', error: { message: 'x' } }, wrote: false, contextTokens: 9700 }), null, 'an error says why by itself');
|
||||
assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700, stoppedByPerson: true }), null, 'Stop is the person\'s own');
|
||||
});
|
||||
|
||||
test('every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all eight languages', () => {
|
||||
const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];
|
||||
const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))]));
|
||||
const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0];
|
||||
for (const [reason, text] of Object.entries(GUARD_NOTES)) {
|
||||
const frame = guardNote(reason);
|
||||
assert.equal(frame.type, 'delta'); assert.equal(frame.key, text); assert.equal(frame.own, true);
|
||||
assert.ok(text.length < 220, reason);
|
||||
assert.match(text, /(Try again|Tell me|Say|Send|approve)/i, `${reason} gives a next step`);
|
||||
const id = idOf(text);
|
||||
assert.ok(id, `${reason} is in the English catalog`);
|
||||
for (const l of langs) assert.ok(catalogs[l][id]?.trim(), `${reason} in ${l}`);
|
||||
}
|
||||
assert.match(GUARD_NOTES.context, /ran out of room/);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ with the real Harness
|
||||
|
||||
async function rig(t, options = {}) {
|
||||
const worker = await startScriptedWorker({ chunkDelayMs: 5 });
|
||||
const dir = mkdtempSync(join(tmpdir(), 'strata-guard-'));
|
||||
const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
|
||||
const logs = [];
|
||||
const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: options.context ?? 32768, slots: 2 }], connections: () => [],
|
||||
env: process.env, startTimeoutMs: 90_000, searchMock: 'limited', log: l => logs.push(l) });
|
||||
t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });
|
||||
return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'manual', onFrame }) };
|
||||
}
|
||||
const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
|
||||
|
||||
test('a search-heavy /plan on a web that keeps refusing stops after 3 failed searches, proposes the plan it has, and says why', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const out = [];
|
||||
await r.bridge.planCommand({ ...r.base('p1', f => out.push(f)), line: 'SCRIPT:searchloop' });
|
||||
const cards = out.filter(f => f.type === 'agent-tool' && f.tool.name === 'web_search' && ['done', 'error'].includes(f.tool.state));
|
||||
assert.ok(cards.length >= 3 && cards.length <= 4, `searches stopped at the limit (${cards.length})`);
|
||||
assert.ok(cards.some(f => /Web search is limited right now/.test(f.tool.result ?? '')), 'the tool said web search is limited');
|
||||
assert.equal(out.filter(f => f.type === 'error').length, 0, 'not an error: a normal end');
|
||||
const done = out.find(f => f.type === 'done');
|
||||
assert.ok(done && !done.cancelled, 'the turn ended normally');
|
||||
const plan = out.find(f => f.type === 'plan');
|
||||
assert.equal(plan?.event, 'proposed', 'the plan it had is offered');
|
||||
assert.equal(plan.plan.steps.length, 3);
|
||||
assert.equal(plan.plan.caution, GUARD_NOTES['searches-failed'], 'and the card says why it stopped early');
|
||||
const requests = r.worker.requests.filter(q => q.directive === 'searchloop');
|
||||
assert.ok(requests.length <= 5, `the model was not asked again and again (${requests.length} requests)`);
|
||||
assert.ok(r.logs.some(l => /turn guard: searches-failed/.test(l)));
|
||||
});
|
||||
|
||||
test('an ordinary turn whose searches keep failing ends with the plain sentence as its last words', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const out = [];
|
||||
await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:searchloop' });
|
||||
assert.equal(out.filter(f => f.type === 'error').length, 0);
|
||||
assert.ok(out.find(f => f.type === 'done'));
|
||||
const note = out.filter(f => f.type === 'delta' && f.key).at(-1);
|
||||
assert.equal(note?.key, GUARD_NOTES['searches-failed']);
|
||||
assert.match(words(out), /Settings → Tools → Web search/);
|
||||
assert.ok(out.findIndex(f => f.key) < out.findIndex(f => f.type === 'done'), 'the sentence comes before the end of the turn');
|
||||
});
|
||||
|
||||
test('a context at 100% with no answer is never silent: the plain message comes, and the older messages are summarised', { skip }, async (t) => {
|
||||
const r = await rig(t, { context: 32768 });
|
||||
const out = [];
|
||||
await r.bridge.runTurn({ ...r.base('f1', f => out.push(f)), message: 'SCRIPT:bloat 32000' });
|
||||
assert.equal(out.filter(f => f.type === 'error').length, 0);
|
||||
assert.ok(out.find(f => f.type === 'done'));
|
||||
assert.equal(out.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.context);
|
||||
assert.match(words(out), /ran out of room/);
|
||||
await new Promise(res => setTimeout(res, 1500));
|
||||
const compacted = r.logs.find(l => /compact after a stopped turn/.test(l));
|
||||
assert.match(compacted ?? '', /compact after a stopped turn: \w+/, `compaction was asked for and the Harness answered (${compacted})`);
|
||||
const out2 = [];
|
||||
await r.bridge.runTurn({ ...r.base('f2', f => out2.push(f)), message: 'SCRIPT:bloat 3000' });
|
||||
assert.equal(out2.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.empty, 'no words at all, plenty of room: still a message');
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Connect an app: Anthropic-style apps get the server root (they add /v1/messages themselves), OpenAI-style apps keep /v1,
|
||||
// and the host accepts /v1/v1/messages as the same request for people who pasted the old address.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import http from 'node:http';
|
||||
import { build } from 'esbuild';
|
||||
import { apiPath } from '../server/api-paths.mjs';
|
||||
import { createLocalShare } from '../server/local-share.mjs';
|
||||
|
||||
const bundled = await build({ entryPoints: ['src/lib/connect-urls.ts'], bundle: true, write: false, format: 'esm', platform: 'node' });
|
||||
const { serverRoot, appBaseUrl } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
test('the Anthropic tab shows the address without /v1, the other tabs keep it', () => {
|
||||
const base = 'http://127.0.0.1:8792/v1';
|
||||
assert.equal(appBaseUrl(base, 'anthropic'), 'http://127.0.0.1:8792');
|
||||
assert.equal(appBaseUrl(base, 'openai'), base);
|
||||
assert.equal(appBaseUrl(base, 'responses'), base);
|
||||
assert.equal(serverRoot('https://abc.trycloudflare.com/v1/'), 'https://abc.trycloudflare.com');
|
||||
assert.equal(serverRoot('http://192.168.1.5:8792'), 'http://192.168.1.5:8792');
|
||||
assert.equal(serverRoot('http://host/api/v1'), 'http://host/api');
|
||||
});
|
||||
|
||||
test('the Connect dialog gives the Anthropic tab the root address and says why in plain words', async () => {
|
||||
const screen = await readFile('src/screens/Serving.tsx', 'utf8');
|
||||
assert.match(screen, /appBaseUrl\(serving\.baseUrl, protocol\)/);
|
||||
assert.match(screen, /ANTHROPIC_BASE_URL/);
|
||||
});
|
||||
|
||||
test('/v1/v1/messages is read as /v1/messages, and nothing else is aliased', () => {
|
||||
assert.equal(apiPath('/v1/v1/messages'), '/v1/messages');
|
||||
assert.equal(apiPath('/v1/v1/messages/'), '/v1/messages');
|
||||
assert.equal(apiPath('/v1/v1/messages/count_tokens'), '/v1/messages/count_tokens');
|
||||
assert.equal(apiPath('/v1/messages'), '/v1/messages');
|
||||
for (const other of ['/v1/v1/chat/completions', '/v1/v1/models', '/v1/v1/responses', '/v1/v1/v1/messages']) assert.equal(apiPath(other), other);
|
||||
});
|
||||
|
||||
test('the shared (key-protected) listener serves /v1/v1/messages as /v1/messages', async () => {
|
||||
const seen = [];
|
||||
const share = createLocalShare({ handle: async (req, res, path) => { seen.push(path); res.writeHead(200); res.end('ok'); }, hasKey: () => true, host: '127.0.0.1', port: 0 });
|
||||
const { url } = await share.start();
|
||||
try {
|
||||
const root = url.replace(/\/v1$/, '');
|
||||
for (const path of ['/v1/messages', '/v1/v1/messages']) {
|
||||
const res = await fetch(root + path, { method: 'POST', body: '{}' });
|
||||
assert.equal(res.status, 200, path);
|
||||
}
|
||||
assert.deepEqual(seen, ['/v1/messages', '/v1/messages']);
|
||||
assert.equal((await fetch(root + '/v1/v1/chat/completions', { method: 'POST', body: '{}' })).status, 404);
|
||||
} finally { await share.stop(); }
|
||||
});
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<!doctype html><html><head><title>strata local llm engine - Search</title></head><body><ol id="b_results">
|
||||
<li class="b_algo" data-id iid=SERP.5344><div class="b_tpcn"><a class="tilk" aria-label="github.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=742e070f460f31c63a7850b7e2884cb8ee651cb333f2ce0f6a64719eb0a6a8a4JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YQ&ntb=1" h="ID=SERP,5129.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">github.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://github.com › Strata</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=742e070f460f31c63a7850b7e2884cb8ee651cb333f2ce0f6a64719eb0a6a8a4JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YQ&ntb=1" h="ID=SERP,5129.2">GitHub - Niko1221/<strong>Strata</strong>: Qwen3.8-Flash-Next on any consumer …</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid=""><span class="news_dt">Sep 24, 2026</span> · Strata makes the model fit by sharing the work across your whole PC. Think of a kitchen: the things you use all the …</p></div><div elementtiming=frp.MiddleOfPage aria-hidden="true" style="pointer-events:none;margin-top:-1px;height:1px;width:1px;font-size:1px;position:absolute;top:0;right:0;" tabindex="-1"> </div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5345><div class="b_tpcn"><a class="tilk" aria-label="github.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=83a355ead65461d915b3a98842374b9104c98dfcc6a84d37dced83063413be2dJmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YS9yZWxlYXNlcw&ntb=1" h="ID=SERP,5147.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=91&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">github.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://github.com › Strata › releases</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=83a355ead65461d915b3a98842374b9104c98dfcc6a84d37dced83063413be2dJmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9naXRodWIuY29tL05pa28xMjIxL1N0cmF0YS9yZWxlYXNlcw&ntb=1" h="ID=SERP,5147.2">Releases · Niko1221/<strong>Strata</strong> - GitHub</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid=""><span class="news_dt">Sep 29, 2026</span> · CUDA only, a build option: -DSTRATA_MMQ_TAB=ON with STRATA_MMQ_DIRECT=1 and …</p></div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5346><div class="b_tpcn"><a class="tilk" aria-label="strataspa.net" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=ec423c99a1c500049b15008a1c77da5392295e31d9001a6d0ce9ae573da58e90JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9zdHJhdGFzcGEubmV0Lw&ntb=1" h="ID=SERP,5164.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">strataspa.net</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://strataspa.net</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=ec423c99a1c500049b15008a1c77da5392295e31d9001a6d0ce9ae573da58e90JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9zdHJhdGFzcGEubmV0Lw&ntb=1" h="ID=SERP,5164.2"><strong>Strata</strong> SpA</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid="">STRATA è una società di consulenza professionale specializzata nei servizi di supporto giuridico-amministrativo e nella gestione di …</p></div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5347><div class="b_tpcn"><a class="tilk" aria-label="strata.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=1dc980cbad2cc71b1b9b3988e8f4602008bc6a4d968de8149c77db25289dcba0JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly93d3cuc3RyYXRhLmNvbS8&ntb=1" h="ID=SERP,5180.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=93&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">strata.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://www.strata.com</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=1dc980cbad2cc71b1b9b3988e8f4602008bc6a4d968de8149c77db25289dcba0JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly93d3cuc3RyYXRhLmNvbS8&ntb=1" h="ID=SERP,5180.2"><strong>Strata</strong> —3D Modeling Software</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid="">Strata is a 3D/VR/AR Developer and Studio that creates powerful 3D modeling software and solutions. Start a free trial and bring …</p></div></li>
|
||||
<li class="b_algo" data-id iid=SERP.5348><div class="b_tpcn"><a class="tilk" aria-label="stratanetwork.com" RedirectUrl="" tabindex="-1" target="_blank" href="https://www.bing.com/ck/a?!&&p=d3ffcc77c74e73bdb811924b6eda6f244b5876d150d8b08dc90500765cc5a782JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9sb2dpbi5zdHJhdGFuZXR3b3JrLmNvbS9Mb2dpbg&ntb=1" h="ID=SERP,5194.1"><div class="tpic"><div class="wr_fav" data-priority="2"><div class="cico siteicon" style="width:32px;height:32px;"><div class="rms_iac" style="height:32px;line-height:32px;width:32px;" data-height="32" data-width="32" data-alt="Global web icon" data-class="rms_img" data-src="https://th.bing.com/th/id/ODLS.A2450BEC-5595-40BA-9F13-D9EC6AB74B9F?w=32&h=32&qlt=94&pcl=fffffa&o=6&pid=1.2"></div></div></div></div><div class="tptxt"><div class="tptt">stratanetwork.com</div><div class="tpmeta"><div class="b_attribution" tabindex="-1"><cite>https://login.stratanetwork.com › Login</cite></div></div></div></a></div><h2><a target="_blank" href="https://www.bing.com/ck/a?!&&p=d3ffcc77c74e73bdb811924b6eda6f244b5876d150d8b08dc90500765cc5a782JmltdHM9MTc5MjI4MTYwMA&ptn=3&ver=2&hsh=4&fclid=0df69d14-8c8b-65ee-062f-8ae28d666410&u=a1aHR0cHM6Ly9sb2dpbi5zdHJhdGFuZXR3b3JrLmNvbS9Mb2dpbg&ntb=1" h="ID=SERP,5194.2"><strong>Strata</strong> Login</a></h2><div class="b_caption"><p class="b_lineclamp2" data-rslinkclamp-iid="">Strata Login ... Strata Login</p></div></li>
|
||||
</ol></body></html>
|
||||
@@ -27,6 +27,8 @@
|
||||
* SCRIPT:planreply a reply ending with a numbered plan of three steps (each step's text carries SCRIPT:goalstep)
|
||||
* SCRIPT:call <tool> <json> one call to any tool with the given JSON arguments
|
||||
* SCRIPT:multi <json> {"calls":[[tool,args],...],"say":"final text"}: all the calls in one reply, then the text once their results are in
|
||||
* SCRIPT:searchloop a model that never stops: every reply rewrites a numbered plan and calls web_search again with a new query
|
||||
* SCRIPT:bloat <prompt tokens> a reply that is only thinking (no answer text), with usage reporting that many prompt tokens (a context at 100%)
|
||||
*
|
||||
* A request whose last message is a tool result is answered with a text that quotes the result.
|
||||
*/
|
||||
@@ -78,9 +80,10 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
||||
const id = `chatcmpl-${requests.length}`;
|
||||
const send = (delta, finish = null, extra = {}) => res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);
|
||||
let promptTokens = 100 + messages.length;
|
||||
const finish = (reason, tokens = 10) => {
|
||||
send({}, reason);
|
||||
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: 100 + messages.length, completion_tokens: tokens, total_tokens: 100 + messages.length + tokens } })}\n\n`);
|
||||
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: promptTokens, completion_tokens: tokens, total_tokens: promptTokens + tokens } })}\n\n`);
|
||||
res.write('data: [DONE]\n\n'); res.end();
|
||||
};
|
||||
const toolCall = async (name, call) => {
|
||||
@@ -116,6 +119,26 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =
|
||||
if (/biggest lever/.test(t) && !answered && last.role !== 'tool') return say(['{"step": 2, "why": "The layout decided in step 1 shapes everything after it."}']);
|
||||
if (/IMPROVEMENT PLAN/.test(t) && !answered && last.role !== 'tool') return say(['## Better path\n\n', '1. Improve the first attempt SCRIPT:goalstep\n', '2. Polish and check SCRIPT:goalstep\n']);
|
||||
}
|
||||
if (directive?.[1] === 'searchloop') {
|
||||
const n = requests.filter(r => r.directive === 'searchloop').length;
|
||||
send({ role: 'assistant', content: `Plan, version ${n}:
|
||||
|
||||
## Search plan
|
||||
|
||||
1. Search for the topic
|
||||
2. Read the best result
|
||||
3. Write the summary
|
||||
|
||||
` });
|
||||
const argsJson = JSON.stringify({ queries: [`topic search number ${n}`] });
|
||||
send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'web_search', arguments: argsJson } }] });
|
||||
return finish('tool_calls', 60);
|
||||
}
|
||||
if (directive?.[1] === 'bloat') {
|
||||
promptTokens = parseInt((directive[2] ?? '').trim(), 10) || 100;
|
||||
send({ role: 'assistant', content: '', reasoning_content: 'Thinking about it for a long time and never getting to the answer.' });
|
||||
return finish('stop', 20);
|
||||
}
|
||||
if (directive?.[1] === 'goalstep') {
|
||||
// A goal round: read the goal, mark it complete, then say so.
|
||||
if (!toolMessages.length) return toolCall('get_goal', {});
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
// /loop stops by itself: a count or a time said in words is read when the loop is created and enforced by the scheduler, and an
|
||||
// answer that says "done" / "stopped" ends it. The model is never left to keep replying "stopped" every minute.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { build } from 'esbuild';
|
||||
|
||||
const bundled = await build({ stdin: { contents: "export * from './src/lib/loop'; export * from './src/lib/loop-runner';", resolveDir: process.cwd(), loader: 'ts' }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
|
||||
const { parseLoop, readLimits, replySaysDone, judgeAnswer, withStopRule, LoopScheduler, LOOP_MAX_FAILURES, LOOP_MAX_RUNS } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`);
|
||||
|
||||
const start = text => { const c = parseLoop(text); assert.equal(c?.kind, 'start', text); return c; };
|
||||
|
||||
test('a count in words or digits is read when the loop is created, and left out of the message', () => {
|
||||
for (const [line, runs, prompt] of [
|
||||
['/loop 1m say hi, stop after 3 answers', 3, 'say hi'],
|
||||
['/loop 1m say hi and stop after three replies', 3, 'say hi'],
|
||||
['/loop 5m say hi. Stop the loop after 2 runs.', 2, 'say hi'],
|
||||
['/loop 5m check the build, only 4 times', 4, 'check the build'],
|
||||
['/loop 5m ping 3 times', 3, 'ping'],
|
||||
['/loop every 2 minutes say hi for 5 answers', 5, 'say hi'],
|
||||
['/loop 1m report the time, up to 6 times', 6, 'report the time'],
|
||||
['/loop 1m say hi then stop after 1 answer', 1, 'say hi'],
|
||||
['/loop 1m say hi, end after the 3rd run', 3, 'say hi'],
|
||||
]) {
|
||||
const c = start(line);
|
||||
assert.equal(c.maxRuns, runs, line);
|
||||
assert.equal(c.prompt, prompt, line);
|
||||
}
|
||||
});
|
||||
|
||||
test('a time limit and a stop condition in words are read too', () => {
|
||||
let c = start('/loop 10m check the build for the next 2 hours');
|
||||
assert.equal(c.maxMs, 2 * 3_600_000); assert.equal(c.prompt, 'check the build');
|
||||
c = start('/loop 5m check the build, stop after 30 minutes');
|
||||
assert.equal(c.maxMs, 30 * 60_000); assert.equal(c.prompt, 'check the build');
|
||||
c = start('/loop 2m check the build, stop when it passes');
|
||||
assert.equal(c.stopWhen, 'it passes'); assert.equal(c.prompt, 'check the build'); assert.equal(c.maxRuns, undefined);
|
||||
c = start('/loop 2m look for the file until it exists');
|
||||
assert.equal(c.stopWhen, 'it exists'); assert.equal(c.prompt, 'look for the file');
|
||||
});
|
||||
|
||||
test('an ordinary message is not mistaken for a limit, and a limit with nothing to do is explained', () => {
|
||||
for (const line of ['/loop 10m summarise my inbox notes', '/loop 5m say hi', '/loop 10m check whether the build passes', '/loop 5m run the tests faster than last time']) {
|
||||
const c = start(line);
|
||||
assert.equal(c.maxRuns, undefined, line); assert.equal(c.maxMs, undefined, line); assert.equal(c.stopWhen, undefined, line);
|
||||
assert.equal(c.prompt, line.replace(/^\/loop \S+ /, ''));
|
||||
}
|
||||
assert.equal(parseLoop('/loop 5m stop after 3 answers').kind, 'help');
|
||||
assert.match(parseLoop('/loop 5m stop after 3 answers').problem, /what to do/);
|
||||
assert.equal(readLimits('say hi').prompt, 'say hi');
|
||||
assert.equal(start('/loop 5m say hi, stop after 500 answers').maxRuns, LOOP_MAX_RUNS, 'the count is capped like the loop');
|
||||
});
|
||||
|
||||
test('a reply that says done or stopped ends the loop, a normal reply does not', () => {
|
||||
for (const reply of ['stopped', 'Stopped.', 'Done', 'DONE the build passes', 'LOOP DONE', 'The loop is stopped.']) assert.equal(replySaysDone(reply, true), true, reply);
|
||||
for (const reply of ['stopped', 'Done.', 'DONE: it passes', 'LOOP STOPPED']) assert.equal(replySaysDone(reply, false), true, reply + ' (nothing stated)');
|
||||
for (const reply of ['The build is done and the tests pass: 41 of 41.', 'Hi! Nice to see you.', 'I checked the folder and found nothing new.', '']) assert.equal(replySaysDone(reply, true), false, reply);
|
||||
// Without a stated limit only the bare words count: "Done. The deploy finished" could be a normal answer.
|
||||
assert.equal(replySaysDone('Done. The build passes.', false), false);
|
||||
assert.equal(replySaysDone('Done. The build passes.', true), true);
|
||||
assert.match(withStopRule('check the build', 'it passes'), /begin your reply with the word DONE/);
|
||||
assert.equal(withStopRule('check the build'), 'check the build');
|
||||
});
|
||||
|
||||
test('judgeAnswer: count, time, failures and the said-done rule, in that situation order', () => {
|
||||
const p = (answers, failures = 0, startedAt = 0) => ({ answers, failures, startedAt });
|
||||
assert.equal(judgeAnswer({ maxRuns: 3 }, p(2), { text: 'hi', failed: false }, 0), null);
|
||||
assert.equal(judgeAnswer({ maxRuns: 3 }, p(3), { text: 'hi', failed: false }, 0), 'count');
|
||||
assert.equal(judgeAnswer({ maxMs: 1000 }, p(1), { text: 'hi', failed: false }, 999), null);
|
||||
assert.equal(judgeAnswer({ maxMs: 1000 }, p(1), { text: 'hi', failed: false }, 1000), 'time');
|
||||
assert.equal(judgeAnswer({}, p(1, LOOP_MAX_FAILURES - 1), { text: '', failed: true }, 0), null);
|
||||
assert.equal(judgeAnswer({}, p(1, LOOP_MAX_FAILURES), { text: '', failed: true }, 0), 'failures');
|
||||
assert.equal(judgeAnswer({}, p(1), { text: 'stopped', failed: false }, 0), 'said-done');
|
||||
assert.equal(judgeAnswer({}, p(LOOP_MAX_RUNS), { text: 'hi', failed: false }, 0), 'cap');
|
||||
});
|
||||
|
||||
/** A scheduler on a fake clock with a scripted model. `reply(n, prompt)` is the model's n-th answer. */
|
||||
function harness(reply, { ready = () => true } = {}) {
|
||||
const sent = []; const notes = []; const timers = new Map(); let t = 0, nextTimer = 1;
|
||||
const host = {
|
||||
async send(_id, message) {
|
||||
sent.push(message);
|
||||
const r = await reply(sent.length, message.text);
|
||||
return r === null ? { answered: false, text: '', failed: false } : typeof r === 'string' ? { answered: true, text: r, failed: false } : { answered: true, ...r };
|
||||
},
|
||||
note: (_id, text) => notes.push(text),
|
||||
exists: () => true,
|
||||
ready,
|
||||
now: () => t,
|
||||
setTimer: (fn, ms) => { const id = nextTimer++; timers.set(id, { fn, at: t + ms }); return id; },
|
||||
clearTimer: id => timers.delete(id),
|
||||
};
|
||||
const scheduler = new LoopScheduler(host);
|
||||
/** Move the clock to the next timer and run it; false when nothing is waiting. */
|
||||
const advance = async () => {
|
||||
const next = [...timers.entries()].sort((a, b) => a[1].at - b[1].at)[0];
|
||||
if (!next) return false;
|
||||
timers.delete(next[0]); t = Math.max(t, next[1].at); next[1].fn();
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||
await new Promise(r => setImmediate(r));
|
||||
return true;
|
||||
};
|
||||
const drain = async (max = 400) => { let n = 0; while (n < max && await advance()) n++; return n; };
|
||||
return { scheduler, sent, notes, timers, advance, drain, clock: () => t };
|
||||
}
|
||||
|
||||
test('"stop after 3 answers" stops the scheduler after the third answer and nothing is sent again', async () => {
|
||||
const h = harness(() => 'Hello!');
|
||||
const c = start('/loop 1m say hi, stop after 3 answers');
|
||||
await h.scheduler.start('chat', c);
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 3);
|
||||
assert.equal(h.sent[0].text, 'say hi', 'the model is not told about the stop rule');
|
||||
assert.equal(h.timers.size, 0, 'no timer is left');
|
||||
assert.equal(h.scheduler.isRunning('chat'), false);
|
||||
assert.match(h.notes.at(-1), /The loop is done: it ran 3 times/);
|
||||
assert.equal(h.notes.filter(n => /stops by itself after 3 answers/.test(n)).length, 1, 'the start note says how it ends');
|
||||
});
|
||||
|
||||
test('the owner case: a model that answers "stopped" every minute is cut off at once', async () => {
|
||||
// With a count in the line the scheduler stops at 3 by itself, and a "stopped" answer before that also ends it.
|
||||
const h = harness(n => (n < 2 ? 'Hi!' : 'stopped'));
|
||||
await h.scheduler.start('chat', start('/loop 1m say hi, stop after 3 answers'));
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 2, 'the "stopped" answer ended the loop');
|
||||
assert.match(h.notes.at(-1), /last answer said the work is done/);
|
||||
// No limit in the line at all: a bare "Stopped." still ends it, instead of 100 minutes of "stopped".
|
||||
const g = harness(n => (n < 3 ? 'Still going.' : 'Stopped.'));
|
||||
await g.scheduler.start('chat', start('/loop 1m keep an eye on the queue'));
|
||||
await g.drain();
|
||||
assert.equal(g.sent.length, 3); assert.equal(g.timers.size, 0);
|
||||
});
|
||||
|
||||
test('a stop condition in words: the model is told how to say it is met, and its DONE ends the loop', async () => {
|
||||
const h = harness(n => (n < 4 ? 'Not yet: 2 tests fail.' : 'DONE all tests pass.'));
|
||||
await h.scheduler.start('chat', start('/loop 2m run the tests, stop when they all pass'));
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 4);
|
||||
assert.match(h.sent[0].text, /begin your reply with the word DONE/);
|
||||
assert.equal(h.sent[0].shown, 'run the tests', 'the chat shows the message without the rule');
|
||||
});
|
||||
|
||||
test('a time limit ends the loop by the clock, between answers', async () => {
|
||||
const h = harness(() => 'ok');
|
||||
await h.scheduler.start('chat', start('/loop 10m check the queue for the next 35 minutes'));
|
||||
await h.drain();
|
||||
// answers at 0, 10, 20, 30 minutes; the timer at 40 finds the 35 minutes over
|
||||
assert.equal(h.sent.length, 4);
|
||||
assert.match(h.notes.at(-1), /time you set is up/);
|
||||
assert.equal(h.timers.size, 0);
|
||||
});
|
||||
|
||||
test('a busy chat waits, and does not use up the count', async () => {
|
||||
let busy = true;
|
||||
const h = harness(() => 'ok', { ready: () => !busy });
|
||||
await h.scheduler.start('chat', start('/loop 1m ping, stop after 2 answers'));
|
||||
assert.equal(h.sent.length, 1);
|
||||
await h.advance(); // 1 minute: busy, retried in 15 s
|
||||
await h.advance(); await h.advance();
|
||||
assert.equal(h.sent.length, 1, 'nothing is sent while the chat is busy');
|
||||
busy = false;
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 2);
|
||||
assert.equal(h.scheduler.isRunning('chat'), false);
|
||||
});
|
||||
|
||||
test('three failed answers in a row end the loop, one failure does not', async () => {
|
||||
const h = harness(n => (n === 2 ? { text: '', failed: true } : 'ok'));
|
||||
await h.scheduler.start('chat', start('/loop 1m check something, stop after 4 answers'));
|
||||
await h.drain();
|
||||
assert.equal(h.sent.length, 5, 'the failed run is not an answer, so 4 good answers took 5 sends');
|
||||
const bad = harness(() => ({ text: '', failed: true }));
|
||||
await bad.scheduler.start('chat', start('/loop 1m check something'));
|
||||
await bad.drain();
|
||||
assert.equal(bad.sent.length, LOOP_MAX_FAILURES);
|
||||
assert.match(bad.notes.at(-1), /did not work/);
|
||||
});
|
||||
|
||||
test('/loop stop while an answer is coming means nothing more is sent', async () => {
|
||||
let release;
|
||||
const h = harness(() => new Promise(resolve => { release = () => resolve('ok'); }));
|
||||
const started = h.scheduler.start('chat', start('/loop 1m ping'));
|
||||
await Promise.resolve();
|
||||
assert.equal(h.scheduler.stop('chat'), true);
|
||||
release(); await started;
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.equal(h.scheduler.isRunning('chat'), false);
|
||||
assert.equal(await h.advance(), false);
|
||||
assert.equal(h.sent.length, 1);
|
||||
});
|
||||
|
||||
test('a second /loop in the same chat is refused with one plain sentence; a loop with no limit still runs on', async () => {
|
||||
const h = harness(() => 'ok');
|
||||
await h.scheduler.start('chat', start('/loop 1m ping'));
|
||||
assert.equal(await h.scheduler.start('chat', start('/loop 1m other')), false);
|
||||
assert.match(h.notes.at(-1), /already has a loop/);
|
||||
for (let i = 0; i < 5; i++) await h.advance();
|
||||
assert.equal(h.sent.length, 6, 'no limit: it keeps going until the person stops it');
|
||||
assert.equal(h.scheduler.stop('chat'), true);
|
||||
});
|
||||
@@ -25,6 +25,8 @@ test('HTTP gateway lists all models, routes both protocols exactly, and isolates
|
||||
const list=(await call('/v1/models')).body.data;assert.equal(list.length,2);assert.deepEqual(new Set(list.map(i=>i.id)),new Set([a.body.instance.apiModelId,b.body.instance.apiModelId]));
|
||||
assert.equal((await call('/v1/chat/completions',{model:'missing',messages:[{role:'user',content:'hello'}]})).status,409);
|
||||
assert.equal((await call('/v1/messages',{messages:[{role:'user',content:'hello'}]})).status,409);
|
||||
assert.equal((await call('/v1/v1/messages',{messages:[{role:'user',content:'hello'}]})).status,409,'an Anthropic client given the /v1 base reaches the same route');
|
||||
assert.notEqual((await call('/v1/v1/chat/completions',{model:'missing',messages:[{role:'user',content:'hello'}]})).status,409,'only the messages path is aliased');
|
||||
const controllers=[new AbortController(),new AbortController()];
|
||||
const responseA=await fetch(base+'/v1/chat/completions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({stream:true,model:a.body.instance.apiModelId,messages:[{role:'user',content:'hello'}]}),signal:controllers[0].signal});
|
||||
const responseB=await fetch(base+'/v1/messages',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({stream:true,model:b.body.instance.apiModelId,messages:[{role:'user',content:'hello'}]}),signal:controllers[1].signal});
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Files dropped on the app window on Linux and macOS: the shell hands the paths to the host, the page fetches each file once.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, mkdir, rm, writeFile, readFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { transform } from 'esbuild';
|
||||
import { createNativeDrops, typeOfName, MAX_FILES } from '../server/native-drop.mjs';
|
||||
|
||||
const root = resolve(import.meta.dirname, '..');
|
||||
async function loadTs(path) {
|
||||
const { code } = await transform(await readFile(new URL(path, import.meta.url), 'utf8'), { loader: 'ts', format: 'esm' });
|
||||
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
|
||||
}
|
||||
const { readDroppedRefs, fetchDropped, dragHasFiles } = await loadTs('../src/lib/native-drop.ts');
|
||||
|
||||
test('the host keeps only regular files it can read, each for one fetch, for a short time', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'strata-drop-'));
|
||||
try {
|
||||
await writeFile(join(dir, 'a.PNG'), Buffer.from([1, 2, 3])); await writeFile(join(dir, 'notes.md'), '# hi'); await writeFile(join(dir, 'thing.bin'), 'x');
|
||||
await mkdir(join(dir, 'folder'));
|
||||
let clock = 1000;
|
||||
const drops = createNativeDrops({ now: () => clock });
|
||||
const got = await drops.add([join(dir, 'a.PNG'), join(dir, 'folder'), join(dir, 'missing.txt'), 'relative/path.txt', 42, join(dir, 'notes.md'), join(dir, 'thing.bin')]);
|
||||
assert.deepEqual(got.map(f => [f.name, f.type, f.size]), [['a.PNG', 'image/png', 3], ['notes.md', 'text/markdown', 4], ['thing.bin', 'application/octet-stream', 1]]);
|
||||
assert.match(got[0].id, /^[0-9a-f-]{36}$/);
|
||||
assert.deepEqual([...drops.take(got[0].id).bytes], [1, 2, 3]);
|
||||
assert.equal(drops.take(got[0].id), null, 'one fetch per file');
|
||||
clock += 3 * 60_000;
|
||||
assert.equal(drops.take(got[1].id), null, 'gone after a couple of minutes');
|
||||
assert.deepEqual(await drops.add('not a list'), []);
|
||||
const many = await drops.add(Array.from({ length: 30 }, () => join(dir, 'notes.md')));
|
||||
assert.equal(many.length, MAX_FILES);
|
||||
const big = createNativeDrops({ info: async () => ({ isFile: () => true, size: 26 * 1024 * 1024 }) });
|
||||
assert.deepEqual(await big.add([join(dir, 'notes.md')]), [], 'a file over 25 MB is left out');
|
||||
assert.equal(typeOfName('x.JPG'), 'image/jpeg');
|
||||
} finally { await rm(dir, { recursive: true, force: true, maxRetries: 3 }); }
|
||||
});
|
||||
|
||||
test('only the app shell can hand files over; the page fetches each file once', { timeout: 60000 }, async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), 'strata-drop-host-'));
|
||||
const socket = createServer(); await new Promise(r => socket.listen(0, '127.0.0.1', r));
|
||||
const port = socket.address().port; await new Promise(r => socket.close(r));
|
||||
const secret = 'a'.repeat(40);
|
||||
const child = spawn(process.execPath, ['server/index.mjs'], { cwd: root, env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port), STRATA_REAL_ENGINE: '0', STRATA_WORKSPACE: join(home, 'work'), STRATA_SHUTDOWN_TOKEN: secret }, stdio: 'ignore', windowsHide: true });
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
try {
|
||||
for (let i = 0; i < 100; i++) { try { if ((await fetch(base + '/api/skills')).ok) break; } catch { /* not up */ } await new Promise(r => setTimeout(r, 100)); }
|
||||
const picture = join(home, 'qa.png'); await writeFile(picture, Buffer.from([137, 80, 78, 71]));
|
||||
const post = (headers) => fetch(base + '/api/app/drop', { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ paths: [picture] }) });
|
||||
assert.equal((await post({})).status, 403, 'a page cannot hand over paths');
|
||||
assert.equal((await post({ 'x-strata-shutdown': 'b'.repeat(40) })).status, 403);
|
||||
const ok = await post({ 'x-strata-shutdown': secret });
|
||||
assert.equal(ok.status, 200);
|
||||
const [file] = (await ok.json()).files;
|
||||
assert.deepEqual([file.name, file.type, file.size], ['qa.png', 'image/png', 4]);
|
||||
const first = await fetch(`${base}/api/app/drop/${file.id}`);
|
||||
assert.equal(first.status, 200); assert.equal(first.headers.get('content-type'), 'image/png');
|
||||
assert.deepEqual([...new Uint8Array(await first.arrayBuffer())], [137, 80, 78, 71]);
|
||||
assert.equal((await fetch(`${base}/api/app/drop/${file.id}`)).status, 404, 'once');
|
||||
assert.equal((await fetch(`${base}/api/app/drop/not-an-id`)).status, 404);
|
||||
} finally { child.kill(); await new Promise(r => setTimeout(r, 300)); await rm(home, { recursive: true, force: true, maxRetries: 3 }).catch(() => {}); }
|
||||
});
|
||||
|
||||
test('the page reads what the shell announced and makes Files of it', async () => {
|
||||
const id = '123e4567-e89b-12d3-a456-426614174000';
|
||||
assert.deepEqual(readDroppedRefs([{ id, name: 'a.png', type: 'image/png', size: 3 }, { id: 'bad', name: 'x' }, { id, name: '' }, null, 7]), [{ id, name: 'a.png', type: 'image/png' }]);
|
||||
assert.deepEqual(readDroppedRefs('nope'), []);
|
||||
const files = await fetchDropped([{ id, name: 'a.png', type: 'image/png' }, { id: id.replace('0', '1'), name: 'gone.png', type: 'image/png' }],
|
||||
async url => url.endsWith(id) ? { ok: true, blob: async () => new Blob([new Uint8Array([1, 2])]) } : { ok: false, blob: async () => new Blob([]) });
|
||||
assert.deepEqual(files.map(f => [f.name, f.type, f.size]), [['a.png', 'image/png', 2]]);
|
||||
assert.equal(dragHasFiles(['text/uri-list', 'text/html']), true); assert.equal(dragHasFiles(['Files']), true); assert.equal(dragHasFiles(['text/plain']), false); assert.equal(dragHasFiles(null), false);
|
||||
});
|
||||
|
||||
test('the window passes the drop on (Linux and macOS) and ignores a file dropped outside the chat', async () => {
|
||||
const rust = await readFile(new URL('../../desktop/src-tauri/src/main.rs', import.meta.url), 'utf8');
|
||||
assert.match(rust, /#\[cfg\(windows\)\]\s+let builder = builder\.disable_drag_drop_handler\(\);/);
|
||||
assert.match(rust, /window\.on_webview_event\(/); assert.match(rust, /\/api\/app\/drop/);
|
||||
const zone = await readFile(new URL('../src/components/DropZone.tsx', import.meta.url), 'utf8');
|
||||
assert.match(zone, /NATIVE_DROP_EVENT/); assert.match(zone, /export function installDropGuard/);
|
||||
assert.match(await readFile(new URL('../src/main.tsx', import.meta.url), 'utf8'), /installDropGuard\(\);/);
|
||||
});
|
||||
@@ -68,7 +68,7 @@ test('O02: the screenshot Download button saves the picture and then says so', a
|
||||
|
||||
test('item 1: the desktop window leaves file drops to the page, and the drop box is animated', async () => {
|
||||
const rust = await readFile(new URL('../../desktop/src-tauri/src/main.rs', import.meta.url), 'utf8');
|
||||
assert.match(rust, /\.min_inner_size\(900\.0, 600\.0\)\.disable_drag_drop_handler\(\);/);
|
||||
assert.match(rust, /#\[cfg\(windows\)\]\s+let builder = builder\.disable_drag_drop_handler\(\);/);
|
||||
const css = await readFile(new URL('../src/styles/app.css', import.meta.url), 'utf8');
|
||||
assert.match(css, /\.dropzone \{ animation: dropzone-in/);
|
||||
assert.match(css, /prefers-reduced-motion: reduce\) \{ \.dropzone/);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// The saved Monitor screenshot starts with the Strata logo alone (no "Monitor" headline); the live Monitor page keeps its title.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const read = path => readFile(new URL(path, import.meta.url), 'utf8').then(s => s.replace(/\r\n/g, '\n'));
|
||||
|
||||
test('the exported Monitor picture has the logo and no "Monitor" headline; the page itself keeps its title', async () => {
|
||||
const source = await read('../src/screens/Monitor.tsx');
|
||||
const header = /\{tr\(frozen \? <header className="section-toolbar">(.*?)<\/header> : null\)\}/s.exec(source)?.[1];
|
||||
assert.ok(header, 'the picture has its own header (it only exists while the picture is taken)');
|
||||
assert.match(header, /<Brand variant="lockup"/);
|
||||
assert.doesNotMatch(header, /<h1/);
|
||||
assert.doesNotMatch(header, /tr\("Monitor"\)/);
|
||||
assert.match(header, /frozen\.modelLabel/, 'the model and time line stays');
|
||||
assert.match(source, /<Screen width="wide" plainHeader title=\{tr\("Monitor"\)\}/, 'the live page still says Monitor');
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// The saved Monitor picture when a model is loaded (the normal case) starts with the Strata logo alone and the models/time line.
|
||||
// (QA follow-up: it was checked with a loaded model through the real page; the picture is the one of the Monitor screen, which shows the
|
||||
// loaded models. NativeMonitor.tsx is not used by any screen, so it needs no header.)
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
|
||||
const read = path => readFile(new URL(path, import.meta.url), 'utf8').then(s => s.replace(/\r\n/g, '\n'));
|
||||
|
||||
test('with a model loaded the picture is headed by the logo and the line "<model> · <time>"; with none, "N loaded models"', async () => {
|
||||
const source = await read('../src/screens/Monitor.tsx');
|
||||
assert.match(source, /const scopeLabel = selectedInstance \? instanceLabel\(selectedInstance\) : `\$\{runtime\?\.instances\.length \?\? 0\} loaded models`;/);
|
||||
const header = /\{tr\(frozen \? <header className="section-toolbar">(.*?)<\/header> : null\)\}/s.exec(source)?.[1];
|
||||
assert.ok(header);
|
||||
assert.match(header, /<Brand variant="lockup"/); assert.doesNotMatch(header, /<h1/);
|
||||
assert.match(header, /frozen\.modelLabel.*frozen\.time/s);
|
||||
assert.match(source, /setFrozen\(\{ data: structuredClone\(scoped \?\? live\), hardware: structuredClone\(inventory\), time: new Date\(\)\.toLocaleString\(localeTag\(\)\), modelLabel: scopeLabel \}\)/);
|
||||
});
|
||||
|
||||
test('no screen renders NativeMonitor, so the Monitor screen is the only picture source', async () => {
|
||||
const dirs = ['../src/screens/', '../src/app/', '../src/components/'];
|
||||
for (const dir of dirs) {
|
||||
for (const name of await readdir(new URL(dir, import.meta.url))) {
|
||||
if (!/\.tsx?$/.test(name) || name === 'NativeMonitor.tsx') continue;
|
||||
assert.doesNotMatch(await read(dir + name), /<NativeMonitor\b|from '\.\/NativeMonitor'|from '\.\.\/components\/NativeMonitor'/, `${dir}${name}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// Linux file drop (found on z440 under Xvfb with a real GTK drag, WebKitGTK 2.52): the page gets no files and WebKit never raises the drop signal,
|
||||
// so the shell reads the file:// addresses from the drag data, accepts the drag itself, takes the "leave" with every button up as the drop and
|
||||
// hands the paths to the host. The behaviour itself is checked on a real X display (scripts in phaseA-tests); these keep the pieces in place.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const read = path => readFile(new URL(path, import.meta.url), 'utf8').then(s => s.replace(/\r\n/g, '\n'));
|
||||
|
||||
test('the Linux shell hooks the drag signals of the page and keeps Windows and macOS on their own paths', async () => {
|
||||
const rust = await read('../../desktop/src-tauri/src/main.rs');
|
||||
assert.match(rust, /#\[cfg\(target_os = "linux"\)\]\s+hook_linux_drops\(&window, port, shell_token\);/);
|
||||
assert.match(rust, /view\.connect_drag_data_received\(/); assert.match(rust, /file_uri_to_path\(u\.as_str\(\)\)/);
|
||||
assert.match(rust, /ctx\.drag_status\(gtk::gdk::DragAction::COPY, time\)/);
|
||||
assert.match(rust, /pointer_buttons_up\(widget\)/);
|
||||
assert.match(rust, /hand_over_drop\(target\.clone\(\), port, token\.clone\(\), list\)/);
|
||||
assert.match(rust, /fn file_uri_to_path\(uri: &str\) -> Option<String>/);
|
||||
assert.match(rust, /#\[cfg\(windows\)\]\s+let builder = builder\.disable_drag_drop_handler\(\);/);
|
||||
const toml = await read('../../desktop/src-tauri/Cargo.toml');
|
||||
assert.match(toml, /\[target\.'cfg\(target_os = "linux"\)'\.dependencies\]\ngtk = "0\.18"\nwebkit2gtk = "2\.0"/);
|
||||
});
|
||||
|
||||
test('only file:// addresses reach the host, which applies the same limits as for every drop', async () => {
|
||||
const rust = await read('../../desktop/src-tauri/src/main.rs');
|
||||
assert.match(rust, /strip_prefix\("file:\/\/"\)\?/);
|
||||
const host = await read('../server/native-drop.mjs');
|
||||
assert.match(host, /MAX_FILES = 10, MAX_BYTES = 25 \* 1024 \* 1024/);
|
||||
assert.match(host, /!isAbsolute\(path\)/);
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
// The agent's keyless web search against a MOCKED, rate-limited DuckDuckGo: spaced requests, a session cache, a cooldown that doubles,
|
||||
// Bing as the second source, and one plain sentence (with the place to add a key) when every source refuses.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createDuckDuckGoSearch, BLOCKED_MESSAGE, LIMITED_SENTENCE, UNREACHABLE_MESSAGE } from '../server/web-search-ddg.mjs';
|
||||
import { bingTarget, parseBingResults, bingLooksBlocked } from '../server/web-search-bing.mjs';
|
||||
|
||||
const BING = readFileSync(new URL('./fixtures/bing-results.html', import.meta.url), 'utf8');
|
||||
const DDG = `<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fddg.example%2Fa">DDG one</a></h2>
|
||||
<a class="result__snippet" href="x">First snippet</a></div>
|
||||
<div class="result"><h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fddg.example%2Fb">DDG two</a></h2></div>`;
|
||||
const ANOMALY = '<html><body><div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too.</div></body></html>';
|
||||
|
||||
/** A fake clock whose sleep moves time, and a fake web: `script(url, n)` decides each answer. */
|
||||
function world(script, { random = () => 0.5 } = {}) {
|
||||
let t = 5_000_000;
|
||||
const calls = [];
|
||||
const fetch = async (url, init) => {
|
||||
const at = t;
|
||||
const call = { url: String(url), method: init?.method ?? 'GET', at, headers: init?.headers ?? {} };
|
||||
calls.push(call);
|
||||
const out = await script(call, calls.length);
|
||||
if (out instanceof Error) throw out;
|
||||
return out;
|
||||
};
|
||||
const search = createDuckDuckGoSearch({ fetch, now: () => t, sleep: async ms => { t += ms; }, random });
|
||||
return { search, calls, advance: ms => { t += ms; }, clock: () => t, hostCalls: host => calls.filter(c => c.url.includes(host)) };
|
||||
}
|
||||
const page = (body, status = 200, headers = {}) => new Response(body, { status, headers });
|
||||
const duck = url => /duckduckgo\.com/.test(url);
|
||||
|
||||
test('requests to one source are spaced 2.5 s or more apart, never in a burst', async () => {
|
||||
const w = world(() => page(DDG));
|
||||
for (const q of ['one', 'two', 'three', 'four']) await w.search.search({ query: q });
|
||||
const at = w.calls.map(c => c.at);
|
||||
assert.equal(at.length, 4);
|
||||
for (let i = 1; i < at.length; i++) assert.ok(at[i] - at[i - 1] >= 2500, `gap ${i}: ${at[i] - at[i - 1]} ms`);
|
||||
});
|
||||
|
||||
test('the request looks like the page\'s own form post: browser headers, Referer, Origin, no hidden tricks', async () => {
|
||||
const w = world(() => page(DDG));
|
||||
await w.search.search({ query: 'strata' });
|
||||
const [c] = w.calls;
|
||||
assert.equal(c.method, 'POST');
|
||||
assert.match(c.headers['user-agent'], /Mozilla\/5\.0 .*Chrome\/\d+/);
|
||||
assert.equal(c.headers.referer, 'https://html.duckduckgo.com/');
|
||||
assert.equal(c.headers.origin, 'https://html.duckduckgo.com');
|
||||
assert.equal(c.headers['sec-fetch-mode'], 'navigate');
|
||||
assert.match(c.headers['accept-language'], /en/);
|
||||
});
|
||||
|
||||
test('the same question is answered from the session cache, even while DuckDuckGo is refusing', async () => {
|
||||
let refuse = false;
|
||||
const w = world(call => (duck(call.url) ? (refuse ? page(ANOMALY, 202) : page(DDG)) : page(BING)));
|
||||
const a = await w.search.search({ query: 'Strata Engine' });
|
||||
assert.equal(a.sources.length, 2);
|
||||
refuse = true;
|
||||
const b = await w.search.search({ query: 'strata engine' });
|
||||
assert.deepEqual(b.sources, a.sources);
|
||||
assert.equal(w.calls.length, 1, 'no second request');
|
||||
w.advance(20 * 60_000);
|
||||
assert.equal((await w.search.search({ query: 'STRATA ENGINE' })).sources.length, 2, 'still cached after 20 minutes');
|
||||
assert.equal(w.calls.length, 1);
|
||||
w.advance(11 * 60_000);
|
||||
await w.search.search({ query: 'strata engine' });
|
||||
assert.ok(w.calls.length > 1, 'asked again after the cache is 30 minutes old');
|
||||
});
|
||||
|
||||
test('DuckDuckGo refuses (HTTP 202): Bing answers, DuckDuckGo is left alone for a minute, and its lite page is not tried', async () => {
|
||||
const w = world(call => (duck(call.url) ? page(ANOMALY, 202) : page(BING)));
|
||||
const first = await w.search.search({ query: 'node release notes', maxResults: 3 });
|
||||
assert.equal(first.sources.length, 3);
|
||||
assert.equal(first.sources[0].url, 'https://github.com/Niko1221/Strata');
|
||||
assert.equal(w.hostCalls('html.duckduckgo.com').length, 1);
|
||||
assert.equal(w.hostCalls('lite.duckduckgo.com').length, 0, 'a refusal is not followed by the lite page');
|
||||
assert.equal(w.hostCalls('bing.com').length, 1);
|
||||
// The next question goes straight to Bing: DuckDuckGo is cooling down.
|
||||
await w.search.search({ query: 'another question' });
|
||||
assert.equal(w.hostCalls('duckduckgo.com').length, 1, 'no request to DuckDuckGo during the cooldown');
|
||||
assert.equal(w.hostCalls('bing.com').length, 2);
|
||||
assert.ok(w.search.status().duckduckgo.blockedForMs > 0);
|
||||
// After the cooldown one probe goes out again.
|
||||
w.advance(61_000);
|
||||
await w.search.search({ query: 'a third question' });
|
||||
assert.equal(w.hostCalls('html.duckduckgo.com').length, 2);
|
||||
});
|
||||
|
||||
test('every source refuses: one plain sentence with the place to add a key; later searches make no request at all', async () => {
|
||||
const w = world(call => page(duck(call.url) ? ANOMALY : '<html>captcha</html>', duck(call.url) ? 202 : 429));
|
||||
const error = await w.search.search({ query: 'hello world' }).catch(e => e);
|
||||
assert.equal(error.code, 'WEB_RATE_LIMITED');
|
||||
assert.equal(error.message, BLOCKED_MESSAGE);
|
||||
assert.ok(error.message.startsWith(LIMITED_SENTENCE));
|
||||
assert.match(LIMITED_SENTENCE, /^Web search is limited right now\. Try again in a minute, or add a search key \(Exa, Perplexity or DeepSeek\) in Settings → Tools → Web search\.$/);
|
||||
assert.match(error.message, /Do not retry this search/, 'the model is told to stop');
|
||||
const used = w.calls.length;
|
||||
assert.equal(used, 2, 'one request per source, nothing more');
|
||||
for (const q of ['again', 'and again', 'once more']) {
|
||||
const e = await w.search.search({ query: q }).catch(x => x);
|
||||
assert.equal(e.code, 'WEB_RATE_LIMITED', q);
|
||||
}
|
||||
assert.equal(w.calls.length, used, 'a model that keeps asking does not extend the block');
|
||||
});
|
||||
|
||||
test('the cooldown doubles each time a source refuses again, and a Retry-After header is honoured', async () => {
|
||||
const w = world(call => (duck(call.url) ? page(ANOMALY, 202) : page('<html>captcha</html>', 429)));
|
||||
await w.search.search({ query: 'q1' }).catch(() => {});
|
||||
const first = w.search.status().duckduckgo.blockedForMs;
|
||||
assert.ok(first > 55_000 && first <= 60_000, `first cooldown ${first}`);
|
||||
w.advance(61_000);
|
||||
await w.search.search({ query: 'q2' }).catch(() => {});
|
||||
const second = w.search.status().duckduckgo.blockedForMs;
|
||||
assert.ok(second > 115_000 && second <= 120_000, `second cooldown ${second}`);
|
||||
w.advance(121_000);
|
||||
await w.search.search({ query: 'q3' }).catch(() => {});
|
||||
assert.ok(w.search.status().duckduckgo.blockedForMs > 235_000);
|
||||
const r = world(call => (duck(call.url) ? page(ANOMALY, 429, { 'retry-after': '300' }) : page('<html>captcha</html>', 429)));
|
||||
await r.search.search({ query: 'x' }).catch(() => {});
|
||||
assert.ok(r.search.status().duckduckgo.blockedForMs > 295_000, 'Retry-After: 300');
|
||||
});
|
||||
|
||||
test('a recovered source resets the cooldown', async () => {
|
||||
let refuse = true;
|
||||
const w = world(call => (duck(call.url) ? (refuse ? page(ANOMALY, 202) : page(DDG)) : page('<html>captcha</html>', 429)));
|
||||
await w.search.search({ query: 'a' }).catch(() => {});
|
||||
w.advance(61_000);
|
||||
refuse = false;
|
||||
assert.equal((await w.search.search({ query: 'b' })).sources[0].url, 'https://ddg.example/a');
|
||||
assert.equal(w.search.status().duckduckgo.strikes, 0);
|
||||
assert.equal(w.search.status().duckduckgo.blockedForMs, 0);
|
||||
});
|
||||
|
||||
test('a timeout or a server error gets one retry; two in a row moves on to the next source; nothing reachable says so', async () => {
|
||||
let n = 0;
|
||||
const flaky = world(call => (duck(call.url) ? (++n === 1 ? page('oops', 503) : page(DDG)) : page(BING)));
|
||||
assert.equal((await flaky.search.search({ query: 'q' })).sources[0].url, 'https://ddg.example/a');
|
||||
assert.equal(flaky.hostCalls('duckduckgo.com').length, 2);
|
||||
const down = world(call => (duck(call.url) ? new TypeError('fetch failed') : page(BING)));
|
||||
const viaBing = await down.search.search({ query: 'q' });
|
||||
assert.equal(viaBing.sources.length, 5, 'DuckDuckGo unreachable twice: Bing answers');
|
||||
const none = world(() => new TypeError('fetch failed'));
|
||||
const e = await none.search.search({ query: 'q' }).catch(x => x);
|
||||
assert.equal(e.message, UNREACHABLE_MESSAGE);
|
||||
assert.notEqual(e.code, 'WEB_RATE_LIMITED');
|
||||
});
|
||||
|
||||
test('a search with no hits is an answer; a cancelled search is cancelled', async () => {
|
||||
const w = world(() => page('<html><body>No results found.</body></html>'));
|
||||
assert.deepEqual(await w.search.search({ query: 'zzzz qqqq' }), { sources: [], truncated: false });
|
||||
const ctrl = new AbortController(); ctrl.abort();
|
||||
const e = await w.search.search({ query: 'later' }, ctrl.signal).catch(x => x);
|
||||
assert.equal(e.code, 'WEB_ABORTED');
|
||||
});
|
||||
|
||||
test('too many searches in a minute are held back by the app, not sent to the sources', async () => {
|
||||
const w = world(() => page(DDG));
|
||||
let held = null;
|
||||
for (let i = 0; i < 12 && !held; i++) held = await w.search.search({ query: `question ${i}` }).then(() => null, e => e);
|
||||
assert.ok(held, 'the ninth search in a minute is held back');
|
||||
assert.equal(held.code, 'WEB_RATE_LIMITED');
|
||||
assert.ok(w.hostCalls('duckduckgo.com').length <= 8);
|
||||
});
|
||||
|
||||
test('Bing: the real result page is read (redirect links decoded, snippets kept); a challenge page is a refusal; ordinary pages are not', () => {
|
||||
const rows = parseBingResults(BING);
|
||||
assert.equal(rows.length, 5);
|
||||
assert.ok(rows.every(r => /^https:\/\//.test(r.url) && !r.url.includes('bing.com')), 'real addresses, not Bing redirects');
|
||||
assert.equal(rows[1].url, 'https://github.com/Niko1221/Strata/releases');
|
||||
assert.ok(rows[0].snippet.length > 20);
|
||||
assert.equal(bingTarget('https://www.bing.com/ck/a?!&&p=1&u=a1aHR0cHM6Ly9leGFtcGxlLmNvbS9hP3g9MQ&ntb=1'), 'https://example.com/a?x=1');
|
||||
assert.equal(bingTarget('https://www.bing.com/images/search?q=x'), null);
|
||||
assert.equal(bingTarget('https://example.org/direct'), 'https://example.org/direct');
|
||||
assert.equal(bingLooksBlocked(429, ''), true);
|
||||
assert.equal(bingLooksBlocked(200, '<html><form>captcha</form></html>'), true);
|
||||
assert.equal(bingLooksBlocked(200, BING), false);
|
||||
assert.deepEqual(parseBingResults('<html>nothing here</html>'), []);
|
||||
});
|
||||
@@ -240,6 +240,9 @@ def focused_recovery_prompt(tok, ids, generated):
|
||||
LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
|
||||
QUEUE_BEAT_S = 10.0 # a request waiting for the single turn sends a keep-alive this often (#1619)
|
||||
KEEPALIVE_S = 10.0 # a held-back tool argument leaves the stream quiet: ping at least this often
|
||||
# Anthropic clients add /v1/messages to their base URL themselves. A base URL that already ends in /v1 (copied from an OpenAI-style
|
||||
# setup) makes them post /v1/v1/messages; these two paths mean the same as the real ones. Nothing else is aliased.
|
||||
V1_V1_ALIASES = {"/v1/v1/messages": "/v1/messages", "/v1/v1/messages/count_tokens": "/v1/messages/count_tokens"}
|
||||
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
|
||||
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
|
||||
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
|
||||
@@ -6116,6 +6119,7 @@ def make_handler(svc: Service):
|
||||
if not self._authorized():
|
||||
return
|
||||
path = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true
|
||||
path = V1_V1_ALIASES.get(path, path) # an Anthropic client given ".../v1" as its base posts /v1/v1/messages
|
||||
if path.startswith("/v1/") and self._foreign_page():
|
||||
return
|
||||
if path == "/settings":
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""serve/test_anthropic_base_url.py - an Anthropic client reaches the server by the root address, and by the "/v1" one too.
|
||||
|
||||
The Anthropic SDKs (and Claude Code) add /v1/messages to the base URL themselves. The app used to show the OpenAI-style base
|
||||
(.../v1) in its Anthropic tab, so those clients posted /v1/v1/messages and got a 404. The address is now shown without /v1, and
|
||||
the server accepts /v1/v1/messages (and /v1/v1/messages/count_tokens) as the same request, for people who already pasted the old one.
|
||||
|
||||
Uses the real `anthropic` Python client against the mock-engine server (no network, no key). Skipped when the package is missing.
|
||||
|
||||
python -m unittest serve.test_anthropic_base_url -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.client
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from serve.frontend import ChatTemplate # noqa: E402
|
||||
from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
try:
|
||||
import anthropic
|
||||
except ImportError: # pragma: no cover
|
||||
anthropic = None
|
||||
|
||||
|
||||
REPLY = "<think>\nhm\n</think>\n\nhello from the mock"
|
||||
|
||||
|
||||
class AnthropicBase(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
tok = ByteTokenizer()
|
||||
cls.engine = MockEngine(tok, REPLY, max_context=4096)
|
||||
cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
|
||||
cls.httpd = serve(cls.svc, port=0)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.root = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def raw(self, path, body):
|
||||
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
|
||||
try:
|
||||
c.request("POST", path, body=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
|
||||
r = c.getresponse()
|
||||
return r.status, json.loads(r.read() or b"{}")
|
||||
finally:
|
||||
c.close()
|
||||
|
||||
@unittest.skipIf(anthropic is None, "the anthropic package is not installed")
|
||||
def test_sdk_with_the_root_address_works(self):
|
||||
client = anthropic.Anthropic(base_url=self.root, api_key="not-needed", max_retries=0)
|
||||
msg = client.messages.create(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}])
|
||||
self.assertEqual(msg.type, "message")
|
||||
self.assertIn("hello", "".join(b.text for b in msg.content if b.type == "text"))
|
||||
|
||||
@unittest.skipIf(anthropic is None, "the anthropic package is not installed")
|
||||
def test_sdk_with_the_old_v1_address_works_through_the_alias(self):
|
||||
client = anthropic.Anthropic(base_url=self.root + "/v1", api_key="not-needed", max_retries=0)
|
||||
msg = client.messages.create(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}])
|
||||
self.assertEqual(msg.type, "message")
|
||||
self.assertIn("hello", "".join(b.text for b in msg.content if b.type == "text"))
|
||||
|
||||
@unittest.skipIf(anthropic is None, "the anthropic package is not installed")
|
||||
def test_sdk_streaming_through_the_alias(self):
|
||||
client = anthropic.Anthropic(base_url=self.root + "/v1", api_key="not-needed", max_retries=0)
|
||||
with client.messages.stream(model="strata", max_tokens=32, messages=[{"role": "user", "content": "hi"}]) as stream:
|
||||
text = "".join(stream.text_stream)
|
||||
self.assertIn("hello", text)
|
||||
|
||||
def test_count_tokens_alias(self):
|
||||
body = {"model": "strata", "messages": [{"role": "user", "content": "hi"}]}
|
||||
code, real = self.raw("/v1/messages/count_tokens", body)
|
||||
code2, aliased = self.raw("/v1/v1/messages/count_tokens", body)
|
||||
self.assertEqual((code, code2), (200, 200))
|
||||
self.assertEqual(real, aliased)
|
||||
|
||||
def test_only_the_two_messages_paths_are_aliased(self):
|
||||
body = {"model": "strata", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 8}
|
||||
for path in ("/v1/v1/chat/completions", "/v1/v1/responses", "/v1/v1/v1/messages", "/v1/v2/messages"):
|
||||
code, _ = self.raw(path, body)
|
||||
self.assertEqual(code, 404, path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3859,8 +3859,10 @@ bool launch_gu_swiglu(const NativeExpertLayout& L, int64_t gy, cudaStream_t s, c
|
||||
return false;
|
||||
} else {
|
||||
if (g_old_kernels || split_off<TG>() || g_no_sub16_gu || L.n_embd != 2560 || L.n_ff % 32 != 0 || L.n_ff <= 0) return false;
|
||||
// the 16-lane rows assume 80 dots a row (as launch_gu): the 256-value K-quants have 160
|
||||
if (kq_type<TG> && (L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb != 80) return false;
|
||||
// the 16-lane rows assume 80 dots a row (as launch_gu): the 256-value K-quants and the APR trellis types (TQ2_T /
|
||||
// TQK6 gate/up: qk 128, ipb 8) have 160 at n_embd 2560 and take launch_gu's full-warp multi kernel. Gyro-S (TQK6
|
||||
// gate/up) went through here on every 12.0 card from 147-verify on: half of each gate/up row, looping answers.
|
||||
if ((L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb != 80) return false;
|
||||
const dim3 grid((unsigned) (L.n_ff / 32), (unsigned) gy);
|
||||
bool stage = false;
|
||||
if constexpr (kStageIqGrid<TG>) stage = g_stage_grid && !((TG == 18 || TG == 21) && !stage_tables_on());
|
||||
|
||||
@@ -494,6 +494,8 @@ def run_launch(a: argparse.Namespace) -> int:
|
||||
label = ("This computer" if "127.0.0.1" in u else "Cloudflare" if "trycloudflare" in u else
|
||||
"Tailscale" if ("ts.net" in u or u.split("//")[1].startswith("100.")) else "Network")
|
||||
_say(f" {label:<14} {u}/v1")
|
||||
if result.urls:
|
||||
_say(f" {'Anthropic apps':<14} {result.urls[0]} (Claude Code: ANTHROPIC_BASE_URL, no /v1 at the end)")
|
||||
if result.key:
|
||||
from strata_cli.launch import access
|
||||
_say(f" {'API key':<14} {access.mask_key(result.key)} (show it: strata launch --show-key --preset \"{s.name}\")")
|
||||
|
||||
@@ -164,7 +164,8 @@ def _limits_codex(t: Target) -> list[str]:
|
||||
|
||||
|
||||
def _limits_claude(t: Target) -> list[str]:
|
||||
out = ["Set CLAUDE_CODE_MAX_CONTEXT_TOKENS to the served context (%d here) and CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096: without them Claude Code "
|
||||
out = ["ANTHROPIC_BASE_URL is the server address %s without /v1: Claude Code adds /v1/messages itself (with /v1 in it the requests go to /v1/v1/messages)." % t.url,
|
||||
"Set CLAUDE_CODE_MAX_CONTEXT_TOKENS to the served context (%d here) and CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096: without them Claude Code "
|
||||
"assumes a 100K window and never compacts, or compacts on every turn." % t.context,
|
||||
"No Anthropic login or credential is used; the token is only checked by your own server.",
|
||||
"The notice [claude-code:unrecognized_model] on stderr is harmless."]
|
||||
@@ -249,8 +250,14 @@ def closest_name(name: str) -> str | None:
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ rendering
|
||||
|
||||
def server_root(url: str) -> str:
|
||||
"""The server root: the address without a trailing /v1 (people paste the OpenAI-style base). Anthropic apps add /v1/messages themselves."""
|
||||
root = url.strip().rstrip("/")
|
||||
return root[:-3].rstrip("/") if root.lower().endswith("/v1") else root
|
||||
|
||||
|
||||
def target(url: str, key: str | None, model: str, context: int | None = None) -> Target:
|
||||
return Target(url=url.rstrip("/"), key=key or PLACEHOLDER_KEY, model=model or "strata", context=int(context or 32768))
|
||||
return Target(url=server_root(url), key=key or PLACEHOLDER_KEY, model=model or "strata", context=int(context or 32768))
|
||||
|
||||
|
||||
def render(h: Harness, t: Target) -> dict:
|
||||
|
||||
@@ -223,6 +223,7 @@ class LaunchMonitor(MonitorApp):
|
||||
t.append(f" URL {self.info['url']}/v1 model {self.info.get('model') or 'strata'} key {shown} ")
|
||||
t.append("(k hide)" if self.show_key else "(k show)", style=MUTE)
|
||||
t.append("\n")
|
||||
t.append(f" Claude Code and other Anthropic apps use {self.info['url']} (no /v1)\n", style=MUTE)
|
||||
for u in self.info.get("urls", [])[1:]:
|
||||
t.append(f" also reachable at {u}/v1\n", style=MUTE)
|
||||
t.append("\n " + "App".ljust(20) + "Works with".ljust(22) + "Status\n", style="bold")
|
||||
|
||||
@@ -804,6 +804,20 @@ class ConnectCommand(unittest.TestCase):
|
||||
self.assertIn("ANTHROPIC_AUTH_TOKEN", out)
|
||||
self.assertNotIn("/v1", out.split("ANTHROPIC_BASE_URL")[1].splitlines()[0]) # the Anthropic client adds /v1 itself
|
||||
|
||||
def test_a_pasted_v1_address_is_cut_back_to_the_server_root(self):
|
||||
"""The Anthropic client adds /v1/messages itself, so ANTHROPIC_BASE_URL must never end in /v1 (that gave /v1/v1/messages, a 404);
|
||||
the OpenAI-style apps get exactly one /v1."""
|
||||
code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080/v1/", "--key", "sk-x1234567890abc", "--show-key", "--output", "json"])
|
||||
data = json.loads(out)
|
||||
self.assertEqual(data["env"]["ANTHROPIC_BASE_URL"], "http://127.0.0.1:8080")
|
||||
self.assertIn('"ANTHROPIC_BASE_URL": "http://127.0.0.1:8080"', data["files"][0]["text"])
|
||||
code, out, _ = run_cli(["connect", "opencode", "--url", "http://127.0.0.1:8080/v1", "--output", "json"])
|
||||
text = json.loads(out)["files"][0]["text"]
|
||||
self.assertIn("http://127.0.0.1:8080/v1", text)
|
||||
self.assertNotIn("/v1/v1", text)
|
||||
code, out, _ = run_cli(["connect", "claude-code", "--url", "http://127.0.0.1:8080"])
|
||||
self.assertIn("without /v1", out)
|
||||
|
||||
def test_write_keeps_a_backup_and_merges(self):
|
||||
target = Path(os.environ["HOME"]) / ".config" / "opencode" / "opencode.json"
|
||||
target.parent.mkdir(parents=True)
|
||||
|
||||
Reference in new issue
Block a user