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
This commit is contained in:
1 parent
df13760cf4
commit
a655bf22b2
7 files changed
+147
-9
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<HTMLElement | null>;
|
||||
}) {
|
||||
@@ -49,6 +49,7 @@ export function Sidebar({ containerRef }: {
|
||||
const [removeWorkspaceId, setRemoveWorkspaceId] = useState<string | null>(null);
|
||||
const [menuId, setMenuId] = useState<string | null>(null);
|
||||
const [renameId, setRenameId] = useState<string | null>(null);
|
||||
const [renameWsId, setRenameWsId] = useState<string | null>(null), [wsName, setWsName] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||
const [folders, setFolders] = useState<Record<string, boolean>>({});
|
||||
@@ -80,10 +81,10 @@ export function Sidebar({ containerRef }: {
|
||||
}}/><IconBtn name="x" title={tr("Close chat search")} onClick={closeSearch}/></div> : <><span className="navgroup__label">{tr("Workspaces")}</span><div className="ws__tools"><button ref={searchTrigger} type="button" className="st-btn st-btn--icon" aria-label={tr("Search chats")} title={tr("Search chats")} onClick={() => setSearchOpen(true)}><Icon name="search" size={18}/></button><IconBtn name="folder-plus" title={tr("Add a workspace folder")} onClick={() => { void pickWorkspace().then(path => path ? addWorkspace(path) : undefined); }}/></div></>)}</div>
|
||||
{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 <div className="ws__group" key={w.id}>
|
||||
<div className={cx('ws__row', activeWorkspace === w.id && 'is-active')}><button className="ws__name" aria-expanded={expanded} onClick={() => { setActiveWorkspace(w.id); setFolders(f => ({ ...f, [w.id]: !expanded })); }}><Icon name="chevron" size={14} className={cx('ws__chev', expanded && 'is-open')}/><Icon name="folder" size={17}/><span>{w.name}</span></button>{tr(w.id !== 'root' ? <IconBtn name="x" title={tr("Remove {0} from sidebar", [w.name])} onClick={() => setRemoveWorkspaceId(w.id)}/> : null)}</div>
|
||||
<div className={cx('ws__row', activeWorkspace === w.id && 'is-active')}><button className="ws__name" aria-expanded={expanded} onClick={() => { setActiveWorkspace(w.id); setFolders(f => ({ ...f, [w.id]: !expanded })); }}><Icon name="chevron" size={14} className={cx('ws__chev', expanded && 'is-open')}/><Icon name="folder" size={17}/><span>{w.name}</span></button><IconBtn name="pencil" title={tr("Rename {0}", [w.name])} onClick={() => { setWsName(w.name); setRenameWsId(w.id); }}/>{tr(w.id !== 'root' ? <IconBtn name="x" title={tr("Remove {0} from sidebar", [w.name])} onClick={() => setRemoveWorkspaceId(w.id)}/> : null)}</div>
|
||||
{tr(expanded ? <div className="navsessions">
|
||||
{tr(shown.map(s => <div key={s.id}>
|
||||
<div className="ws__session row"><a className="navsession" href={href('chat', s.id)} aria-current={activeSession === s.id && location.route === 'chat' ? 'page' : undefined} onClick={() => selectSession(s.id)} onContextMenu={e => { e.preventDefault(); openMenu(s.id, e.currentTarget); }} title={sessionTitle(s)}><span className="navsession__title">{sessionTitle(s)}</span>{tr(s.pinned ? <span aria-label={tr("Pinned")}><Icon name="pin" size={12}/></span> : <span className="navsession__time">{tr(relTime(s.updatedAt))}</span>)}{tr(isUnread(s, activeSession) ? <span className="navsession__unread" aria-label={tr("Unread")}/> : null)}{tr(s.archived ? <span className="xs muted">{tr("Archived")}</span> : null)}</a><button className="st-btn st-btn--icon session-overflow" aria-label={tr("Actions for {0}", [sessionTitle(s)])} onClick={e => openMenu(s.id, e.currentTarget)}><Icon name="ellipsis" size={16}/></button></div>
|
||||
@@ -113,6 +114,11 @@ export function Sidebar({ containerRef }: {
|
||||
renameSession(renameId, name.trim());
|
||||
setRenameId(null);
|
||||
}}>{tr("Save name")}</Btn></>}><label className="input-field" htmlFor="chat-name"><span>{tr("Chat name")}</span><input className="st-input" id="chat-name" value={name} onFocus={e => e.currentTarget.select()} onChange={e => setName(e.target.value)}/></label></Dialog>
|
||||
<Dialog open={!!renameWsId} compact title={tr("Rename workspace")} onClose={() => setRenameWsId(null)} actions={<><Btn onClick={() => setRenameWsId(null)}>{tr("Cancel")}</Btn><Btn variant="primary" disabled={!wsName.trim()} onClick={() => {
|
||||
if (renameWsId)
|
||||
void renameWorkspace(renameWsId, wsName.trim());
|
||||
setRenameWsId(null);
|
||||
}}>{tr("Save name")}</Btn></>}><label className="input-field" htmlFor="workspace-name"><span>{tr("Workspace name")}</span><input className="st-input" id="workspace-name" value={wsName} onFocus={e => e.currentTarget.select()} onChange={e => setWsName(e.target.value)}/></label><p className="small muted">{tr("Only the name changes. The folder stays where it is.")}</p></Dialog>
|
||||
<Dialog open={!!deleteId} compact title={tr("Delete this chat?")} onClose={() => setDeleteId(null)} actions={<><Btn onClick={() => setDeleteId(null)}>{tr("Keep chat")}</Btn><Btn variant="danger" onClick={() => {
|
||||
if (deleteId)
|
||||
deleteSession(deleteId);
|
||||
|
||||
@@ -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<Workspace>(`/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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user