From a655bf22b2d3909ec6c3011e4832cd76c96a3609 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 16 Oct 2026 10:22:01 +0200 Subject: [PATCH] Context from cached prompts for agent chats, and a default workspace that is never the app folder - agent context: the Harness reports a cached prompt as cacheReadTokens, apart from inputTokens; the context now counts input + cache read + cache write + reply of the last request (a long agent chat showed 0-3%; checked against a real Swift IQ2_XS 64K run: 8,152 tokens, matching the engine's own 8,042-token prompt + 110 reply) - first workspace: Documents\Strata\Workspace (display name Strata) unless STRATA_WORKSPACE names one, never the app folder; a saved first workspace that is the app folder moves there and its chats follow through an alias - workspaces can be renamed (display name only, path kept): PATCH /api/workspaces/:id, pencil in the sidebar, 8 languages - tests: workspaces.test.mjs, cache-aware context in functional-fixes.test.mjs --- apps/host/server/agent/events.mjs | 7 ++- apps/host/server/index.mjs | 40 ++++++++++-- apps/host/src/app/Sidebar.tsx | 12 +++- apps/host/src/lib/store.ts | 10 +++ apps/host/src/lib/types.ts | 2 + apps/host/tests/functional-fixes.test.mjs | 11 ++++ apps/host/tests/workspaces.test.mjs | 74 +++++++++++++++++++++++ 7 files changed, 147 insertions(+), 9 deletions(-) create mode 100644 apps/host/tests/workspaces.test.mjs diff --git a/apps/host/server/agent/events.mjs b/apps/host/server/agent/events.mjs index cec153f0..4b7728a9 100644 --- a/apps/host/server/agent/events.mjs +++ b/apps/host/server/agent/events.mjs @@ -225,9 +225,12 @@ export class TurnProjector { out.push({ type: 'reasoning', text: c.text }); } else if (c.type === 'usage' && c.usage) { this.usageSeen = true; - this.tokensIn += Number(c.usage.inputTokens) || 0; + // The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`, + // not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%). + const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0); + this.tokensIn += prompt; this.tokensOut += Number(c.usage.outputTokens) || 0; - this.contextTokens = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.outputTokens) || 0); + this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0); } } return out; diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 4b97ae1d..6ecb6061 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -28,7 +28,7 @@ import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirS import { spawn } from 'node:child_process'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import { basename, dirname, extname, isAbsolute, join, normalize, resolve } from 'node:path'; +import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import * as hardware from './hardware.mjs'; @@ -75,7 +75,22 @@ const DIST = process.env.STRATA_DIST : join(ROOT, 'dist'); const PORT = Number(process.env.STRATA_PORT ?? 8791); const HOST = process.env.STRATA_BIND ?? '127.0.0.1'; -const WORKSPACE = process.env.STRATA_WORKSPACE ?? process.cwd(); +/* The folder chats work in when nothing else is chosen. It is never the app's own folder (the host is started inside its install + directory, so `process.cwd()` was "host" in the sidebar and the agent could read and write the app): the person's own + Documents\Strata\Workspace (the models folder is next to it, not in it), created on first use, unless STRATA_WORKSPACE names one. */ +function defaultWorkspace() { + if (process.env.STRATA_WORKSPACE) return resolve(process.env.STRATA_WORKSPACE); + const user = process.env.USERPROFILE ?? process.env.HOME ?? homedir(); + for (const base of [join(user, 'Documents'), user]) { + const dir = join(base, 'Strata', 'Workspace'); + try { mkdirSync(dir, { recursive: true }); return dir; } catch { /* try the next place */ } + } + return user; +} +const WORKSPACE = defaultWorkspace(); +const WORKSPACE_NAME = process.env.STRATA_WORKSPACE ? basename(WORKSPACE) : 'Strata'; +/** True for the app's own install/source folder or anything inside it. */ +const insideApp = path => { const rel = relative(ROOT, resolve(path)); return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)); }; const hub = new EventHub(); const modelProviders = createModelProviders({ directory: store.DATA_DIR, changed: value => hub.send('providers', value) }); @@ -371,11 +386,15 @@ const WORKSPACES_FILE = join(store.DATA_DIR, 'workspaces.json'); function loadWorkspaces() { try { const parsed = JSON.parse(readFileSync(WORKSPACES_FILE, 'utf8')); - if (Array.isArray(parsed) && parsed.length) return parsed; + if (Array.isArray(parsed) && parsed.length) { + // An earlier version saved the app's own folder as the first workspace. The first entry keeps its id (chats point at it) and moves to the default folder. + if (parsed[0]?.id === 'root' && typeof parsed[0].path === 'string' && insideApp(parsed[0].path)) parsed[0] = { ...parsed[0], aliases: [...new Set([...(parsed[0].aliases ?? []), parsed[0].path])], path: WORKSPACE, name: WORKSPACE_NAME }; + return parsed; + } } catch { /* first run */ } - return [{ id: 'root', name: basename(WORKSPACE), path: WORKSPACE }]; + return [{ id: 'root', name: WORKSPACE_NAME, path: WORKSPACE }]; } let workspaces = loadWorkspaces(); @@ -1345,6 +1364,19 @@ async function api(req, res, path, method, url) { return json(res, 200, ws); } + /* A workspace's name is only what the sidebar shows; its folder stays. */ + if (path.startsWith('/api/workspaces/') && method === 'PATCH') { + const id = path.split('/')[3]; + const body = await readBody(req); + const name = String(body.name ?? '').trim().slice(0, 80); + if (!name) return error(res, 400, 'Type a name for this workspace.'); + const at = workspaces.findIndex(w => w.id === id); + if (at < 0) return error(res, 404, 'That workspace is not in your list.'); + workspaces = workspaces.map((w, i) => (i === at ? { ...w, name } : w)); + saveWorkspaces(); + return json(res, 200, workspaces[at]); + } + if (path.startsWith('/api/workspaces/') && method === 'DELETE') { const id = path.split('/')[3]; if (id === workspaces[0]?.id) { diff --git a/apps/host/src/app/Sidebar.tsx b/apps/host/src/app/Sidebar.tsx index c7f72376..e51571f2 100644 --- a/apps/host/src/app/Sidebar.tsx +++ b/apps/host/src/app/Sidebar.tsx @@ -16,7 +16,7 @@ import { MOD, runCommand } from '../lib/commands'; import { bindingFor, bindingKeys, useBindings } from '../lib/shortcut-bindings'; import { Btn, Dialog, Icon, IconBtn, type IconName } from '../components/ui'; import { Brand } from '../components/Brand'; -import { addWorkspace, deleteSession, go, isUnread, pickWorkspace, renameSession, removeWorkspace, selectSession, setActiveWorkspace, setNavOpen, togglePin, toggleRail, setTheme, useStore } from '../lib/store'; +import { addWorkspace, deleteSession, go, isUnread, pickWorkspace, renameSession, removeWorkspace, renameWorkspace, selectSession, setActiveWorkspace, setNavOpen, togglePin, toggleRail, setTheme, useStore } from '../lib/store'; export function Sidebar({ containerRef }: { containerRef: RefObject; }) { @@ -49,6 +49,7 @@ export function Sidebar({ containerRef }: { const [removeWorkspaceId, setRemoveWorkspaceId] = useState(null); const [menuId, setMenuId] = useState(null); const [renameId, setRenameId] = useState(null); + const [renameWsId, setRenameWsId] = useState(null), [wsName, setWsName] = useState(''); const [name, setName] = useState(''); const [deleteId, setDeleteId] = useState(null); const [folders, setFolders] = useState>({}); @@ -80,10 +81,10 @@ export function Sidebar({ containerRef }: { }}/> : <>{tr("Workspaces")}
{ void pickWorkspace().then(path => path ? addWorkspace(path) : undefined); }}/>
)} {workspaces.map(w => { const expanded = folders[w.id] !== false || !!q; - const rows = matching.filter(s => s.workspace === w.path); + const rows = matching.filter(s => s.workspace === w.path || !!w.aliases?.includes(s.workspace)); const shown = q ? rows : rows.slice(0, 20); return
-
{tr(w.id !== 'root' ? setRemoveWorkspaceId(w.id)}/> : null)}
+
{ setWsName(w.name); setRenameWsId(w.id); }}/>{tr(w.id !== 'root' ? setRemoveWorkspaceId(w.id)}/> : null)}
{tr(expanded ?
{tr(shown.map(s =>
@@ -113,6 +114,11 @@ export function Sidebar({ containerRef }: { renameSession(renameId, name.trim()); setRenameId(null); }}>{tr("Save name")}}> + setRenameWsId(null)} actions={<> setRenameWsId(null)}>{tr("Cancel")} { + if (renameWsId) + void renameWorkspace(renameWsId, wsName.trim()); + setRenameWsId(null); + }}>{tr("Save name")}}>

{tr("Only the name changes. The folder stays where it is.")}

setDeleteId(null)} actions={<> setDeleteId(null)}>{tr("Keep chat")} { if (deleteId) deleteSession(deleteId); diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 5dd878fd..949635ed 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -549,6 +549,16 @@ export async function addWorkspace(path: string) { } } +/** The name the sidebar shows for a workspace; its folder is unchanged. */ +export async function renameWorkspace(id: string, name: string) { + try { + const ws = await api.patch(`/api/workspaces/${id}`, { name }); + set({ workspaces: state.workspaces.map(w => (w.id === id ? { ...w, name: ws.name } : w)) }); + } catch (err) { + pushToast('error', "Couldn't rename that workspace", err instanceof Error ? err.message : String(err)); + } +} + export async function removeWorkspace(id: string) { const ws = state.workspaces.find((w) => w.id === id); try { diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 02a434b8..20bc7265 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -372,6 +372,8 @@ export interface Workspace { id: string; name: string; path: string; + /** Earlier folders whose chats belong here (the first workspace moved off the app's own folder). */ + aliases?: string[]; } export interface SessionAgent { diff --git a/apps/host/tests/functional-fixes.test.mjs b/apps/host/tests/functional-fixes.test.mjs index da833f08..b83b93e2 100644 --- a/apps/host/tests/functional-fixes.test.mjs +++ b/apps/host/tests/functional-fixes.test.mjs @@ -63,6 +63,17 @@ test('item 2: the context is the LAST request (prompt + reply), not the sum of e assert.equal(done.tokensIn, 15800, 'the billed sum is still reported separately'); }); +test('item 3: a prompt the server already held counts towards the context (the Harness reports it apart from the input)', () => { + const p = new TurnProjector({ startedAt: 0 }); + // The shape of a real Swift 64K run: the last request had a prompt of 8,042 tokens of which 7,317 came from the conversation cache. + p.consume(chunk({ type: 'usage', usage: { inputTokens: 5800, outputTokens: 40, cacheReadTokens: 0 } }, 'a:1')); + p.consume(chunk({ type: 'usage', usage: { inputTokens: 725, outputTokens: 110, cacheReadTokens: 7317 } }, 'a:2')); + p.consume(ev('turn/end', { turn: 1, reason: { kind: 'completed' } })); + const done = p.finish({ model: 'M', contextMax: 65536 }).find(f => f.type === 'done'); + assert.equal(done.contextTokens, 8152, 'prompt (input + cache) + reply of the last request, which is what the engine held'); + assert.equal(done.tokensIn, 5800 + 725 + 7317); +}); + test('item 7: tool rows say what happened in plain words, with what it was about', () => { const p = new TurnProjector({ startedAt: 0 }); const call = p.consume(ev('tool/call', { callId: 'w1', name: 'write', arguments: JSON.stringify({ file_path: 'C:/work/notes.md', content: 'x' }) }))[0].tool; diff --git a/apps/host/tests/workspaces.test.mjs b/apps/host/tests/workspaces.test.mjs new file mode 100644 index 00000000..8a226f51 --- /dev/null +++ b/apps/host/tests/workspaces.test.mjs @@ -0,0 +1,74 @@ +/** + * The first workspace is never the app's own folder, and any workspace can be renamed (a display name; the path stays). + * A real host process with a scratch user profile; no STRATA_WORKSPACE, started inside the host folder like the installed app. + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const HOST_DIR = resolve(import.meta.dirname, '..'); +const freePort = () => new Promise(r => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); }); +const sleep = ms => new Promise(r => setTimeout(r, ms)); + +async function start(t, { user, home }) { + const port = await freePort(); + const env = { ...process.env, STRATA_HOME: home, STRATA_PORT: String(port), USERPROFILE: user, HOME: user, STRATA_REAL_ENGINE: '0', STRATA_COMPONENTS_DIR: join(home, 'components') }; + delete env.STRATA_WORKSPACE; + const child = spawn(process.execPath, [join(HOST_DIR, 'server', 'index.mjs')], { cwd: HOST_DIR, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }); + let log = ''; child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; }); + t.after(async () => { + if (child.exitCode !== null) return; + if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }); else child.kill('SIGTERM'); + await new Promise(r => child.once('exit', r)); + }); + const base = `http://127.0.0.1:${port}`; + for (let i = 0; i < 100; i++) { + try { if ((await fetch(`${base}/api/workspaces`)).ok) break; } catch { /* not up yet */ } + if (child.exitCode !== null) throw new Error(`the host exited: ${log.slice(-400)}`); + await sleep(200); + } + const call = async (method, path, body) => { const r = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); return { status: r.status, body: await r.json().catch(() => null) }; }; + return { call }; +} + +const scratch = () => { const dir = mkdtempSync(join(tmpdir(), 'strata-ws-')); const user = join(dir, 'user'); const home = join(dir, 'home'); mkdirSync(user, { recursive: true }); mkdirSync(home, { recursive: true }); return { dir, user, home }; }; + +test('item 6: with nothing chosen the first workspace is Documents\\Strata, never the app folder', async t => { + const s = scratch(); t.after(() => rmSync(s.dir, { recursive: true, force: true })); + const host = await start(t, s); + const { body } = await host.call('GET', '/api/workspaces'); + const first = body.workspaces[0]; + assert.equal(first.id, 'root'); + assert.equal(resolve(first.path), join(s.user, 'Documents', 'Strata', 'Workspace')); + assert.equal(first.name, 'Strata'); + assert.ok(existsSync(first.path), 'the folder is created'); + assert.notEqual(resolve(first.path), HOST_DIR); +}); + +test('item 6: a saved first workspace that is the app folder moves to the default; its chats follow through an alias', async t => { + const s = scratch(); t.after(() => rmSync(s.dir, { recursive: true, force: true })); + mkdirSync(join(s.home, 'data'), { recursive: true }); + writeFileSync(join(s.home, 'data', 'workspaces.json'), JSON.stringify([{ id: 'root', name: 'host', path: HOST_DIR }, { id: 'ws_a', name: 'Mine', path: s.user }])); + const host = await start(t, s); + const { body } = await host.call('GET', '/api/workspaces'); + assert.equal(resolve(body.workspaces[0].path), join(s.user, 'Documents', 'Strata', 'Workspace')); + assert.equal(body.workspaces[0].name, 'Strata'); + assert.deepEqual(body.workspaces[0].aliases, [HOST_DIR]); + assert.equal(body.workspaces[1].path, s.user, 'a folder the person added is left alone'); +}); + +test('item 6: renaming changes the display name only', async t => { + const s = scratch(); t.after(() => rmSync(s.dir, { recursive: true, force: true })); + const host = await start(t, s); + const before = (await host.call('GET', '/api/workspaces')).body.workspaces[0]; + const done = await host.call('PATCH', '/api/workspaces/root', { name: ' My projects ' }); + assert.equal(done.status, 200); + assert.equal(done.body.name, 'My projects'); assert.equal(done.body.path, before.path); + assert.equal((await host.call('GET', '/api/workspaces')).body.workspaces[0].name, 'My projects', 'it is saved'); + assert.equal((await host.call('PATCH', '/api/workspaces/root', { name: ' ' })).status, 400); + assert.equal((await host.call('PATCH', '/api/workspaces/nope', { name: 'x' })).status, 404); +});