diff --git a/apps/host/scripts/tools-shots.mjs b/apps/host/scripts/tools-shots.mjs new file mode 100644 index 00000000..291868e4 --- /dev/null +++ b/apps/host/scripts/tools-shots.mjs @@ -0,0 +1,81 @@ +/** + * Settings -> Tools screenshots from the real UI. The host's /api/agent/tools answer is replaced by a fixture (page.route) so every state can be + * shown without a model or a Harness. + * + * STRATA_URL=http://127.0.0.1:8899 SHOTS=./tools-shots node scripts/tools-shots.mjs + */ +import { chromium } from 'playwright-core'; +import { existsSync, mkdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +const BASE = process.env.STRATA_URL; +if (!BASE) { console.error('STRATA_URL is required'); process.exit(2); } +const SHOTS = resolve(process.env.SHOTS ?? 'tools-shots'); +mkdirSync(SHOTS, { recursive: true }); +const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); + +const group = (id, name, about, area, asks = false, enabled = true) => ({ id, name, about, area, asks, enabled }); +const GROUPS = [ + group('shell', 'Run commands', 'Lets the assistant run commands, for example to open a folder or start a program.', 'computer', true), + group('files', 'Read and change files', 'Lets the assistant read, create and edit files in your chat folder.', 'computer', true), + group('find', 'Find files and text', 'Lets the assistant look for files by name and search inside them. It only reads.', 'computer'), + group('jobs', 'Long-running jobs', 'Lets the assistant start a slow command in the background and check on it later.', 'computer', true), + group('fetch', 'Open web pages', 'Lets the assistant read a web page you point it to.', 'web'), + group('search', 'Search the web', 'Lets the assistant search the web when it needs fresh information.', 'web'), + group('helpers', 'Helper assistants', 'Lets the assistant start helpers that work on parts of a task at the same time.', 'together'), + group('goals', 'Goals', 'Lets you give a goal with /goal. The assistant keeps working until it is done.', 'together'), + group('todo', 'To-do list', 'Lets the assistant keep a checklist while it works on a big task.', 'together'), + group('skills', 'Skills', 'Lets the assistant use your saved skills when they fit the task.', 'together'), + group('present', 'Show results', 'Lets the assistant show a page or file in the preview next to the chat.', 'together'), +]; +const base = () => ({ groups: GROUPS.map(g => ({ ...g })), search: { provider: 'builtin', keySet: false }, browser: { enabled: false, found: true, name: 'Google Chrome' }, custom: [] }); +const STATES = { + fresh: base(), + busy: (() => { const s = base(); s.groups[3].enabled = false; s.groups[5].enabled = false; s.browser.enabled = true; + s.custom = [ + { id: 'c1', name: 'Release notes', about: 'Write release notes in our house style.', kind: 'instructions', enabled: true, summary: 'Start with a one-line summary…' }, + { id: 'c2', name: 'Check website', about: 'Check that our website answers.', kind: 'command', enabled: true, summary: 'curl -I https://example.com', command: 'curl -I https://example.com' }, + { id: 'c3', name: 'Issue tracker', about: 'Look up and update issues.', kind: 'server', enabled: false, summary: 'https://issues.example/mcp', address: 'https://issues.example/mcp' }, + ]; return s; })(), + key: (() => { const s = base(); s.search = { provider: 'exa', keySet: false }; return s; })(), + nobrowser: (() => { const s = base(); s.browser = { enabled: false, found: false, name: null }; return s; })(), +}; + +const browser = await chromium.launch({ executablePath: CHROME, headless: true }); +let page = null, context = null; +let current = 'fresh'; +const shot = async name => { await page.waitForTimeout(500); await page.screenshot({ path: join(SHOTS, `${name}.png`) }); console.log(`shot ${name}.png`); }; +const open = async state => { + current = state; + if (!page) { + context = await browser.newContext({ viewport: { width: 1360, height: 980 } }); + page = await context.newPage(); + page.on('pageerror', e => console.log('pageerror', e.message.slice(0, 300))); + page.on('console', m => { if (m.type() === 'error') console.log('console', m.text().slice(0, 300)); }); + await page.route('**/api/agent/tools**', route => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(STATES[current]) })); + await page.goto(`${BASE}/`); + const skip = page.getByText('Go straight to the app'); + await skip.waitFor({ timeout: 8000 }).then(() => skip.click()).catch(() => {}); + await page.goto(`${BASE}/#/settings`); + await page.waitForSelector('#settings-tab-Tools', { timeout: 20000 }); + await page.locator('#settings-tab-Tools').evaluate(el => el.click()); + } else { + // The Tools panel loads its list when it is shown: leave it and come back to load the next fixture. + await page.locator('#settings-tab-Appearance').evaluate(el => el.click()); + await page.waitForTimeout(300); + } + await page.locator('#settings-tab-Tools').evaluate(el => el.click()); + await page.waitForSelector('.settings-tools', { timeout: 10000 }); +}; +await open('fresh'); await shot('01-tools-top'); +await page.getByRole('heading', { name: 'Web search' }).evaluate(el => el.scrollIntoView({ block: 'start' })); await shot('02-tools-web-and-browser'); +await open('busy'); await page.getByRole('heading', { name: 'Your own tools' }).evaluate(el => el.scrollIntoView({ block: 'start' })); await shot('03-your-own-tools'); +await open('key'); await page.getByRole('heading', { name: 'Web search' }).evaluate(el => el.scrollIntoView({ block: 'start' })); await shot('04-search-with-key'); +await open('nobrowser'); await page.getByRole('heading', { name: 'Web browser' }).evaluate(el => el.scrollIntoView({ block: 'start' })); await shot('05-no-browser-found'); +await open('fresh'); +await page.getByRole('button', { name: 'Add a tool' }).click(); await shot('06-add-tool-instructions'); +await page.getByRole('dialog').getByLabel('How it works').click(); +await page.getByRole('option', { name: 'Run a command' }).click(); await shot('07-add-tool-command'); +await page.getByRole('dialog').getByLabel('How it works').click(); +await page.getByRole('option', { name: 'Connect a tool server (MCP)' }).click(); await shot('08-add-tool-server'); +await browser.close(); diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index c8d2cead..d8361ff8 100644 --- a/apps/host/server/index.mjs +++ b/apps/host/server/index.mjs @@ -625,6 +625,8 @@ const TIMESKIP_REVISE = process.env.STRATA_TIMESKIP_REVISE ?? `"${process.execPath}" "${REVISE_NODE_SCRIPT}"`; /** Proves a revision request comes from a job this host started, not from some other program on this PC. */ const INTERNAL_SECRET = randomBytes(24).toString('hex'); +/** The model a trial runs on, by run id: the chat's saved API model when it uses one, else the loaded local model. */ +const timeskipChoices = new Map(); /** * Tuning, from the App Host. * @@ -931,6 +933,7 @@ async function api(req, res, path, method, url) { extraEnv: { STRATA_HOST_URL: `http://127.0.0.1:${PORT}`, STRATA_INTERNAL_SECRET: INTERNAL_SECRET }, }); if (!result.ok) return error(res, result.code === 2 ? 400 : 502, result.error); + if (body.remoteModel?.connectionId && body.remoteModel?.modelId) timeskipChoices.set(result.run.id, { connectionId: String(body.remoteModel.connectionId), modelId: String(body.remoteModel.modelId) }); return json(res, 200, { run: result.run, simulated: false }); } if (path === '/api/timeskip/files' && method === 'GET') { @@ -952,7 +955,8 @@ async function api(req, res, path, method, url) { // Only the job's own candidate folders may be worked in. const root = resolve(timeskip.stateDir()); if (!cwd || !resolve(cwd).startsWith(root + sep)) return error(res, 400, 'That folder is not part of a Time-skip run.'); - const chosen = (() => { try { return { instanceId: native.resolveInstance(native.state().defaultId).id }; } catch { return null; } })(); + const runId = resolve(cwd).slice(root.length + 1).split(sep)[0]; + const chosen = timeskipChoices.get(runId) ?? (() => { try { return { instanceId: native.resolveInstance(native.state().defaultId).id }; } catch { return null; } })(); if (!chosen) return error(res, 503, 'Load a model first, then try Time-skip again.'); const chatId = `timeskip:${randomBytes(6).toString('hex')}`; let text = '', failure = null; diff --git a/apps/host/src/components/SettingsTools.tsx b/apps/host/src/components/SettingsTools.tsx new file mode 100644 index 00000000..875aa945 --- /dev/null +++ b/apps/host/src/components/SettingsTools.tsx @@ -0,0 +1,190 @@ +import { tr } from '../lib/i18n'; +/** + * Settings -> Tools: what the assistant may use in chats, in plain words. + * + * Every row is a switch in the existing Field pattern. Nothing here is a new component: switches, selects, dialogs and buttons are + * the ones the other Settings panels use. The host owns the truth (GET/PUT /api/agent/tools); a change applies from the next message. + */ +import { useEffect, useState } from 'react'; +import { api } from '../lib/client'; +import { pushToast } from '../lib/store'; +import { Btn, Dialog, ErrorNotice, Field, Icon, Select } from './ui'; + +export interface ToolGroup { + id: string; + name: string; + about: string; + area: 'computer' | 'web' | 'together'; + enabled: boolean; + /** Manual mode asks before this tool changes anything. */ + asks: boolean; +} +export interface CustomTool { + id: string; + name: string; + about: string; + kind: 'instructions' | 'command' | 'server'; + enabled: boolean; + /** Shown in the list: the command, the server address or the first words of the instructions. */ + summary: string; + instructions?: string; + command?: string; + address?: string; + args?: string[]; +} +export interface ToolsState { + groups: ToolGroup[]; + search: { provider: 'builtin' | 'exa' | 'perplexity' | 'deepseek'; keySet: boolean }; + browser: { enabled: boolean; found: boolean; name: string | null }; + custom: CustomTool[]; +} + +const AREAS: { id: ToolGroup['area']; title: string }[] = [ + { id: 'computer', title: 'On this computer' }, + { id: 'web', title: 'On the web' }, + { id: 'together', title: 'Working on bigger jobs' }, +]; +const SEARCH_CHOICES = [ + { value: 'builtin', label: 'DuckDuckGo (no key)' }, + { value: 'exa', label: 'Exa (your own key)' }, + { value: 'perplexity', label: 'Perplexity (your own key)' }, + { value: 'deepseek', label: 'DeepSeek (your own key)' }, +]; +const KIND_CHOICES = [ + { value: 'instructions', label: 'Follow my instructions' }, + { value: 'command', label: 'Run a command' }, + { value: 'server', label: 'Connect a tool server (MCP)' }, +]; +const KIND_NAMES: Record = { instructions: 'Instructions', command: 'Command', server: 'Tool server' }; + +interface Draft { + id?: string; + name: string; + about: string; + kind: CustomTool['kind']; + instructions: string; + command: string; + address: string; + args: string; +} +const blank = (): Draft => ({ name: '', about: '', kind: 'instructions', instructions: '', command: '', address: '', args: '' }); + +export function SettingsTools({ preview }: { preview?: ToolsState }) { + const [state, setState] = useState(preview ?? null); + const [error, setError] = useState(''); + const [key, setKey] = useState(''); + const [draft, setDraft] = useState(null); + const [formError, setFormError] = useState(''); + const [remove, setRemove] = useState(null); + const [busy, setBusy] = useState(false); + + async function load() { + try { setState(await api.get('/api/agent/tools')); setError(''); } + catch (e) { setError(e instanceof Error ? e.message : 'The tool list could not be loaded.'); } + } + useEffect(() => { if (!preview) void load(); }, []); + + async function save(change: Record) { + if (preview) return; + setBusy(true); + try { setState(await api.put('/api/agent/tools', change)); setError(''); } + catch (e) { setError(e instanceof Error ? e.message : 'The change could not be saved.'); void load(); } + finally { setBusy(false); } + } + const toggle = (id: string, on: boolean) => { + setState(s => s && { ...s, groups: s.groups.map(g => g.id === id ? { ...g, enabled: on } : g) }); + void save({ groups: { [id]: on } }); + }; + + async function submit() { + if (!draft) return; + if (!/^[A-Za-z][A-Za-z0-9 _-]{0,39}$/.test(draft.name.trim())) { setFormError('Give the tool a short name: letters, numbers, spaces or hyphens.'); return; } + if (!draft.about.trim()) { setFormError('Say what the tool does, in a sentence. The assistant reads this to decide when to use it.'); return; } + if (draft.kind === 'instructions' && !draft.instructions.trim()) { setFormError('Write the instructions the assistant should follow when it uses this tool.'); return; } + if (draft.kind === 'command' && !draft.command.trim()) { setFormError('Enter the command to run.'); return; } + if (draft.kind === 'server' && !draft.address.trim()) { setFormError('Enter the tool server’s web address, or the program that starts it.'); return; } + setBusy(true); + try { + const body = { name: draft.name.trim(), about: draft.about.trim(), kind: draft.kind, instructions: draft.instructions, command: draft.command.trim(), address: draft.address.trim(), args: draft.args.split('\n').map(a => a.trim()).filter(Boolean) }; + setState(draft.id ? await api.patch(`/api/agent/tools/custom/${encodeURIComponent(draft.id)}`, body) : await api.post('/api/agent/tools/custom', body)); + setDraft(null); setFormError(''); + } catch (e) { setFormError(e instanceof Error ? e.message : 'The tool could not be saved.'); } + finally { setBusy(false); } + } + + if (!state) return
{error ? void load()} /> :

{tr('Loading the tool list…')}

}
; + const keyed = state.search.provider !== 'builtin'; + + return
+

