Add context management: notepad, sliding window, cache reuse, windowed GUI
Per-session notepad: agent-curated labelled entries via the notepad tool
(set/remove/clear), injected as a pinned <NOTEPAD> section above DIALOG,
char-budgeted with a consolidate ceiling, exposed in a read-only GUI panel.
Sliding DIALOG window (src/window.rs): retains recent messages by count in
two tiers (MAIN_AREA=40 + BUFFER=10), append-only while the buffer fills so
the prompt prefix stays byte-stable for KV reuse, then stepped hysteresis
eviction snapping to user-turn boundaries (never splits a tool exchange).
window_start persisted per session; full history never deleted.
Engine prefix-cache reuse: leave DIALOG open (a moving </DIALOG> closer broke
the engine prompt_ckpt_prefix every user turn, forcing full re-prefill);
surface usage.cached_tokens as a GUI badge; fix the PerfMeter prefill gauge to
gauge over non-cached tokens; add a static sliding-window marker after the
opener so the model knows older turns are omitted.
Stats clarity: distinguish the current inference context (last_prompt_tokens,
new "Contesto attuale" card) from the cumulative lifetime token total
(relabeled "Token cumulativi ... su tutti i turni"); /api/stats carries both.
Windowed browser transcript: GET /api/sessions/{id}/messages returns only the
retained window (SQL-filtered by window_start, never loads the full history)
plus the total count, wrapped as {messages, window_start, total}; the GUI shows
a banner noting older turns are preserved server-side. Full-chat export deferred.
Settings: the session scope re-reads the persisted instance fresh from the store
(like the general scope already did), fixing a stale-cache display that looked
like the session System Prompt was not being kept.
Docs (README) refreshed; 158 tests + 3 ignored green, clippy and fmt clean.
This commit is contained in:
1 parent
7c945890f4
commit
0ce84581a4
20 files changed
+1412
-118
No files matched your search
@@ -96,13 +96,19 @@ offline, same-origin so no CORS). It is a thin client over a **session-aware API
|
||||
session list and the chat — width clamped and persisted; streaming answers with a
|
||||
collapsible "thinking" panel; touch-friendly targets and safe-area insets).
|
||||
- `POST /api/sessions`, `GET /api/sessions`, `GET/PATCH/DELETE /api/sessions/{id}`,
|
||||
`GET /api/sessions/{id}/messages` — session CRUD and history.
|
||||
`GET /api/sessions/{id}/messages` — session CRUD and the **sliding-window**
|
||||
transcript: the same recent messages the model sees (filtered in SQL by the
|
||||
persisted `window_start`), wrapped as `{messages, window_start, total}` so the
|
||||
GUI can flag older turns as omitted-but-preserved. The full history is never
|
||||
shipped to the browser.
|
||||
- `POST /api/sessions/{id}/chat` — append a turn; the server loads the stored
|
||||
context, runs inference (streaming SSE or not) and persists the new turns with
|
||||
their token usage.
|
||||
- `GET /api/stats` — the stats dashboard payload: persistent totals (sessions,
|
||||
messages, prompt/completion/total tokens, tool calls), per-session and per-day
|
||||
breakdowns, plus live engine status and a since-startup decode/prefill speed gauge.
|
||||
messages, cumulative prompt/completion/total tokens, tool calls), the current
|
||||
inference context (`last_prompt_tokens`, the latest turn's prompt), per-session
|
||||
and per-day breakdowns, plus live engine status and a since-startup
|
||||
decode/prefill speed gauge.
|
||||
- `GET/PUT /api/settings/defaults` — the global default settings template.
|
||||
- `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir;
|
||||
returns metadata (kind, token count, path). Attach the returned id to a chat turn.
|
||||
@@ -137,8 +143,17 @@ each closed by its tag plus a blank line so boundaries are explicit. The static
|
||||
sections — `SYSTEM_PROMPT` (identity + speaker convention + the session's system
|
||||
prompt) and `TOOL_USE` (a compact tool manual) — live in the SQLite
|
||||
`context_sections` table: seeded, editable without recompiling, and extensible by
|
||||
adding a row. The interactive `DIALOG` region wraps the real role messages
|
||||
(history + new turn) so the engine keeps its turn structure. Every turn carries a
|
||||
adding a row. The interactive `DIALOG` region opens with `<DIALOG>` and is left
|
||||
**open** (no trailing closer) around the real role messages (history + new turn),
|
||||
so the engine keeps its turn structure. The open tail is deliberate: a moving
|
||||
`</DIALOG>` after the last user turn shifts every turn and breaks the engine's
|
||||
prefix checkpoint (`RESUME`), forcing a full re-prefill; leaving DIALOG open keeps
|
||||
the prompt prefix byte-stable so the engine reuses its cached KV and only the
|
||||
newest exchange is prefilled. The engine's `RESUME` cache-hit count is surfaced
|
||||
per turn as `usage.cached_tokens` (the GUI badge). A **static marker** right after
|
||||
the `<DIALOG>` opener tells the model it is viewing a sliding window (older turns
|
||||
omitted; the first visible turn is not necessarily the chat's first message) — being
|
||||
static, it keeps the prefix cache-stable. Every turn carries a
|
||||
prompt-only `[SPEAKER: name - YYYY-MM-DD HH:MM]` provenance stamp in the server's
|
||||
local time — framework metadata for the model, **never shown in the browser**: any
|
||||
tag the model echoes back is stripped from stored/displayed content and from
|
||||
@@ -155,10 +170,16 @@ the context directly. The `shell_exec` output cap is a second safety net.
|
||||
|
||||
**Statistics.** The "Statistiche" button opens a live dashboard over the
|
||||
*persistent* history — our angle on the reference's ephemeral request monitor:
|
||||
overview cards (engine model / context window / idle-busy, token-weighted **decode
|
||||
speed** and prefill speed since startup, total/prompt/completion tokens, sessions,
|
||||
messages, tool calls), a **daily token chart** (stacked prompt/completion per UTC
|
||||
day) and a **per-session breakdown** with relative token-share bars. `GET /api/stats`
|
||||
overview cards (engine model / context window / idle-busy, **current context** —
|
||||
the latest turn's prompt size, i.e. what we actually send to inference now —
|
||||
token-weighted **decode speed** and prefill speed since startup, **cumulative**
|
||||
prompt/completion/total tokens, sessions, messages, tool calls), a **daily token
|
||||
chart** (stacked prompt/completion per UTC day) and a **per-session breakdown**
|
||||
with relative token-share bars. The cumulative prompt total is a *lifetime*
|
||||
counter, **not** the context size: every turn re-sends the whole retained window,
|
||||
so summing per-turn `prompt_tokens` re-counts that window each turn (and includes
|
||||
the cache-resumed prefix); the dedicated **current-context** card
|
||||
(`last_prompt_tokens`) reports the actual inference context instead. `GET /api/stats`
|
||||
returns the store aggregates plus a live engine status and an in-memory performance
|
||||
gauge (token-weighted over the requests served since startup, from the engine's
|
||||
`DONE` timings); the view polls every 2s while open. History totals survive
|
||||
@@ -270,14 +291,18 @@ later adaptation round.
|
||||
|
||||
## Status
|
||||
|
||||
Working and tested (140 tests, plus 3 real-file tests run on demand). Text, images,
|
||||
Working and tested (158 tests, plus 3 real-file tests run on demand). Text, images,
|
||||
the full client-side tool loop, the Anthropic endpoint, the web GUI (session
|
||||
context, streaming, stats, **file/image upload**, assistant **Markdown/LaTeX
|
||||
rendering** with native MathML) and **agent mode** (the model using `shell_exec`
|
||||
on the host) have been validated live against the real Inkling engine. The
|
||||
**context compositor** (named sections stored in SQLite — `SYSTEM_PROMPT` /
|
||||
`TOOL_USE` / `DIALOG`) and prompt-only **[SPEAKER] provenance** are in place,
|
||||
verified against the real chat template.
|
||||
verified against the real chat template. A per-session **notepad** (agent-curated
|
||||
`<NOTEPAD>` entries via the `notepad` tool) and a **sliding DIALOG window**
|
||||
(message-count main area + buffer headroom, stepped KV-cache-friendly eviction at
|
||||
turn boundaries, `window_start` persisted per session, full history never deleted)
|
||||
are implemented and dogfooded live.
|
||||
|
||||
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
|
||||
returns a clear 400), multi-slot batching, logprobs / structured output, automatic
|
||||
@@ -340,6 +365,73 @@ Candidates under evaluation — the concrete engine / embedder / store choice is
|
||||
the same seam: the team's Qdrant (used by Iris) and the planned ArangoDB
|
||||
(documents + vectors + search).
|
||||
|
||||
### Sliding context window + per-session notepad
|
||||
|
||||
Both are **implemented and validated live**: the per-session notepad (store,
|
||||
`notepad` tool, `<NOTEPAD>` injection, read-only GUI panel) and the **sliding
|
||||
DIALOG window** (`src/window.rs`). The compositor no longer injects the full
|
||||
history: `window::select` retains the most recent messages **by count**, in two
|
||||
tiers — a **main area** (`MAIN_AREA = 40` recent messages always kept) plus a
|
||||
**buffer** (`BUFFER = 10` messages of headroom above it). The cut lands on
|
||||
**user-turn boundaries**, so a `tool_call`/`tool_result` pair is never split, and
|
||||
the full history stays in SQLite (evicted turns remain recallable).
|
||||
|
||||
Eviction is **stepped, with hysteresis** — the "buffer fills → cleared → new
|
||||
buffer" cycle: while the retained count is at most `MAIN_AREA + BUFFER` the window
|
||||
is **append-only** (new turns join the tail), so the prompt prefix is byte-identical
|
||||
turn-to-turn and the engine reuses its cached KV. When occupancy crosses
|
||||
`MAIN_AREA + BUFFER` the buffer is **cleared**: the start advances in chunks to
|
||||
user-turn boundaries down to `MAIN_AREA`, amortizing one re-prefill over several
|
||||
append-only turns, and a new buffer starts filling. The chosen start id is persisted
|
||||
per session (`sessions.window_start`, idempotent migration) and respected on the
|
||||
next turn. The counts are a starting point (40 main + 10 buffer); both will shrink
|
||||
at regime. A **total-size (char/token) cut** is deliberately deferred — it interacts
|
||||
with the stepped anchor and is not as simple as a second cap; the notepad preserves
|
||||
what matters beyond the window.
|
||||
|
||||
The **browser sees the same window**: `GET …/messages` returns only the retained
|
||||
suffix (SQL-filtered by `window_start`, so a months-long history — potentially tens
|
||||
of millions of tokens — is never loaded whole or shipped to the client), plus the
|
||||
total count so the GUI shows a banner noting older turns are preserved server-side.
|
||||
A full-chat export/download command is deferred; the live view is windowed by design.
|
||||
|
||||
To survive what slides out, each session has a **notepad**: a small,
|
||||
agent-curated set of **labelled entries** (`key → short text`, e.g. `goal`,
|
||||
`state`, `decision:…`, `pitfall:…`, `ref:…`) persisted per-session behind the
|
||||
`Store` trait and injected as a pinned `<NOTEPAD>` section **immediately above `DIALOG`**,
|
||||
always visible; its usage instructions live in the `TOOL_USE` section (the tool
|
||||
manual), not in the notepad block itself. One action-based tool (`notepad(action=set|remove|clear,
|
||||
key, text?)`) upserts/removes by key — idempotent, no shifting numeric indices.
|
||||
Compact single-line block, deterministic order, a **soft size budget** (chars,
|
||||
per-entry and total caps) with a hard ceiling that asks the agent to consolidate.
|
||||
|
||||
Design stance — **importance, not recency**: no silent FIFO eviction, no age-based
|
||||
decay. strata-ctl sessions are **persistent (no expiry)** and the agent is
|
||||
**reactive** — it runs only on external input, with no autonomous background
|
||||
curator (unlike Iris's recap/dreamer). The notepad is therefore the **resume
|
||||
anchor** across idle gaps, restarts and the sliding window: a goal set on turn 1
|
||||
must survive weeks, and the agent itself decides what to keep, in-turn. Guidance
|
||||
steers *what* to pin (goal, decisions + rationale, state/next step, constraints,
|
||||
pitfalls, key paths) and what not (logs/long documents → future recall;
|
||||
single-task ephemera → history). A read-only GUI panel exposes each session's
|
||||
notepad for observability.
|
||||
|
||||
Section order is already driven by the `context_sections.position` column, so a
|
||||
natural extension is to let the **agent itself choose the layout**: it is the
|
||||
consumer that sees the sections, so it can ask to reorder them (persisted as
|
||||
positions). Ordering applies to the pinned sections above `DIALOG`, which stays
|
||||
the tail; it is deliberate and persisted, not per-turn, to keep the KV-cache
|
||||
prefix stable.
|
||||
|
||||
Deferred: a total-size (char/token) cut on the dialog window (the message-count
|
||||
policy ships first), common/cross-session memories, a working-memory reference area
|
||||
(content addressed but kept out of the prompt budget), auto-curation. **Automatic
|
||||
recap is out of scope**: summarizing what slides out needs an autonomous background
|
||||
agent, whereas strata-ctl is reactive — the agent-curated notepad plus deterministic
|
||||
truncation cover the resume anchor without a curator. The deep-retrieval complement
|
||||
is the suspended semantic vector memory above; a simpler lexical recall over the
|
||||
retained SQLite history can come first.
|
||||
|
||||
### Client surfaces (under consideration, not scheduled)
|
||||
|
||||
Protocol-first: harden and version the existing client contract (session/turn JSON
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"identity.folder": " Your personal folder is {folder}.",
|
||||
"speaker.tag": "[SPEAKER: {name} - {when}]",
|
||||
"speaker.note": " User and agent turns are prefixed with a [SPEAKER: name - local date and time] tag identifying who generated them and when. It is framework-added metadata: never write or repeat it in your own replies.",
|
||||
"dialog.window_note": "[Sliding window: this view shows only recent turns; older turns are omitted but kept in history. The first visible turn is NOT necessarily the chat's first message. Pin what must survive the window in the NOTEPAD.]",
|
||||
"error.name_locked": "The session name is immutable after the first interaction.",
|
||||
"error.name_empty": "The name must not be empty.",
|
||||
"error.session_not_found": "Session not found.",
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"identity.folder": " La tua cartella personale è {folder}.",
|
||||
"speaker.tag": "[SPEAKER: {name} - {when}]",
|
||||
"speaker.note": " I turni dell'utente e dell'agente sono preceduti da un tag [SPEAKER: nome - data e ora locale] che identifica chi li ha generati e quando. È un metadato aggiunto dal framework: non scriverlo né ripeterlo mai nelle tue risposte.",
|
||||
"dialog.window_note": "[Finestra scorrevole: questa vista mostra solo i turni recenti; i turni più vecchi sono omessi ma conservati nella cronologia. Il primo turno visibile NON è necessariamente il primo messaggio della chat. Fissa nel NOTEPAD ciò che deve sopravvivere alla finestra.]",
|
||||
"error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.",
|
||||
"error.name_empty": "Il nome non può essere vuoto.",
|
||||
"error.session_not_found": "Sessione non trovata.",
|
||||
|
||||
+97
-15
@@ -9,6 +9,7 @@
|
||||
//! [`run_loop`] is pure orchestration — generic over the "model step" — so it is
|
||||
//! testable without the engine and independent of the concrete runner.
|
||||
|
||||
pub mod notepad;
|
||||
pub mod shell;
|
||||
|
||||
use std::future::Future;
|
||||
@@ -25,9 +26,13 @@ use shell::{ShellRequest, ShellRunner};
|
||||
/// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
|
||||
pub const MAX_ITERS: usize = 24;
|
||||
|
||||
/// The tools offered to the agent (currently the universal `shell_exec`).
|
||||
/// The tools offered to the agent: the universal `shell_exec` (action) and the
|
||||
/// `notepad` (per-session context management).
|
||||
pub fn agent_tools() -> Json {
|
||||
json!([shell::shell_exec_declaration()])
|
||||
json!([
|
||||
shell::shell_exec_declaration(),
|
||||
notepad::notepad_declaration()
|
||||
])
|
||||
}
|
||||
|
||||
/// Progress events streamed to the GUI for observability (no confirmation gate).
|
||||
@@ -69,24 +74,29 @@ fn emit(progress: &Option<UnboundedSender<AgentEvent>>, ev: AgentEvent) {
|
||||
/// `default_cwd` (the session's personal folder) is used when the model omits cwd.
|
||||
async fn execute_tool(
|
||||
runner: &Arc<dyn ShellRunner>,
|
||||
store: &Arc<dyn Store>,
|
||||
session_id: &str,
|
||||
tc: &ToolCall,
|
||||
default_cwd: Option<&str>,
|
||||
) -> String {
|
||||
if tc.function.name != "shell_exec" {
|
||||
return format!("error: unknown tool '{}'", tc.function.name);
|
||||
}
|
||||
let args: Json = match serde_json::from_str(&tc.function.arguments) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return format!("error: invalid tool arguments JSON: {e}"),
|
||||
};
|
||||
let req = match ShellRequest::from_args(&args) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return format!("error: {e}"),
|
||||
};
|
||||
let cwd = req.cwd.as_deref().or(default_cwd);
|
||||
match runner.run(&req.command, cwd, req.timeout).await {
|
||||
Ok(out) => out.to_result_text(),
|
||||
Err(e) => format!("error: {e}"),
|
||||
match tc.function.name.as_str() {
|
||||
"shell_exec" => {
|
||||
let req = match ShellRequest::from_args(&args) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return format!("error: {e}"),
|
||||
};
|
||||
let cwd = req.cwd.as_deref().or(default_cwd);
|
||||
match runner.run(&req.command, cwd, req.timeout).await {
|
||||
Ok(out) => out.to_result_text(),
|
||||
Err(e) => format!("error: {e}"),
|
||||
}
|
||||
}
|
||||
"notepad" => notepad::execute(store, session_id, &args).await,
|
||||
other => format!("error: unknown tool '{other}'"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,7 +229,8 @@ where
|
||||
arguments: tc.function.arguments.clone(),
|
||||
},
|
||||
);
|
||||
let output = execute_tool(&runner, tc, default_cwd.as_deref()).await;
|
||||
let output =
|
||||
execute_tool(&runner, &store, session_id, tc, default_cwd.as_deref()).await;
|
||||
emit(
|
||||
&progress,
|
||||
AgentEvent::ToolResult {
|
||||
@@ -443,6 +454,14 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_tool_yields_error_result() {
|
||||
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
let sess = store
|
||||
.create_session(
|
||||
"Agent",
|
||||
"test-model",
|
||||
&crate::store::SessionSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
||||
let tc = ToolCall {
|
||||
id: "c".into(),
|
||||
@@ -452,10 +471,73 @@ mod tests {
|
||||
arguments: "{}".into(),
|
||||
},
|
||||
};
|
||||
let out = execute_tool(&runner, &tc, None).await;
|
||||
let out = execute_tool(&runner, &store, &sess.id, &tc, None).await;
|
||||
assert!(out.contains("unknown tool"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loop_runs_notepad_tool_and_persists_entry() {
|
||||
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
let sess = store
|
||||
.create_session(
|
||||
"Agent",
|
||||
"test-model",
|
||||
&crate::store::SessionSettings::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
||||
let n = Arc::new(AtomicUsize::new(0));
|
||||
let model = move |_req: ChatRequest| {
|
||||
let n = n.clone();
|
||||
async move {
|
||||
if n.fetch_add(1, Ordering::SeqCst) == 0 {
|
||||
Ok(response(
|
||||
ChatMessage {
|
||||
role: Role::Assistant,
|
||||
content: None,
|
||||
tool_call_id: None,
|
||||
tool_calls: Some(vec![ToolCall {
|
||||
id: "np1".into(),
|
||||
kind: "function".into(),
|
||||
function: FunctionCall {
|
||||
name: "notepad".into(),
|
||||
arguments: json!({"action":"set","key":"goal","text":"dogfood the notepad"}).to_string(),
|
||||
},
|
||||
}]),
|
||||
name: None,
|
||||
reasoning_content: None,
|
||||
},
|
||||
FinishReason::ToolCalls,
|
||||
))
|
||||
} else {
|
||||
Ok(final_response())
|
||||
}
|
||||
}
|
||||
};
|
||||
run_loop(
|
||||
model,
|
||||
LoopContext {
|
||||
runner,
|
||||
store: store.clone(),
|
||||
default_cwd: None,
|
||||
max_iters: 8,
|
||||
progress: None,
|
||||
},
|
||||
&sess.id,
|
||||
base_req(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// The entry is persisted per-session, and the tool result is in the trajectory.
|
||||
let np = store.notepad(&sess.id).unwrap();
|
||||
assert_eq!(np.len(), 1);
|
||||
assert_eq!(np[0].key, "goal");
|
||||
assert_eq!(np[0].text, "dogfood the notepad");
|
||||
let msgs = store.messages(&sess.id).unwrap();
|
||||
let tool = msgs.iter().find(|m| m.role == "tool").unwrap();
|
||||
assert!(tool.content.contains("saved"), "{}", tool.content);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_cwd_is_used_when_model_omits_it() {
|
||||
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
//! The agent's notepad tool: a persistent, per-session set of labelled entries
|
||||
//! the agent curates so important state survives the sliding context window.
|
||||
//!
|
||||
//! One action-based tool (`set`/`remove`/`clear`); entries are addressed by a
|
||||
//! stable `key` (upsert is idempotent, no shifting numeric indices). Bounded by a
|
||||
//! char budget with a soft warning and a hard ceiling that asks the agent to
|
||||
//! consolidate — nothing is evicted automatically (importance, not recency).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use serde_json::{json, Value as Json};
|
||||
|
||||
use crate::store::Store;
|
||||
|
||||
/// Per-entry char cap (unicode-aware). Over-long entries are refused, not
|
||||
/// silently truncated: the agent must keep notes short.
|
||||
const MAX_ENTRY_CHARS: usize = 1024;
|
||||
/// Total notepad char cap (hard ceiling). Over it, a `set` is refused and the
|
||||
/// agent is asked to consolidate stale entries itself.
|
||||
const MAX_TOTAL_CHARS: usize = 8000;
|
||||
/// Soft warning threshold: near the ceiling, nudge consolidation.
|
||||
const SOFT_WARN_CHARS: usize = 6000;
|
||||
/// Max key length.
|
||||
const MAX_KEY_CHARS: usize = 64;
|
||||
|
||||
/// The OpenAI function declaration offered to the model for the agent.
|
||||
pub fn notepad_declaration() -> Json {
|
||||
json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "notepad",
|
||||
"description": "Manage your persistent per-session notepad, always visible above \
|
||||
the dialog. Pin durable task state that must survive the sliding context window: \
|
||||
goal, decisions + rationale, current state/next step, constraints, pitfalls, key \
|
||||
paths/identifiers. Entries are labelled by a stable key: action=set upserts by key \
|
||||
(idempotent), remove deletes one entry, clear empties all. Keep entries short. Do \
|
||||
NOT store long logs/documents or single-task ephemera. The notepad is bounded: \
|
||||
near the limit, consolidate stale entries yourself — nothing is evicted automatically.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"enum": ["set", "remove", "clear"],
|
||||
"description": "set creates/updates entry `key`; remove deletes `key`; clear empties the notepad."
|
||||
},
|
||||
"key": {
|
||||
"type": "string",
|
||||
"description": "Stable label addressing the entry (required for set/remove), e.g. goal, state, decision:auth, pitfall:x, ref:path."
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "Short entry content (required for set, max 1024 chars)."
|
||||
}
|
||||
},
|
||||
"required": ["action"]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute a notepad tool call against the store, returning the text the model
|
||||
/// reads as the tool result. Store work runs off the async runtime.
|
||||
pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> String {
|
||||
let action = args
|
||||
.get("action")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let key = args
|
||||
.get("key")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let text = args
|
||||
.get("text")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let store = store.clone();
|
||||
let sid = session_id.to_string();
|
||||
let res = tokio::task::spawn_blocking(move || -> Result<String> {
|
||||
match action.as_str() {
|
||||
"set" => {
|
||||
if key.is_empty() {
|
||||
return Ok("error: notepad set requires a non-empty 'key'".into());
|
||||
}
|
||||
if key.chars().count() > MAX_KEY_CHARS {
|
||||
return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)"));
|
||||
}
|
||||
if key.contains('\n') {
|
||||
return Ok("error: key must be a single line".into());
|
||||
}
|
||||
if text.is_empty() {
|
||||
return Ok("error: notepad set requires non-empty 'text'".into());
|
||||
}
|
||||
let nlen = text.chars().count();
|
||||
if nlen > MAX_ENTRY_CHARS {
|
||||
return Ok(format!(
|
||||
"error: entry too long ({nlen} > {MAX_ENTRY_CHARS} chars); shorten it"
|
||||
));
|
||||
}
|
||||
let entries = store.notepad(&sid)?;
|
||||
let others: usize = entries
|
||||
.iter()
|
||||
.filter(|e| e.key != key)
|
||||
.map(|e| e.text.chars().count())
|
||||
.sum();
|
||||
let total = others + nlen;
|
||||
if total > MAX_TOTAL_CHARS {
|
||||
return Ok(format!(
|
||||
"error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \
|
||||
consolidate stale entries (notepad remove/clear), then retry. Nothing \
|
||||
is evicted automatically."
|
||||
));
|
||||
}
|
||||
store.set_notepad_entry(&sid, &key, &text)?;
|
||||
let count = store.notepad(&sid)?.len();
|
||||
let mut msg = format!(
|
||||
"Entry '{key}' saved. Notepad: {count} entries, {total}/{MAX_TOTAL_CHARS} chars."
|
||||
);
|
||||
if total >= SOFT_WARN_CHARS {
|
||||
msg.push_str(" Warning: nearing the limit — consolidate stale entries.");
|
||||
}
|
||||
Ok(msg)
|
||||
}
|
||||
"remove" => {
|
||||
if key.is_empty() {
|
||||
return Ok("error: notepad remove requires a non-empty 'key'".into());
|
||||
}
|
||||
let existed = store.remove_notepad_entry(&sid, &key)?;
|
||||
if existed {
|
||||
Ok(format!("Entry '{key}' removed."))
|
||||
} else {
|
||||
Ok(format!("No entry '{key}' (nothing removed)."))
|
||||
}
|
||||
}
|
||||
"clear" => {
|
||||
store.clear_notepad(&sid)?;
|
||||
Ok("Notepad cleared.".into())
|
||||
}
|
||||
other => Ok(format!(
|
||||
"error: unknown notepad action '{other}' (use set|remove|clear)"
|
||||
)),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match res {
|
||||
Ok(Ok(msg)) => msg,
|
||||
Ok(Err(e)) => format!("error: {e}"),
|
||||
Err(e) => format!("error: notepad task failed: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::store::{SessionSettings, SqliteStore};
|
||||
|
||||
fn setup() -> (Arc<dyn Store>, String) {
|
||||
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
let sess = store
|
||||
.create_session("Chat", "m", &SessionSettings::default())
|
||||
.unwrap();
|
||||
(store, sess.id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_upsert_remove_clear() {
|
||||
let (store, sid) = setup();
|
||||
let out = execute(
|
||||
&store,
|
||||
&sid,
|
||||
&json!({"action":"set","key":"goal","text":"ship it"}),
|
||||
)
|
||||
.await;
|
||||
assert!(out.contains("saved"), "{out}");
|
||||
// Upsert by key replaces, does not duplicate.
|
||||
execute(
|
||||
&store,
|
||||
&sid,
|
||||
&json!({"action":"set","key":"goal","text":"ship + dogfood"}),
|
||||
)
|
||||
.await;
|
||||
let np = store.notepad(&sid).unwrap();
|
||||
assert_eq!(np.len(), 1);
|
||||
assert_eq!(np[0].text, "ship + dogfood");
|
||||
// Remove.
|
||||
let out = execute(&store, &sid, &json!({"action":"remove","key":"goal"})).await;
|
||||
assert!(out.contains("removed"), "{out}");
|
||||
assert!(store.notepad(&sid).unwrap().is_empty());
|
||||
// Clear.
|
||||
execute(&store, &sid, &json!({"action":"set","key":"a","text":"x"})).await;
|
||||
let out = execute(&store, &sid, &json!({"action":"clear"})).await;
|
||||
assert!(out.contains("cleared"), "{out}");
|
||||
assert!(store.notepad(&sid).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validation_and_budget() {
|
||||
let (store, sid) = setup();
|
||||
assert!(execute(&store, &sid, &json!({"action":"set","text":"x"}))
|
||||
.await
|
||||
.contains("key"));
|
||||
assert!(execute(&store, &sid, &json!({"action":"set","key":"k"}))
|
||||
.await
|
||||
.contains("text"));
|
||||
assert!(execute(&store, &sid, &json!({"action":"bogus"}))
|
||||
.await
|
||||
.contains("unknown"));
|
||||
// Over-long entry is refused (not truncated).
|
||||
let long = "a".repeat(MAX_ENTRY_CHARS + 1);
|
||||
assert!(
|
||||
execute(&store, &sid, &json!({"action":"set","key":"k","text":long}))
|
||||
.await
|
||||
.contains("too long")
|
||||
);
|
||||
// Hard ceiling: 7 * 1024 = 7168 fits; an 8th (8192) exceeds 8000 -> refused.
|
||||
let big = "b".repeat(MAX_ENTRY_CHARS);
|
||||
for i in 0..7 {
|
||||
execute(
|
||||
&store,
|
||||
&sid,
|
||||
&json!({"action":"set","key":format!("k{i}"),"text":big}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let out = execute(&store, &sid, &json!({"action":"set","key":"k7","text":big})).await;
|
||||
assert!(out.contains("full"), "{out}");
|
||||
assert_eq!(store.notepad(&sid).unwrap().len(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declaration_shape() {
|
||||
let d = notepad_declaration();
|
||||
assert_eq!(d["type"], "function");
|
||||
assert_eq!(d["function"]["name"], "notepad");
|
||||
assert_eq!(d["function"]["parameters"]["required"][0], "action");
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
|
||||
.patch(sessions::patch_session),
|
||||
)
|
||||
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
|
||||
.route("/api/sessions/{id}/notepad", get(sessions::get_notepad))
|
||||
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
|
||||
.route(
|
||||
"/api/uploads",
|
||||
|
||||
+29
-4
@@ -58,7 +58,10 @@ impl PerfMeter {
|
||||
self.decode_ms += d;
|
||||
}
|
||||
if let Some(p) = u.prompt_ms.filter(|p| *p > 0.0) {
|
||||
self.prompt_tokens += u.prompt_tokens as u64;
|
||||
// prompt_ms covers only the tokens actually prefilled (RESUME excluded),
|
||||
// so gauge throughput over the non-cached tokens, not the total prompt.
|
||||
self.prompt_tokens +=
|
||||
u.prompt_tokens.saturating_sub(u.cached_tokens.unwrap_or(0)) as u64;
|
||||
self.prompt_ms += p;
|
||||
}
|
||||
}
|
||||
@@ -308,7 +311,10 @@ impl ChatService {
|
||||
.and_then(|o| o.done.as_ref())
|
||||
.map(|d| (Some(d.prompt_ms), Some(d.decode_ms)))
|
||||
.unwrap_or((None, None));
|
||||
let usage = Usage::new(prompt_len, completion).with_timings(pms, dms);
|
||||
let resumed = gen.as_ref().ok().map(|o| o.resumed).unwrap_or(0);
|
||||
let usage = Usage::new(prompt_len, completion)
|
||||
.with_timings(pms, dms)
|
||||
.with_cached(resumed);
|
||||
perf.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.record(&usage);
|
||||
@@ -462,8 +468,9 @@ fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason {
|
||||
fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
|
||||
match &outcome.done {
|
||||
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion))
|
||||
.with_timings(Some(d.prompt_ms), Some(d.decode_ms)),
|
||||
None => Usage::new(prompt_len, completion),
|
||||
.with_timings(Some(d.prompt_ms), Some(d.decode_ms))
|
||||
.with_cached(outcome.resumed),
|
||||
None => Usage::new(prompt_len, completion).with_cached(outcome.resumed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -493,4 +500,22 @@ mod tests {
|
||||
}
|
||||
assert!(!p.exists(), "guard must remove the file on drop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_of_carries_cache_hits() {
|
||||
let out = Outcome {
|
||||
tokens: vec![1, 2, 3],
|
||||
done: None,
|
||||
resumed: 80,
|
||||
};
|
||||
let u = usage_of(&out, 100, 3);
|
||||
assert_eq!(u.prompt_tokens, 100);
|
||||
assert_eq!(u.cached_tokens, Some(80));
|
||||
let cold = Outcome {
|
||||
tokens: vec![],
|
||||
done: None,
|
||||
resumed: 0,
|
||||
};
|
||||
assert_eq!(usage_of(&cold, 50, 0).cached_tokens, None);
|
||||
}
|
||||
}
|
||||
+166
-28
@@ -29,8 +29,9 @@ use crate::i18n::t;
|
||||
use crate::name;
|
||||
use crate::render;
|
||||
use crate::store::{
|
||||
ContextSection, NewMessage, Session, SessionSettings, Stats, Store, StoredMessage,
|
||||
ContextSection, NewMessage, NotepadEntry, Session, SessionSettings, Stats, Store, StoredMessage,
|
||||
};
|
||||
use crate::window;
|
||||
use tokio_stream::wrappers::UnboundedReceiverStream;
|
||||
|
||||
/// Run a synchronous store operation off the async runtime.
|
||||
@@ -197,12 +198,33 @@ pub(crate) struct MessageView {
|
||||
content_html: Option<String>,
|
||||
}
|
||||
|
||||
/// The GUI transcript payload: the sliding-window messages (the same recent view
|
||||
/// the model sees) plus metadata so the UI can tell the user older turns are
|
||||
/// omitted but preserved. The full history is never shipped to the browser — an
|
||||
/// agent active for months could accumulate tens of millions of tokens.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct MessagesView {
|
||||
messages: Vec<MessageView>,
|
||||
/// First retained message id (the persisted window start; 0 = from the start).
|
||||
window_start: i64,
|
||||
/// Total stored messages; exceeds `messages.len()` when older turns slid out.
|
||||
total: u64,
|
||||
}
|
||||
|
||||
pub(crate) async fn get_messages(
|
||||
State(st): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<Vec<MessageView>>, Error> {
|
||||
let msgs = with_store(&st, move |s| s.messages(&id)).await?;
|
||||
let views = msgs
|
||||
) -> Result<Json<MessagesView>, Error> {
|
||||
// The browser sees the SAME sliding window the model sees: only messages at
|
||||
// or after the persisted window start, filtered in SQL (the full history is
|
||||
// never loaded whole). Older turns stay in the store for a future export.
|
||||
let (msgs, total, window_start) = with_store(&st, move |s| {
|
||||
let ws = s.window_start(&id)?;
|
||||
let (m, total) = s.message_window(&id, ws)?;
|
||||
Ok((m, total, ws))
|
||||
})
|
||||
.await?;
|
||||
let messages = msgs
|
||||
.into_iter()
|
||||
.map(|mut m| {
|
||||
// The [SPEAKER] tag is model-context metadata; if a reply echoed it,
|
||||
@@ -218,7 +240,20 @@ pub(crate) async fn get_messages(
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(Json(views))
|
||||
Ok(Json(MessagesView {
|
||||
messages,
|
||||
window_start,
|
||||
total,
|
||||
}))
|
||||
}
|
||||
|
||||
/// `GET /api/sessions/{id}/notepad` — the session's pinned notepad entries
|
||||
/// (read-only observability; the agent writes them via the notepad tool).
|
||||
pub(crate) async fn get_notepad(
|
||||
State(st): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<Vec<NotepadEntry>>, Error> {
|
||||
Ok(Json(with_store(&st, move |s| s.notepad(&id)).await?))
|
||||
}
|
||||
|
||||
/// The stats dashboard payload: persistent history aggregates (from the store)
|
||||
@@ -253,6 +288,15 @@ pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<StatsRespon
|
||||
}))
|
||||
}
|
||||
|
||||
/// Ambient context inputs resolved from the store + global defaults for one
|
||||
/// turn: the human speaker name, the static sections and the session notepad.
|
||||
/// Bundled so `build_request` stays within the argument-count lint.
|
||||
struct Ambient<'a> {
|
||||
user_name: &'a str,
|
||||
sections: &'a [ContextSection],
|
||||
notepad: &'a [NotepadEntry],
|
||||
}
|
||||
|
||||
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
|
||||
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
|
||||
fn build_request(
|
||||
@@ -261,11 +305,18 @@ fn build_request(
|
||||
body: &SessionChat,
|
||||
extra: &str,
|
||||
images: &[serde_json::Value],
|
||||
user_name: &str,
|
||||
sections: &[ContextSection],
|
||||
ambient: Ambient<'_>,
|
||||
) -> ChatRequest {
|
||||
let user_content = format!("{}{}", body.content, extra);
|
||||
let messages = context::compose(sess, history, &user_content, images, user_name, sections);
|
||||
let messages = context::compose(
|
||||
sess,
|
||||
history,
|
||||
&user_content,
|
||||
images,
|
||||
ambient.user_name,
|
||||
ambient.sections,
|
||||
ambient.notepad,
|
||||
);
|
||||
ChatRequest {
|
||||
model: sess.model.clone(),
|
||||
messages,
|
||||
@@ -424,12 +475,51 @@ pub(crate) async fn session_chat(
|
||||
Ok(v) => v,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
let notepad = match with_store(&st, {
|
||||
let id = id.clone();
|
||||
move |s| s.notepad(&id)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(v) => v,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
// Sliding DIALOG window: retain the most recent messages by COUNT (main area
|
||||
// + buffer headroom), with stepped eviction so the prefix stays byte-stable
|
||||
// for KV-cache reuse. Full history stays in SQLite; the agent pins what
|
||||
// matters in the notepad. A total-size (char/token) cut is deferred.
|
||||
let user_content = format!("{}{}", body.content, extra);
|
||||
let window_start = match with_store(&st, {
|
||||
let id = id.clone();
|
||||
move |s| s.window_start(&id)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(v) => v,
|
||||
Err(e) => return e.into_response(),
|
||||
};
|
||||
let sel = window::select(&history, window_start);
|
||||
if sel.start_id != window_start {
|
||||
let start_id = sel.start_id;
|
||||
let idc = id.clone();
|
||||
if let Err(e) = with_store(&st, move |s| s.set_window_start(&idc, start_id)).await {
|
||||
return e.into_response();
|
||||
}
|
||||
}
|
||||
let mut req = build_request(
|
||||
&sess, &history, &body, &extra, &images, &user_name, §ions,
|
||||
&sess,
|
||||
&history[sel.start..],
|
||||
&body,
|
||||
&extra,
|
||||
&images,
|
||||
Ambient {
|
||||
user_name: &user_name,
|
||||
sections: §ions,
|
||||
notepad: ¬epad,
|
||||
},
|
||||
);
|
||||
|
||||
// Persist the user turn (text + attachment context) before generating.
|
||||
let user_content = format!("{}{}", body.content, extra);
|
||||
if let Err(e) = with_store(&st, {
|
||||
let id = id.clone();
|
||||
move |s| {
|
||||
@@ -707,8 +797,19 @@ mod tests {
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
};
|
||||
let req = build_request(&sess, &[], &body, "", &[], "Federico", &[sp_section()]);
|
||||
// SYSTEM_PROMPT section wraps identity + session SP; DIALOG markers around turns.
|
||||
let req = build_request(
|
||||
&sess,
|
||||
&[],
|
||||
&body,
|
||||
"",
|
||||
&[],
|
||||
Ambient {
|
||||
user_name: "Federico",
|
||||
sections: &[sp_section()],
|
||||
notepad: &[],
|
||||
},
|
||||
);
|
||||
// SYSTEM_PROMPT section wraps identity + session SP; DIALOG opens (no closer).
|
||||
assert!(matches!(req.messages[0].role, Role::System));
|
||||
let t0 = req.messages[0].text().unwrap();
|
||||
assert!(t0.starts_with("<SYSTEM_PROMPT>"));
|
||||
@@ -716,15 +817,17 @@ mod tests {
|
||||
assert!(t0.contains("sii breve"));
|
||||
assert!(t0.ends_with("</SYSTEM_PROMPT>\n\n"));
|
||||
assert_eq!(req.messages[1].text().unwrap(), "<DIALOG>\n");
|
||||
let user = &req.messages[req.messages.len() - 2];
|
||||
let user = &req.messages[req.messages.len() - 1];
|
||||
assert!(matches!(user.role, Role::User));
|
||||
// The new user turn carries the human speaker tag.
|
||||
assert!(user.text().unwrap().starts_with("[SPEAKER: Federico - "));
|
||||
assert!(user.text().unwrap().ends_with("ciao"));
|
||||
assert_eq!(
|
||||
req.messages.last().unwrap().text().unwrap(),
|
||||
"\n</DIALOG>\n\n"
|
||||
);
|
||||
// DIALOG stays open: no moving </DIALOG> closer (it would break the
|
||||
// engine's prefix checkpoint every user turn).
|
||||
assert!(!req
|
||||
.messages
|
||||
.iter()
|
||||
.any(|m| m.text().unwrap_or("").contains("</DIALOG>")));
|
||||
}
|
||||
|
||||
fn sp_section() -> ContextSection {
|
||||
@@ -780,12 +883,23 @@ mod tests {
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
};
|
||||
let req = build_request(&sess, &history, &body, "", &[], "User", &[sp_section()]);
|
||||
// messages: [SYSTEM_PROMPT, <DIALOG>, user(hist), assistant(hist), user(new), </DIALOG>]
|
||||
let u = req.messages[2].text().unwrap();
|
||||
let req = build_request(
|
||||
&sess,
|
||||
&history,
|
||||
&body,
|
||||
"",
|
||||
&[],
|
||||
Ambient {
|
||||
user_name: "User",
|
||||
sections: &[sp_section()],
|
||||
notepad: &[],
|
||||
},
|
||||
);
|
||||
// messages: [SYSTEM_PROMPT, <DIALOG>, window-marker, user(hist), assistant(hist), user(new)]
|
||||
let u = req.messages[3].text().unwrap();
|
||||
assert!(u.starts_with("[SPEAKER: User - "));
|
||||
assert!(u.ends_with("domanda"));
|
||||
let a = req.messages[3].text().unwrap();
|
||||
let a = req.messages[4].text().unwrap();
|
||||
assert!(a.starts_with("[SPEAKER: Nebula - "));
|
||||
assert!(a.ends_with("risposta"));
|
||||
}
|
||||
@@ -822,8 +936,19 @@ mod tests {
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
};
|
||||
let req = build_request(&sess, &history, &body, "", &[], "User", &[sp_section()]);
|
||||
let a = req.messages[2].text().unwrap();
|
||||
let req = build_request(
|
||||
&sess,
|
||||
&history,
|
||||
&body,
|
||||
"",
|
||||
&[],
|
||||
Ambient {
|
||||
user_name: "User",
|
||||
sections: &[sp_section()],
|
||||
notepad: &[],
|
||||
},
|
||||
);
|
||||
let a = req.messages[3].text().unwrap();
|
||||
assert_eq!(a.matches("[SPEAKER:").count(), 1, "exactly one tag: {a}");
|
||||
assert!(a.ends_with("risposta"));
|
||||
}
|
||||
@@ -857,7 +982,18 @@ mod tests {
|
||||
position: 1,
|
||||
},
|
||||
];
|
||||
let req = build_request(&sess, &[], &body, "", &[], "User", §ions);
|
||||
let req = build_request(
|
||||
&sess,
|
||||
&[],
|
||||
&body,
|
||||
"",
|
||||
&[],
|
||||
Ambient {
|
||||
user_name: "User",
|
||||
sections: §ions,
|
||||
notepad: &[],
|
||||
},
|
||||
);
|
||||
assert!(req.messages[0]
|
||||
.text()
|
||||
.unwrap()
|
||||
@@ -871,9 +1007,11 @@ mod tests {
|
||||
"<TOOL_USE>\nmanuale\n</TOOL_USE>\n\n"
|
||||
);
|
||||
assert_eq!(req.messages[2].text().unwrap(), "<DIALOG>\n");
|
||||
assert_eq!(
|
||||
req.messages.last().unwrap().text().unwrap(),
|
||||
"\n</DIALOG>\n\n"
|
||||
);
|
||||
// The new user turn is last; DIALOG is left open (no moving closer).
|
||||
assert!(matches!(req.messages.last().unwrap().role, Role::User));
|
||||
assert!(!req
|
||||
.messages
|
||||
.iter()
|
||||
.any(|m| m.text().unwrap_or("").contains("</DIALOG>")));
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,10 @@ pub struct Usage {
|
||||
/// Engine decode time (ms), when reported.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub decode_ms: Option<f64>,
|
||||
/// Prompt tokens served from the engine's conversation cache (`RESUME`),
|
||||
/// not re-prefilled. Non-standard extra; the GUI shows it to gauge reuse.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cached_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
impl Usage {
|
||||
@@ -167,6 +171,7 @@ impl Usage {
|
||||
total_tokens: prompt_tokens + completion_tokens,
|
||||
prompt_ms: None,
|
||||
decode_ms: None,
|
||||
cached_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,6 +181,13 @@ impl Usage {
|
||||
self.decode_ms = decode_ms.filter(|v| *v > 0.0);
|
||||
self
|
||||
}
|
||||
|
||||
/// Attach the engine's cache-hit count (`RESUME`): prompt tokens reused from
|
||||
/// the conversation cache instead of re-prefilled. 0 -> absent.
|
||||
pub fn with_cached(mut self, cached: u32) -> Self {
|
||||
self.cached_tokens = (cached > 0).then_some(cached);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Why generation stopped (OpenAI spelling).
|
||||
|
||||
+154
-28
@@ -1,14 +1,15 @@
|
||||
//! The context compositor: assembles the model prompt from named sections.
|
||||
//!
|
||||
//! Static sections (`SYSTEM_PROMPT`, `TOOL_USE`, …) live in the store and are
|
||||
//! emitted wrapped in `<NAME>…</NAME>`; the interactive `DIALOG` region wraps the
|
||||
//! real role messages (history + new turn) so the engine keeps its turn structure.
|
||||
//! emitted wrapped in `<NAME>…</NAME>`; the interactive `DIALOG` region is an open
|
||||
//! tail (opener `<DIALOG>`, no moving closer) around the real role messages, so the
|
||||
//! engine keeps its turn structure and the prompt prefix stays stable for KV reuse.
|
||||
//! Per-turn `[SPEAKER]` provenance and the server-local stamp are applied here,
|
||||
//! prompt-only (stored content stays clean). Adding a section = adding a store row.
|
||||
|
||||
use crate::api::types::{now_unix, ChatMessage, Role};
|
||||
use crate::i18n::t;
|
||||
use crate::store::{ContextSection, Session, StoredMessage};
|
||||
use crate::store::{ContextSection, NotepadEntry, Session, StoredMessage};
|
||||
|
||||
/// Compose the full context message list: static sections, then the DIALOG region.
|
||||
/// `user_content` is the new turn's typed text plus attachment context.
|
||||
@@ -19,34 +20,23 @@ pub fn compose(
|
||||
images: &[serde_json::Value],
|
||||
user_name: &str,
|
||||
sections: &[ContextSection],
|
||||
notepad: &[NotepadEntry],
|
||||
) -> Vec<ChatMessage> {
|
||||
let mut messages = Vec::new();
|
||||
// Server-local timezone offset, computed once for every turn in this request.
|
||||
let tz_offset = server_utc_offset_secs();
|
||||
// Structural identity reminder (name + personal folder) and the speaker
|
||||
// convention are injected into the SYSTEM_PROMPT template via placeholders.
|
||||
let mut identity = t("identity.name", &[("name", &sess.title)]);
|
||||
if let Some(folder) = &sess.folder {
|
||||
identity.push_str(&t("identity.folder", &[("folder", folder)]));
|
||||
}
|
||||
let speaker_note = t("speaker.note", &[]);
|
||||
let session_prompt = sess.settings.system_prompt.clone().unwrap_or_default();
|
||||
// Static context sections live in the store (editable without recompiling);
|
||||
// each is emitted as a system message wrapped in its own <NAME> tag.
|
||||
for sec in sections {
|
||||
let rendered = sec
|
||||
.content
|
||||
.replace("{identity}", &identity)
|
||||
.replace("{speaker_note}", &speaker_note)
|
||||
.replace("{session_prompt}", &session_prompt);
|
||||
messages.push(text_message(
|
||||
Role::System,
|
||||
format!("<{}>\n{}\n</{}>\n\n", sec.name, rendered, sec.name),
|
||||
));
|
||||
}
|
||||
// The interactive region is its own section: opener/closer markers around the
|
||||
// real role messages, which keep the engine's turn structure intact.
|
||||
// Pinned prefix: static sections + notepad, always present above the window.
|
||||
let mut messages = pinned_messages(sess, sections, notepad);
|
||||
// The interactive region opens with <DIALOG> and is left OPEN: a trailing
|
||||
// </DIALOG> after the last user turn would move every turn and break the
|
||||
// engine's prefix checkpoint (RESUME 0). Role messages keep turn structure.
|
||||
messages.push(text_message(Role::System, "<DIALOG>\n".to_string()));
|
||||
// Static sliding-window marker: tells the model this is a window (older turns
|
||||
// omitted), so it doesn't mistake the first visible turn for the chat's first
|
||||
// message. STATIC text (no counts) -> stable prefix, cache-safe.
|
||||
messages.push(text_message(
|
||||
Role::System,
|
||||
format!("{}\n\n", t("dialog.window_note", &[])),
|
||||
));
|
||||
for m in history {
|
||||
// Per-turn provenance for the model: [SPEAKER: name - datetime]. The
|
||||
// human uses the global user name; the assistant uses the session name.
|
||||
@@ -94,7 +84,46 @@ pub fn compose(
|
||||
reasoning_content: None,
|
||||
});
|
||||
}
|
||||
messages.push(text_message(Role::System, "\n</DIALOG>\n\n".to_string()));
|
||||
messages
|
||||
}
|
||||
|
||||
/// The pinned prefix: static sections (placeholders rendered) + the notepad
|
||||
/// block. Always present above the sliding DIALOG window. Extracted from
|
||||
/// `compose` so the pinned prefix is a single reusable unit.
|
||||
pub fn pinned_messages(
|
||||
sess: &Session,
|
||||
sections: &[ContextSection],
|
||||
notepad: &[NotepadEntry],
|
||||
) -> Vec<ChatMessage> {
|
||||
let mut messages = Vec::new();
|
||||
let mut identity = t("identity.name", &[("name", &sess.title)]);
|
||||
if let Some(folder) = &sess.folder {
|
||||
identity.push_str(&t("identity.folder", &[("folder", folder)]));
|
||||
}
|
||||
let speaker_note = t("speaker.note", &[]);
|
||||
let session_prompt = sess.settings.system_prompt.clone().unwrap_or_default();
|
||||
for sec in sections {
|
||||
let rendered = sec
|
||||
.content
|
||||
.replace("{identity}", &identity)
|
||||
.replace("{speaker_note}", &speaker_note)
|
||||
.replace("{session_prompt}", &session_prompt);
|
||||
messages.push(text_message(
|
||||
Role::System,
|
||||
format!("<{}>\n{}\n</{}>\n\n", sec.name, rendered, sec.name),
|
||||
));
|
||||
}
|
||||
if !notepad.is_empty() {
|
||||
let body = notepad
|
||||
.iter()
|
||||
.map(|e| format!("{}: {}", e.key, e.text.replace('\n', " ")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
messages.push(text_message(
|
||||
Role::System,
|
||||
format!("<NOTEPAD>\n{body}\n</NOTEPAD>\n\n"),
|
||||
));
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
@@ -259,4 +288,101 @@ mod tests {
|
||||
assert_eq!(parse_utc_offset("+0000"), Some(0));
|
||||
assert_eq!(parse_utc_offset("nope"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_places_notepad_above_dialog() {
|
||||
let sess = Session {
|
||||
id: "s".into(),
|
||||
title: "Nebula".into(),
|
||||
model: "m".into(),
|
||||
settings: crate::store::SessionSettings::default(),
|
||||
name_locked: true,
|
||||
folder: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
};
|
||||
let sections = vec![ContextSection {
|
||||
name: "TOOL_USE".into(),
|
||||
content: "manuale".into(),
|
||||
position: 1,
|
||||
}];
|
||||
let notepad = vec![
|
||||
NotepadEntry {
|
||||
key: "goal".into(),
|
||||
text: "ship it".into(),
|
||||
updated_at: 0,
|
||||
},
|
||||
NotepadEntry {
|
||||
key: "state".into(),
|
||||
text: "coding\nnow".into(),
|
||||
updated_at: 0,
|
||||
},
|
||||
];
|
||||
let texts = |msgs: Vec<ChatMessage>| -> Vec<String> {
|
||||
msgs.iter()
|
||||
.map(|m| {
|
||||
m.content
|
||||
.as_ref()
|
||||
.and_then(|c| c.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let t = texts(compose(
|
||||
&sess,
|
||||
&[],
|
||||
"ciao",
|
||||
&[],
|
||||
"Federico",
|
||||
§ions,
|
||||
¬epad,
|
||||
));
|
||||
let tool = t.iter().position(|x| x.starts_with("<TOOL_USE>")).unwrap();
|
||||
let np = t.iter().position(|x| x.starts_with("<NOTEPAD>")).unwrap();
|
||||
let dlg = t.iter().position(|x| x == "<DIALOG>\n").unwrap();
|
||||
assert!(
|
||||
tool < np && np < dlg,
|
||||
"notepad must sit between TOOL_USE and DIALOG"
|
||||
);
|
||||
assert!(t[np].contains("goal: ship it"));
|
||||
assert!(t[np].contains("state: coding now")); // newline normalized to one line
|
||||
assert!(t[np].ends_with("</NOTEPAD>\n\n"));
|
||||
// Empty notepad emits no section.
|
||||
let t2 = texts(compose(&sess, &[], "ciao", &[], "Federico", §ions, &[]));
|
||||
assert!(!t2.iter().any(|x| x.starts_with("<NOTEPAD>")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_window_marker_is_static() {
|
||||
let sess = Session {
|
||||
id: "s".into(),
|
||||
title: "Nebula".into(),
|
||||
model: "m".into(),
|
||||
settings: crate::store::SessionSettings::default(),
|
||||
name_locked: true,
|
||||
folder: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
};
|
||||
let sections = vec![ContextSection {
|
||||
name: "TOOL_USE".into(),
|
||||
content: "manuale".into(),
|
||||
position: 1,
|
||||
}];
|
||||
let a = compose(&sess, &[], "ciao", &[], "Federico", §ions, &[]);
|
||||
let b = compose(&sess, &[], "altro turno", &[], "Federico", §ions, &[]);
|
||||
let da = a
|
||||
.iter()
|
||||
.position(|m| m.text().unwrap_or("") == "<DIALOG>\n")
|
||||
.unwrap();
|
||||
let db = b
|
||||
.iter()
|
||||
.position(|m| m.text().unwrap_or("") == "<DIALOG>\n")
|
||||
.unwrap();
|
||||
// A static system marker sits right after the opener, identical across turns.
|
||||
assert!(matches!(a[da + 1].role, Role::System));
|
||||
assert!(a[da + 1].text().unwrap().ends_with("\n\n"));
|
||||
assert_eq!(a[da + 1].text().unwrap(), b[db + 1].text().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
//! a swappable `Store` trait).
|
||||
//! - [`render`]: safe Markdown + LaTeX → HTML for assistant messages.
|
||||
//! - [`context`]: the context compositor (named sections + DIALOG) for the prompt.
|
||||
//! - [`window`]: the sliding DIALOG window (token budget, stepped KV-cache eviction).
|
||||
|
||||
pub mod agent;
|
||||
pub mod api;
|
||||
@@ -18,3 +19,4 @@ pub mod inkling;
|
||||
pub mod name;
|
||||
pub mod render;
|
||||
pub mod store;
|
||||
pub mod window;
|
||||
+218
-2
@@ -14,7 +14,7 @@ use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A session's own settings instance. Global defaults are only a *template*:
|
||||
@@ -128,6 +128,11 @@ pub struct Stats {
|
||||
pub prompt_tokens: u64,
|
||||
pub completion_tokens: u64,
|
||||
pub total_tokens: u64,
|
||||
/// Current inference context: prompt tokens of the most recent assistant
|
||||
/// turn (the actual prompt last sent to the engine). Unlike `prompt_tokens`
|
||||
/// — a cumulative sum that re-counts the whole window every turn — this is
|
||||
/// the size of the context we are actually sending to inference now.
|
||||
pub last_prompt_tokens: u64,
|
||||
/// Tool calls requested across all assistant turns (agent activity).
|
||||
pub tool_calls: u64,
|
||||
/// Per-session breakdown, busiest (most tokens) first.
|
||||
@@ -182,10 +187,22 @@ pub struct ContextSection {
|
||||
pub position: i64,
|
||||
}
|
||||
|
||||
/// One labelled entry of a session's persistent notepad: a stable `key` the
|
||||
/// agent addresses (upsert/remove) and a short `text`. Per-session; injected as
|
||||
/// the pinned <NOTEPAD> section above DIALOG, ordered by key for a deterministic
|
||||
/// block. Nothing is evicted automatically — the agent curates it.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct NotepadEntry {
|
||||
pub key: String,
|
||||
pub text: String,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
/// Bootstrap templates for the static context sections (seeded once into SQLite;
|
||||
/// the DB rows are the source of truth afterwards).
|
||||
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
|
||||
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
|
||||
const TOOL_USE_SECTION_PRE_NOTEPAD: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
|
||||
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi.";
|
||||
|
||||
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
|
||||
pub trait Store: Send + Sync {
|
||||
@@ -201,8 +218,15 @@ pub trait Store: Send + Sync {
|
||||
fn update_settings(&self, id: &str, settings: &SessionSettings) -> Result<()>;
|
||||
fn set_name_locked(&self, id: &str, locked: bool) -> Result<()>;
|
||||
fn set_folder(&self, id: &str, folder: &str) -> Result<()>;
|
||||
/// First retained history message id for the sliding DIALOG window (0 = all).
|
||||
fn window_start(&self, id: &str) -> Result<i64>;
|
||||
fn set_window_start(&self, id: &str, start: i64) -> Result<()>;
|
||||
fn delete_session(&self, id: &str) -> Result<()>;
|
||||
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
|
||||
/// The GUI's sliding-window view: messages at/after `start_id` (the persisted
|
||||
/// window start) plus the total stored message count. Filtered in SQL so a
|
||||
/// months-long history is never loaded whole just to render the recent window.
|
||||
fn message_window(&self, session_id: &str, start_id: i64) -> Result<(Vec<StoredMessage>, u64)>;
|
||||
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>;
|
||||
fn stats(&self) -> Result<Stats>;
|
||||
/// The global default settings template (None until seeded).
|
||||
@@ -211,6 +235,14 @@ pub trait Store: Send + Sync {
|
||||
/// The static context sections, ordered (SYSTEM_PROMPT, TOOL_USE, ...).
|
||||
fn context_sections(&self) -> Result<Vec<ContextSection>>;
|
||||
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()>;
|
||||
/// The session's notepad entries, ordered by key (deterministic block).
|
||||
fn notepad(&self, session_id: &str) -> Result<Vec<NotepadEntry>>;
|
||||
/// Create or update (upsert) the entry labelled `key`.
|
||||
fn set_notepad_entry(&self, session_id: &str, key: &str, text: &str) -> Result<()>;
|
||||
/// Remove the entry `key`; returns whether it existed.
|
||||
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool>;
|
||||
/// Empty the session's notepad.
|
||||
fn clear_notepad(&self, session_id: &str) -> Result<()>;
|
||||
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
|
||||
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
|
||||
}
|
||||
@@ -242,6 +274,7 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
settings_json TEXT,
|
||||
name_locked INTEGER NOT NULL DEFAULT 0,
|
||||
folder TEXT,
|
||||
window_start INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
@@ -276,6 +309,13 @@ CREATE TABLE IF NOT EXISTS context_sections (
|
||||
content TEXT NOT NULL,
|
||||
position INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS notepad_entries (
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
key TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (session_id, key)
|
||||
);
|
||||
";
|
||||
|
||||
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
|
||||
@@ -351,6 +391,11 @@ fn migrate(conn: &Connection) -> Result<()> {
|
||||
if !has_col("sessions", "folder")? {
|
||||
conn.execute_batch("ALTER TABLE sessions ADD COLUMN folder TEXT;")?;
|
||||
}
|
||||
if !has_col("sessions", "window_start")? {
|
||||
conn.execute_batch(
|
||||
"ALTER TABLE sessions ADD COLUMN window_start INTEGER NOT NULL DEFAULT 0;",
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -365,6 +410,12 @@ fn seed_context_sections(conn: &Connection) -> Result<()> {
|
||||
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
|
||||
params![TOOL_USE_SECTION],
|
||||
)?;
|
||||
// Refresh an untouched pre-notepad TOOL_USE row so the notepad manual reaches
|
||||
// existing databases; a user-edited row (content differs) is left alone.
|
||||
conn.execute(
|
||||
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
|
||||
params![TOOL_USE_SECTION, TOOL_USE_SECTION_PRE_NOTEPAD],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -472,6 +523,27 @@ impl Store for SqliteStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn window_start(&self, id: &str) -> Result<i64> {
|
||||
let conn = self.lock();
|
||||
let v = conn
|
||||
.query_row(
|
||||
"SELECT window_start FROM sessions WHERE id = ?1",
|
||||
params![id],
|
||||
|r| r.get::<_, i64>(0),
|
||||
)
|
||||
.optional()?;
|
||||
Ok(v.unwrap_or(0))
|
||||
}
|
||||
|
||||
fn set_window_start(&self, id: &str, start: i64) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"UPDATE sessions SET window_start = ?2 WHERE id = ?1",
|
||||
params![id, start],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_session(&self, id: &str) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
|
||||
@@ -498,6 +570,32 @@ impl Store for SqliteStore {
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
fn message_window(&self, session_id: &str, start_id: i64) -> Result<(Vec<StoredMessage>, u64)> {
|
||||
let conn = self.lock();
|
||||
let total: i64 = conn.query_row(
|
||||
"SELECT COUNT(*) FROM messages WHERE session_id = ?1",
|
||||
params![session_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT * FROM messages WHERE session_id = ?1 AND id >= ?2 ORDER BY id ASC")?;
|
||||
let rows = stmt.query_map(params![session_id, start_id], |row| {
|
||||
Ok(StoredMessage {
|
||||
id: row.get("id")?,
|
||||
role: row.get("role")?,
|
||||
content: row.get("content")?,
|
||||
reasoning_content: row.get("reasoning_content")?,
|
||||
tool_calls_json: row.get("tool_calls_json")?,
|
||||
tool_call_id: row.get("tool_call_id")?,
|
||||
prompt_tokens: row.get::<_, i64>("prompt_tokens")? as u32,
|
||||
completion_tokens: row.get::<_, i64>("completion_tokens")? as u32,
|
||||
created_at: row.get("created_at")?,
|
||||
})
|
||||
})?;
|
||||
let msgs = rows.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok((msgs, total as u64))
|
||||
}
|
||||
|
||||
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage> {
|
||||
let now = now_secs();
|
||||
let conn = self.lock();
|
||||
@@ -552,6 +650,21 @@ impl Store for SqliteStore {
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)?;
|
||||
|
||||
// Current context = the prompt of the latest assistant turn (the size
|
||||
// actually sent to inference last). The cumulative SUM(prompt_tokens)
|
||||
// above re-counts the whole retained window every turn, so it is NOT
|
||||
// the context size; this single latest value is.
|
||||
let last_prompt: i64 = conn
|
||||
.query_row(
|
||||
"SELECT prompt_tokens FROM messages
|
||||
WHERE role = 'assistant' AND prompt_tokens > 0
|
||||
ORDER BY id DESC LIMIT 1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?
|
||||
.unwrap_or(0);
|
||||
|
||||
// Per-session breakdown (LEFT JOIN keeps empty sessions visible), busiest first.
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT s.id, s.title, COUNT(m.id),
|
||||
@@ -599,6 +712,7 @@ impl Store for SqliteStore {
|
||||
prompt_tokens: prompt as u64,
|
||||
completion_tokens: completion as u64,
|
||||
total_tokens: (prompt + completion) as u64,
|
||||
last_prompt_tokens: last_prompt as u64,
|
||||
tool_calls: tool_calls as u64,
|
||||
by_session,
|
||||
daily,
|
||||
@@ -649,6 +763,49 @@ impl Store for SqliteStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn notepad(&self, session_id: &str) -> Result<Vec<NotepadEntry>> {
|
||||
let conn = self.lock();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT key, text, updated_at FROM notepad_entries WHERE session_id = ?1 ORDER BY key ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map(params![session_id], |r| {
|
||||
Ok(NotepadEntry {
|
||||
key: r.get(0)?,
|
||||
text: r.get(1)?,
|
||||
updated_at: r.get(2)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
fn set_notepad_entry(&self, session_id: &str, key: &str, text: &str) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"INSERT INTO notepad_entries (session_id, key, text, updated_at) VALUES (?1, ?2, ?3, ?4)
|
||||
ON CONFLICT(session_id, key) DO UPDATE SET text = ?3, updated_at = ?4",
|
||||
params![session_id, key, text, now_secs()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool> {
|
||||
let conn = self.lock();
|
||||
let n = conn.execute(
|
||||
"DELETE FROM notepad_entries WHERE session_id = ?1 AND key = ?2",
|
||||
params![session_id, key],
|
||||
)?;
|
||||
Ok(n > 0)
|
||||
}
|
||||
|
||||
fn clear_notepad(&self, session_id: &str) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"DELETE FROM notepad_entries WHERE session_id = ?1",
|
||||
params![session_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
@@ -753,6 +910,7 @@ mod tests {
|
||||
assert_eq!(stats.messages, 2);
|
||||
assert_eq!(stats.prompt_tokens, 6);
|
||||
assert_eq!(stats.completion_tokens, 5);
|
||||
assert_eq!(stats.last_prompt_tokens, 3); // latest assistant turn, not the sum
|
||||
|
||||
s.delete_session(&sess.id).unwrap();
|
||||
assert!(s.messages(&sess.id).unwrap().is_empty()); // cascade
|
||||
@@ -802,6 +960,9 @@ mod tests {
|
||||
assert_eq!(st.prompt_tokens, 24);
|
||||
assert_eq!(st.completion_tokens, 5);
|
||||
assert_eq!(st.total_tokens, 29);
|
||||
// Current context tracks the latest assistant turn (Beta, pt=2), not
|
||||
// the cumulative prompt sum (24) which re-counts every turn's window.
|
||||
assert_eq!(st.last_prompt_tokens, 2);
|
||||
assert_eq!(st.tool_calls, 2); // two calls inside Alpha's single turn
|
||||
// Busiest first: Alpha (24 tokens) ahead of Beta (5).
|
||||
assert_eq!(st.by_session.len(), 2);
|
||||
@@ -907,6 +1068,7 @@ mod tests {
|
||||
};
|
||||
assert_eq!(has("settings_json"), 1);
|
||||
assert_eq!(has("name_locked"), 1);
|
||||
assert_eq!(has("window_start"), 1);
|
||||
// The old system_prompt was backfilled into the settings instance.
|
||||
let sj: String = conn
|
||||
.query_row(
|
||||
@@ -919,4 +1081,58 @@ mod tests {
|
||||
// Idempotent: running again does not error.
|
||||
migrate(&conn).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notepad_upsert_remove_clear_and_cascade() {
|
||||
let s = store();
|
||||
let sess = s
|
||||
.create_session("Chat", "m", &SessionSettings::default())
|
||||
.unwrap();
|
||||
assert!(s.notepad(&sess.id).unwrap().is_empty());
|
||||
s.set_notepad_entry(&sess.id, "goal", "ship the notepad")
|
||||
.unwrap();
|
||||
s.set_notepad_entry(&sess.id, "state", "coding").unwrap();
|
||||
// Upsert by key replaces, does not duplicate.
|
||||
s.set_notepad_entry(&sess.id, "goal", "ship + dogfood")
|
||||
.unwrap();
|
||||
let np = s.notepad(&sess.id).unwrap();
|
||||
assert_eq!(np.len(), 2);
|
||||
assert_eq!(np[0].key, "goal"); // ordered by key
|
||||
assert_eq!(np[0].text, "ship + dogfood");
|
||||
assert_eq!(np[1].key, "state");
|
||||
assert!(s.remove_notepad_entry(&sess.id, "state").unwrap());
|
||||
assert!(!s.remove_notepad_entry(&sess.id, "state").unwrap());
|
||||
assert_eq!(s.notepad(&sess.id).unwrap().len(), 1);
|
||||
s.clear_notepad(&sess.id).unwrap();
|
||||
assert!(s.notepad(&sess.id).unwrap().is_empty());
|
||||
// Per-session isolation + cascade on delete.
|
||||
s.set_notepad_entry(&sess.id, "k", "v").unwrap();
|
||||
let other = s
|
||||
.create_session("Other", "m", &SessionSettings::default())
|
||||
.unwrap();
|
||||
assert!(s.notepad(&other.id).unwrap().is_empty());
|
||||
s.delete_session(&sess.id).unwrap();
|
||||
assert!(s.notepad(&sess.id).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_use_section_includes_notepad_manual() {
|
||||
let s = store();
|
||||
let secs = s.context_sections().unwrap();
|
||||
let tool_use = secs.iter().find(|x| x.name == "TOOL_USE").unwrap();
|
||||
assert!(tool_use.content.contains("notepad("));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_start_default_and_roundtrip() {
|
||||
let s = store();
|
||||
let sess = s
|
||||
.create_session("Chat", "m", &SessionSettings::default())
|
||||
.unwrap();
|
||||
assert_eq!(s.window_start(&sess.id).unwrap(), 0);
|
||||
s.set_window_start(&sess.id, 42).unwrap();
|
||||
assert_eq!(s.window_start(&sess.id).unwrap(), 42);
|
||||
// Missing session -> 0, no panic.
|
||||
assert_eq!(s.window_start("nope").unwrap(), 0);
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
//! The sliding DIALOG window: retains the most recent messages by COUNT, with
|
||||
//! stepped (hysteresis) eviction so the retained prefix stays byte-stable across
|
||||
//! turns for engine KV-cache reuse.
|
||||
//!
|
||||
//! Two tiers, in messages: a MAIN area of the most recent turns always retained,
|
||||
//! plus a BUFFER of headroom above it. Between evictions the window is append-only
|
||||
//! (new turns join the tail) while the buffer fills, so the prompt prefix is
|
||||
//! identical turn-to-turn and the engine reuses its cached KV. When occupancy
|
||||
//! crosses MAIN + BUFFER the buffer is cleared: the start advances in chunks to
|
||||
//! USER-message boundaries (never splitting a tool_call/tool_result exchange)
|
||||
//! down to MAIN, and a new buffer starts filling. This amortizes one re-prefill
|
||||
//! over several turns. The full history is never deleted — evicted turns stay
|
||||
//! recallable from the store, and the agent pins what matters in the notepad.
|
||||
//!
|
||||
//! A total-SIZE (char/token) cut is deliberately deferred: it interacts with the
|
||||
//! stepped anchor and is not as simple as adding a second cap.
|
||||
|
||||
use crate::store::StoredMessage;
|
||||
|
||||
/// Main dialogic area: the most recent messages always retained. This is the
|
||||
/// low-water mark the window drops to after an eviction.
|
||||
pub const MAIN_AREA: usize = 40;
|
||||
/// Buffer headroom above the main area. While the retained count is at most
|
||||
/// MAIN_AREA + BUFFER the window is append-only; crossing it clears the buffer
|
||||
/// (evict down to MAIN_AREA) and starts a new one.
|
||||
pub const BUFFER: usize = 10;
|
||||
|
||||
/// The window selection: where the retained history suffix begins.
|
||||
pub struct Selection {
|
||||
/// Index into `history` where the retained suffix starts.
|
||||
pub start: usize,
|
||||
/// Message id to persist as the session's window start (a user-turn id).
|
||||
pub start_id: i64,
|
||||
}
|
||||
|
||||
/// Select the retained history suffix by message count: keep the most recent
|
||||
/// MAIN_AREA messages, allowing BUFFER headroom to accumulate append-only before
|
||||
/// a stepped eviction. `window_start` is the persisted first-retained message id
|
||||
/// (0 = from the beginning).
|
||||
pub fn select(history: &[StoredMessage], window_start: i64) -> Selection {
|
||||
if history.is_empty() {
|
||||
return Selection {
|
||||
start: 0,
|
||||
start_id: window_start.max(0),
|
||||
};
|
||||
}
|
||||
let cost = |s: usize| history[s..].len();
|
||||
// Current start: first message at/after the persisted window start.
|
||||
let mut start = history
|
||||
.iter()
|
||||
.position(|m| m.id >= window_start)
|
||||
.unwrap_or(0);
|
||||
// Append-only while the buffer has room: the prefix stays stable (KV hit).
|
||||
if cost(start) <= MAIN_AREA + BUFFER {
|
||||
return Selection {
|
||||
start,
|
||||
start_id: history[start].id,
|
||||
};
|
||||
}
|
||||
// Buffer full: clear it down to the main area, advancing to successive
|
||||
// user-turn boundaries. Never split an exchange; always keep at least the
|
||||
// most recent user-initiated turn.
|
||||
let last_user = history
|
||||
.iter()
|
||||
.rposition(|m| m.role == "user")
|
||||
.unwrap_or(start);
|
||||
while start < last_user && cost(start) > MAIN_AREA {
|
||||
match history[start + 1..].iter().position(|m| m.role == "user") {
|
||||
Some(off) => start += off + 1,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
Selection {
|
||||
start,
|
||||
start_id: history[start].id,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn msg(id: i64, role: &str) -> StoredMessage {
|
||||
StoredMessage {
|
||||
id,
|
||||
role: role.into(),
|
||||
content: "x".into(),
|
||||
reasoning_content: None,
|
||||
tool_calls_json: None,
|
||||
tool_call_id: None,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
created_at: id,
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` messages, ids 1..=n, alternating user (odd) / assistant (even).
|
||||
fn exchanges(n: usize) -> Vec<StoredMessage> {
|
||||
(1..=n as i64)
|
||||
.map(|id| msg(id, if id % 2 == 1 { "user" } else { "assistant" }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn under_trigger_is_append_only() {
|
||||
let h = exchanges(10);
|
||||
let sel = select(&h, 0);
|
||||
assert_eq!(sel.start, 0);
|
||||
assert_eq!(sel.start_id, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_fills_then_clears_to_main() {
|
||||
// 51 messages > MAIN(40) + BUFFER(10) = 50 -> clear down to <= 40.
|
||||
let h = exchanges(51);
|
||||
let sel = select(&h, 0);
|
||||
assert_eq!(h[sel.start].role, "user");
|
||||
assert!(h[sel.start..].len() <= MAIN_AREA);
|
||||
assert!(sel.start > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eviction_snaps_to_user_boundary() {
|
||||
let h = exchanges(60);
|
||||
let sel = select(&h, 0);
|
||||
assert_eq!(h[sel.start].role, "user");
|
||||
// 60 - start <= 40 -> start >= 20; id 21 is a user turn.
|
||||
assert_eq!(sel.start, 20);
|
||||
assert_eq!(sel.start_id, 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_starts_mid_tool_exchange() {
|
||||
let mut h = exchanges(60);
|
||||
// Turn id 20 into an assistant tool_call and id 21 into its tool result,
|
||||
// so the cut must skip past them to the next user turn (id 23).
|
||||
h[19].role = "assistant".into();
|
||||
h[19].tool_calls_json = Some(r#"[{"id":"c1"}]"#.into());
|
||||
h[20].role = "tool".into();
|
||||
let sel = select(&h, 0);
|
||||
assert_eq!(h[sel.start].role, "user");
|
||||
assert_eq!(sel.start_id, 23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_start_is_respected_append_only() {
|
||||
let h = exchanges(10);
|
||||
// window_start = 7 retains ids 7..10 (4 messages) <= 50 -> unchanged.
|
||||
let sel = select(&h, 7);
|
||||
assert_eq!(sel.start, 6);
|
||||
assert_eq!(sel.start_id, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_evicts_past_the_last_user_turn() {
|
||||
// 55 messages, user only at the very start and the very end: the guard
|
||||
// keeps the latest user turn even though dropping to MAIN would pass it.
|
||||
let mut h = exchanges(55);
|
||||
for m in h.iter_mut().take(54).skip(1) {
|
||||
m.role = "assistant".into();
|
||||
}
|
||||
let sel = select(&h, 0);
|
||||
assert_eq!(sel.start_id, 55);
|
||||
assert_eq!(h[sel.start].role, "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_history_is_safe() {
|
||||
let sel = select(&[], 7);
|
||||
assert_eq!(sel.start, 0);
|
||||
assert_eq!(sel.start_id, 7);
|
||||
}
|
||||
}
|
||||
+68
-7
@@ -15,7 +15,7 @@ use strata_ctl::api::service::ChatService;
|
||||
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
|
||||
use strata_ctl::api::{router_with_store, AuthConfig};
|
||||
use strata_ctl::engine::Engine;
|
||||
use strata_ctl::store::{SqliteStore, Store};
|
||||
use strata_ctl::store::{NewMessage, SqliteStore, Store};
|
||||
|
||||
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
|
||||
|
||||
@@ -143,8 +143,10 @@ async fn session_holds_context_and_persists_usage() {
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::OK);
|
||||
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(msgs.as_array().unwrap().len(), 2);
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
let msgs = v["messages"].as_array().unwrap();
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(v["total"], 2);
|
||||
assert_eq!(msgs[0]["role"], "user");
|
||||
assert_eq!(msgs[0]["content"], "hi");
|
||||
assert_eq!(msgs[1]["role"], "assistant");
|
||||
@@ -167,8 +169,10 @@ async fn session_holds_context_and_persists_usage() {
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(msgs.as_array().unwrap().len(), 4);
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
let msgs = v["messages"].as_array().unwrap();
|
||||
assert_eq!(msgs.len(), 4);
|
||||
assert_eq!(v["total"], 4);
|
||||
assert_eq!(msgs[2]["content"], "again");
|
||||
|
||||
// Stats aggregate across the session.
|
||||
@@ -232,12 +236,69 @@ async fn session_stream_persists_and_ends_with_done() {
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(msgs.as_array().unwrap().len(), 2);
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
let msgs = v["messages"].as_array().unwrap();
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[1]["content"], "efghi");
|
||||
assert_eq!(msgs[1]["completion_tokens"], 5);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn messages_endpoint_returns_only_the_sliding_window() {
|
||||
let (app, store) = build_app().await;
|
||||
let id = create_session(&app).await;
|
||||
// Seed a long history directly (60 messages, alternating user/assistant).
|
||||
for i in 0..60 {
|
||||
store
|
||||
.append_message(
|
||||
&id,
|
||||
NewMessage {
|
||||
role: if i % 2 == 0 { "user" } else { "assistant" },
|
||||
content: "x",
|
||||
reasoning_content: None,
|
||||
tool_calls_json: None,
|
||||
tool_call_id: None,
|
||||
prompt_tokens: 0,
|
||||
completion_tokens: 0,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// One chat turn runs window::select over the 60-message history and persists
|
||||
// the evicted start — the model's window. The GUI must see that same window.
|
||||
let (st, _) = req(
|
||||
&app,
|
||||
Method::POST,
|
||||
&format!("/api/sessions/{id}/chat"),
|
||||
Some(serde_json::json!({"content": "hi"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::OK);
|
||||
|
||||
let (_, text) = req(
|
||||
&app,
|
||||
Method::GET,
|
||||
&format!("/api/sessions/{id}/messages"),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
let msgs = v["messages"].as_array().unwrap();
|
||||
let total = v["total"].as_u64().unwrap();
|
||||
assert_eq!(total, 62); // 60 seeded + the new user + assistant turns
|
||||
// Bounded window (MAIN_AREA + BUFFER), never the whole history.
|
||||
assert!(
|
||||
msgs.len() <= 50,
|
||||
"window must be bounded, got {}",
|
||||
msgs.len()
|
||||
);
|
||||
assert!(msgs.len() < total as usize);
|
||||
// The window snaps to a user-turn boundary (never mid-exchange).
|
||||
assert_eq!(msgs[0]["role"], "user");
|
||||
// The full history is still in the store — nothing was deleted.
|
||||
assert_eq!(store.messages(&id).unwrap().len(), 62);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn gui_is_served_and_delete_cascades() {
|
||||
let (app, store) = build_app().await;
|
||||
|
||||
@@ -143,10 +143,12 @@ fn real_prompt_closes_sections_with_blank_line() {
|
||||
position: 1,
|
||||
},
|
||||
];
|
||||
let msgs = context::compose(&sess, &[], "ciao", &[], "Federico", §ions);
|
||||
let msgs = context::compose(&sess, &[], "ciao", &[], "Federico", §ions, &[]);
|
||||
let val = serde_json::to_value(&msgs).unwrap();
|
||||
let out = t.render(&val, None, Some("low")).unwrap();
|
||||
assert!(out.contains("</SYSTEM_PROMPT>\n\n"), "{out}");
|
||||
assert!(out.contains("</TOOL_USE>\n\n"), "{out}");
|
||||
assert!(out.contains("</DIALOG>"), "{out}");
|
||||
// DIALOG is an open tail: opener present, no moving closer (KV-cache prefix).
|
||||
assert!(out.contains("<DIALOG>"), "{out}");
|
||||
assert!(!out.contains("</DIALOG>"), "DIALOG must stay open: {out}");
|
||||
}
|
||||
+20
-1
@@ -121,6 +121,16 @@ body.resizing { cursor: col-resize; user-select: none; }
|
||||
}
|
||||
.empty { color: var(--muted); text-align: center; margin: auto; max-width: 28ch; }
|
||||
|
||||
/* Sliding-window banner: the browser shows the same recent window the model
|
||||
sees; older turns are preserved server-side. Sticky so it stays visible. */
|
||||
.window-note {
|
||||
position: sticky; top: 0; z-index: 1;
|
||||
max-width: 860px; width: 100%; margin: 0 auto;
|
||||
padding: 6px 12px; font-size: 0.75rem; color: var(--muted);
|
||||
background: var(--panel-2); border: 1px solid var(--border);
|
||||
border-radius: 8px; text-align: center;
|
||||
}
|
||||
|
||||
/* ---- Message bubbles ---- */
|
||||
.msg { max-width: 860px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; }
|
||||
.msg .role { font-size: 0.75rem; color: var(--muted); margin-bottom: 4px; }
|
||||
@@ -260,7 +270,7 @@ details.thinking .reasoning {
|
||||
.msg-attachments { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
|
||||
|
||||
/* ---- Stats modal ---- */
|
||||
#stats-modal, #dialog, #settings-modal {
|
||||
#stats-modal, #dialog, #settings-modal, #notepad-modal {
|
||||
position: fixed; inset: 0; z-index: 40;
|
||||
background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center;
|
||||
padding: 20px;
|
||||
@@ -380,6 +390,15 @@ details.thinking .reasoning {
|
||||
.field-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 12px; }
|
||||
.sess-btn:disabled { opacity: 0.35; cursor: default; }
|
||||
|
||||
/* ---- Notepad (read-only pinned entries, agent-managed) ---- */
|
||||
.notepad-card { width: min(560px, 100%); max-width: 560px; max-height: 85dvh; display: flex; flex-direction: column; padding: 0; overflow: hidden; }
|
||||
.notepad-card .stats-head h2 { flex: 1; }
|
||||
.notepad-hint { margin: 0; padding: 10px 18px 0; }
|
||||
.notepad-content { padding: 14px 18px 18px; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }
|
||||
.notepad-entry { display: flex; gap: 10px; align-items: baseline; padding: 8px 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--panel-2); }
|
||||
.notepad-key { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-weight: 600; color: var(--accent); flex: 0 0 auto; max-width: 42%; overflow-wrap: anywhere; }
|
||||
.notepad-text { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
|
||||
/* ---- Wide screens: persistent sidebar ---- */
|
||||
@media (min-width: 900px) {
|
||||
#drawer { position: static; transform: none; width: var(--sidebar-w); flex-shrink: 0; }
|
||||
|
||||
+80
-14
@@ -99,6 +99,7 @@ function usageText(u) {
|
||||
if (u.decode_ms > 0 && u.completion_tokens > 0) {
|
||||
s += " · " + t("stats.tps", { n: fmt1(u.completion_tokens / (u.decode_ms / 1000)) });
|
||||
}
|
||||
if (u.cached_tokens > 0) s += " · " + t("usage.cached", { n: fmtInt(u.cached_tokens) });
|
||||
if (u.prompt_ms > 0) s += " · " + t("usage.ttft", { n: fmtInt(u.prompt_ms / 1000) });
|
||||
return s;
|
||||
}
|
||||
@@ -169,32 +170,40 @@ function renderSessions() {
|
||||
}
|
||||
}
|
||||
|
||||
function renderTranscript(messages) {
|
||||
const t = $("#transcript");
|
||||
t.textContent = "";
|
||||
function renderTranscript(messages, win) {
|
||||
const tr = $("#transcript");
|
||||
tr.textContent = "";
|
||||
// The browser shows the SAME sliding window the model sees. When older turns
|
||||
// have slid out, say so: they are preserved server-side (full export later).
|
||||
if (win && win.total > messages.length) {
|
||||
tr.appendChild(el("div", "window-note", t("window.note", {
|
||||
shown: fmtInt(messages.length),
|
||||
omitted: fmtInt(win.total - messages.length),
|
||||
})));
|
||||
}
|
||||
if (!messages.length) {
|
||||
t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto."));
|
||||
tr.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto."));
|
||||
return;
|
||||
}
|
||||
for (const m of messages) {
|
||||
if (m.role === "user") {
|
||||
t.appendChild(messageNode("user", m.content, null, null, m.created_at));
|
||||
tr.appendChild(messageNode("user", m.content, null, null, m.created_at));
|
||||
} else if (m.role === "tool") {
|
||||
t.appendChild(toolResultNode(m.content));
|
||||
tr.appendChild(toolResultNode(m.content));
|
||||
} else if (m.role === "assistant") {
|
||||
if (m.tool_calls_json) {
|
||||
let calls = [];
|
||||
try { calls = JSON.parse(m.tool_calls_json); } catch { /* ignore */ }
|
||||
for (const tc of calls) {
|
||||
const f = tc.function || {};
|
||||
t.appendChild(toolCallNode(f.name, f.arguments));
|
||||
tr.appendChild(toolCallNode(f.name, f.arguments));
|
||||
}
|
||||
}
|
||||
if (m.content) {
|
||||
const usage = m.completion_tokens
|
||||
? usageText({ prompt_tokens: m.prompt_tokens, completion_tokens: m.completion_tokens })
|
||||
: null;
|
||||
t.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at, m.content_html));
|
||||
tr.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at, m.content_html));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -221,8 +230,8 @@ async function selectSession(id) {
|
||||
$("#session-title").textContent = sess ? sess.title : "Conversazione";
|
||||
$("#model-name").textContent = sess ? sess.model : "";
|
||||
renderSessions();
|
||||
const messages = await getJSON(`/api/sessions/${id}/messages`);
|
||||
renderTranscript(messages);
|
||||
const data = await getJSON(`/api/sessions/${id}/messages`);
|
||||
renderTranscript(data.messages, data);
|
||||
}
|
||||
|
||||
async function newSession() {
|
||||
@@ -512,6 +521,11 @@ function renderStats(s) {
|
||||
const perf = s.perf || {};
|
||||
const cards = el("div", "stat-cards");
|
||||
cards.appendChild(engineCard(s.engine || {}));
|
||||
// Current inference context (last turn's prompt) — distinct from the
|
||||
// cumulative token total below, which re-counts the window every turn.
|
||||
cards.appendChild(statCard(t("stats.context_now"),
|
||||
s.last_prompt_tokens ? fmtInt(s.last_prompt_tokens) : t("stats.na"),
|
||||
t("stats.context_now.sub")));
|
||||
const decode = perf.decode_tps != null ? t("stats.tps", { n: fmt1(perf.decode_tps) }) : t("stats.na");
|
||||
const decodeSub = perf.prefill_tps != null
|
||||
? t("stats.decode.sub") + " · " + t("stats.prefill", { n: fmt1(perf.prefill_tps) })
|
||||
@@ -637,6 +651,37 @@ function closeStats() {
|
||||
statsTimer = null;
|
||||
}
|
||||
|
||||
// ---- Notepad (read-only observability; the agent writes via the tool) ------
|
||||
async function showNotepad() {
|
||||
if (!currentSession()) return;
|
||||
$("#notepad-modal").hidden = false;
|
||||
await refreshNotepad();
|
||||
}
|
||||
|
||||
async function refreshNotepad() {
|
||||
const sess = currentSession();
|
||||
if (!sess) return;
|
||||
const root = $("#notepad-content");
|
||||
root.textContent = "";
|
||||
try {
|
||||
const entries = await getJSON(`/api/sessions/${sess.id}/notepad`);
|
||||
if (!entries.length) {
|
||||
root.appendChild(el("div", "empty", t("notepad.empty")));
|
||||
return;
|
||||
}
|
||||
for (const e of entries) {
|
||||
const row = el("div", "notepad-entry");
|
||||
row.appendChild(el("span", "notepad-key", e.key));
|
||||
row.appendChild(el("span", "notepad-text", e.text));
|
||||
root.appendChild(row);
|
||||
}
|
||||
} catch (err) {
|
||||
root.appendChild(el("div", "empty", t("notepad.error", { msg: err.message })));
|
||||
}
|
||||
}
|
||||
|
||||
function closeNotepad() { $("#notepad-modal").hidden = true; }
|
||||
|
||||
// ---- Settings (per-session instance or global defaults) -------------------
|
||||
let settingsScope = "session";
|
||||
let settingsBase = {};
|
||||
@@ -693,10 +738,23 @@ async function openSettings(scope) {
|
||||
$("#set-scope-general").classList.toggle("active", scope === "general");
|
||||
$("#settings-title").textContent =
|
||||
scope === "session" ? t("settings.title.session") : t("settings.title.general");
|
||||
settingsBase =
|
||||
scope === "session"
|
||||
? { ...(currentSession()?.settings || {}) }
|
||||
: await getJSON("/api/settings/defaults");
|
||||
if (scope === "session") {
|
||||
// Read the persisted instance fresh from the store, exactly like the general
|
||||
// scope does. The cached session list can be stale (e.g. a tab opened before
|
||||
// the last edit, or a general save that doesn't refresh sessions), which would
|
||||
// show an empty/outdated System Prompt and look like the note wasn't kept.
|
||||
const sess = currentSession();
|
||||
if (sess) {
|
||||
try {
|
||||
const fresh = await getJSON(`/api/sessions/${sess.id}`);
|
||||
const i = state.sessions.findIndex((s) => s.id === sess.id);
|
||||
if (i >= 0) state.sessions[i] = fresh;
|
||||
} catch { /* fall back to the cached instance */ }
|
||||
}
|
||||
settingsBase = { ...(currentSession()?.settings || {}) };
|
||||
} else {
|
||||
settingsBase = await getJSON("/api/settings/defaults");
|
||||
}
|
||||
fillSettingsForm(settingsBase, scope);
|
||||
$("#settings-modal").hidden = false;
|
||||
}
|
||||
@@ -835,6 +893,14 @@ function wire() {
|
||||
$("#close-stats").addEventListener("click", closeStats);
|
||||
$("#stats-modal").addEventListener("click", (e) => { if (e.target.id === "stats-modal") closeStats(); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("#stats-modal").hidden) closeStats(); });
|
||||
$("#show-notepad").setAttribute("aria-label", t("notepad.title"));
|
||||
$("#show-notepad").addEventListener("click", showNotepad);
|
||||
$("#refresh-notepad").setAttribute("aria-label", t("notepad.refresh"));
|
||||
$("#refresh-notepad").addEventListener("click", refreshNotepad);
|
||||
$("#close-notepad").setAttribute("aria-label", t("notepad.close"));
|
||||
$("#close-notepad").addEventListener("click", closeNotepad);
|
||||
$("#notepad-modal").addEventListener("click", (e) => { if (e.target.id === "notepad-modal") closeNotepad(); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("#notepad-modal").hidden) closeNotepad(); });
|
||||
$("#show-settings").addEventListener("click", () => openSettings("session"));
|
||||
$("#set-scope-session").addEventListener("click", () => openSettings("session"));
|
||||
$("#set-scope-general").addEventListener("click", () => openSettings("general"));
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
"attach.remove": "Remove attachment",
|
||||
"attach.error": "Upload failed: {msg}",
|
||||
"usage.ttft": "1st token {n} s",
|
||||
"usage.cached": "{n} cached",
|
||||
"window.note": "Sliding window: showing {shown} recent messages; {omitted} older ones are kept in history.",
|
||||
"stats.title": "Statistics",
|
||||
"stats.close": "Close",
|
||||
"stats.updated": "Updated {time}",
|
||||
@@ -32,11 +34,13 @@
|
||||
"stats.engine.idle": "Idle",
|
||||
"stats.engine.busy": "In use",
|
||||
"stats.context": "{n} token context",
|
||||
"stats.context_now": "Current context",
|
||||
"stats.context_now.sub": "prompt sent on the last turn",
|
||||
"stats.decode": "Decode speed",
|
||||
"stats.decode.sub": "run average",
|
||||
"stats.prefill": "prefill {n} tok/s",
|
||||
"stats.tokens": "Total tokens",
|
||||
"stats.tokens.sub": "{p} prompt · {c} completion",
|
||||
"stats.tokens": "Cumulative tokens",
|
||||
"stats.tokens.sub": "{p} prompt · {c} completion · across all turns",
|
||||
"stats.sessions": "Sessions",
|
||||
"stats.messages.sub": "{n} messages",
|
||||
"stats.tools": "Tool calls",
|
||||
@@ -53,5 +57,11 @@
|
||||
"stats.perSession.empty": "No sessions yet.",
|
||||
"stats.session.updated": "updated {when}",
|
||||
"stats.tps": "{n} tok/s",
|
||||
"stats.na": "—"
|
||||
"stats.na": "—",
|
||||
"notepad.title": "Notepad",
|
||||
"notepad.hint": "The session's persistent notes, managed by the agent. Read-only.",
|
||||
"notepad.empty": "No notes yet. The agent can pin important things here.",
|
||||
"notepad.refresh": "Refresh",
|
||||
"notepad.close": "Close",
|
||||
"notepad.error": "Error: {msg}"
|
||||
}
|
||||
@@ -24,6 +24,8 @@
|
||||
"attach.remove": "Rimuovi allegato",
|
||||
"attach.error": "Caricamento fallito: {msg}",
|
||||
"usage.ttft": "1° token {n} s",
|
||||
"usage.cached": "{n} cache",
|
||||
"window.note": "Finestra scorrevole: vedi {shown} messaggi recenti; {omitted} più vecchi sono conservati nella cronologia.",
|
||||
"stats.title": "Statistiche",
|
||||
"stats.close": "Chiudi",
|
||||
"stats.updated": "Aggiornato {time}",
|
||||
@@ -32,11 +34,13 @@
|
||||
"stats.engine.idle": "Inattivo",
|
||||
"stats.engine.busy": "In uso",
|
||||
"stats.context": "{n} token di contesto",
|
||||
"stats.context_now": "Contesto attuale",
|
||||
"stats.context_now.sub": "prompt inviato nell'ultimo turno",
|
||||
"stats.decode": "Velocità decode",
|
||||
"stats.decode.sub": "media dall'avvio",
|
||||
"stats.prefill": "prefill {n} tok/s",
|
||||
"stats.tokens": "Token totali",
|
||||
"stats.tokens.sub": "{p} prompt · {c} completati",
|
||||
"stats.tokens": "Token cumulativi",
|
||||
"stats.tokens.sub": "{p} prompt · {c} completati · su tutti i turni",
|
||||
"stats.sessions": "Sessioni",
|
||||
"stats.messages.sub": "{n} messaggi",
|
||||
"stats.tools": "Chiamate tool",
|
||||
@@ -53,5 +57,11 @@
|
||||
"stats.perSession.empty": "Nessuna sessione.",
|
||||
"stats.session.updated": "aggiornato {when}",
|
||||
"stats.tps": "{n} tok/s",
|
||||
"stats.na": "—"
|
||||
"stats.na": "—",
|
||||
"notepad.title": "Notepad",
|
||||
"notepad.hint": "Appunti persistenti della sessione, gestiti dall'agente. Sola lettura.",
|
||||
"notepad.empty": "Nessun appunto. L'agente può fissare qui le cose importanti.",
|
||||
"notepad.refresh": "Aggiorna",
|
||||
"notepad.close": "Chiudi",
|
||||
"notepad.error": "Errore: {msg}"
|
||||
}
|
||||
@@ -32,6 +32,7 @@
|
||||
<span id="session-title">Conversazione</span>
|
||||
<span id="model-name" class="muted"></span>
|
||||
</div>
|
||||
<button id="show-notepad" class="btn icon" aria-label="Notepad">📝</button>
|
||||
<button id="show-settings" class="btn icon" aria-label="Impostazioni">⚙️</button>
|
||||
</header>
|
||||
|
||||
@@ -59,6 +60,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Notepad (read-only): the session's pinned entries, managed by the agent -->
|
||||
<div id="notepad-modal" hidden>
|
||||
<div class="modal-card notepad-card">
|
||||
<div class="stats-head">
|
||||
<h2 data-i18n="notepad.title">Notepad</h2>
|
||||
<button id="refresh-notepad" class="btn icon" aria-label="Aggiorna">↻</button>
|
||||
<button id="close-notepad" class="btn icon" aria-label="Chiudi">✕</button>
|
||||
</div>
|
||||
<p class="muted small notepad-hint" data-i18n="notepad.hint">Appunti persistenti della sessione, gestiti dall'agente. Sola lettura.</p>
|
||||
<div id="notepad-content" class="notepad-content"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Generic dialog (rename input / delete confirm); replaces native prompt/confirm -->
|
||||
<div id="dialog" hidden>
|
||||
<div class="modal-card">
|
||||
|
||||
Reference in new issue
Block a user