{tr('Tools')}

{tr('Choose what the assistant may use in your chats. A change applies from your next message. In Manual mode, anything that changes your computer still asks you first.')}

+ {error ? void load()} /> : null} + {AREAS.map(area =>
+

{tr(area.title)}

+
+ {state.groups.filter(g => g.area === area.id).map(g => +
+
)} + +
+

{tr('Web search')}

+
+ + setKey(e.target.value)} /> + { void save({ search: { provider: state.search.provider, key: key.trim() } }); setKey(''); pushToast('success', tr('Key saved')); }}>{tr('Save key')} +
+ : null} +
+ + +
+

{tr('Web browser')}

+
+ +
+
+ +
+

{tr('Your own tools')}

+

{tr('Teach the assistant something new: give it instructions to follow, a command to run, or connect a tool server. Commands and servers ask first in Manual mode.')}

+ {state.custom.length ?
+ {state.custom.map(t => {tr(t.about)} · {tr(KIND_NAMES[t.kind])}}> +
+ { setFormError(''); setDraft({ id: t.id, name: t.name, about: t.about, kind: t.kind, instructions: t.instructions ?? '', command: t.command ?? '', address: t.address ?? '', args: (t.args ?? []).join('\n') }); }}>{tr('Edit')} + setRemove(t)}>{tr('Remove')} +
+
)} +
:
{tr('No tools of your own yet')}

{tr('For example: “Write release notes in our house style”, or a command that checks your website is up.')}

} +
{ setFormError(''); setDraft(blank()); }}>{tr('Add a tool')}
+
+ + setDraft(null)} actions={<> setDraft(null)}>{tr('Cancel')} void submit()}>{tr('Save tool')}}> + {draft ?
+ + +
{tr('How it works')}