Time-skip: run the page's own script in the A/B preview, working view in the sidebar, retry the file list; mode change applies to the next tool call mid-run
This commit is contained in:
1 parent
50f973c9f9
commit
2e1fcd15d9
9 files changed
+111
-16
No files matched your search
@@ -610,6 +610,34 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
return runTurn({ ...options, goal: { action: 'create', objective: text } });
|
||||
}
|
||||
|
||||
/**
|
||||
* The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset
|
||||
* is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are
|
||||
* settled the way the new mode would have settled them: Bypass allows them, Plan rejects them.
|
||||
*/
|
||||
async function setMode(chatId, mode) {
|
||||
const want = modeOf(mode);
|
||||
const c = chats.get(chatId);
|
||||
const sessionId = sessionMap[chatId]?.sessionId;
|
||||
if (!rt || !sessionId) return { applied: false, mode: want, reason: 'no session yet' };
|
||||
if (c?.turn && c.turn.mode === want) return { applied: true, mode: want, settled: 0 };
|
||||
await applyMode(rt, sessionId, want);
|
||||
let settled = 0;
|
||||
if (c?.turn) {
|
||||
c.turn.mode = want;
|
||||
c.turn.projector.policy = MODE_PRESETS[want].approval;
|
||||
if (want !== 'manual') {
|
||||
const helpers = c.turn.children;
|
||||
for (const [key, entry] of [...pending.entries()]) {
|
||||
if (entry.sessionId !== sessionId && !helpers?.has(entry.sessionId)) continue;
|
||||
pending.delete(key);
|
||||
try { await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: want === 'bypass' ? 'allowed-once' : 'rejected' }); settled++; } catch { /* already answered */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
return { applied: true, mode: want, settled };
|
||||
}
|
||||
|
||||
/** Answer one pending approval. `decision` is `approve` or `deny`. */
|
||||
async function approve({ chatId, callId, decision }) {
|
||||
const sessionId = sessionMap[chatId]?.sessionId;
|
||||
@@ -680,7 +708,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir =
|
||||
/** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */
|
||||
function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); }
|
||||
|
||||
return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, forget, approve, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };
|
||||
return { goalState, goalControl, harnessDir, status, runTurn, goalCommand, forget, approve, setMode, stop, pendingFor, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };
|
||||
}
|
||||
|
||||
/** A goal that stopped by itself, in words. */
|
||||
|
||||
@@ -166,6 +166,11 @@ export function apply(ctx) {
|
||||
if (!agent || exec.name === 'run_code') return next();
|
||||
let preset;
|
||||
try { preset = effectivePreset(agent.session); } catch { return next(); }
|
||||
// A helper that was set to ask while the chat was in Manual must stop asking the moment the chat leaves Manual,
|
||||
// so a mode change applies to the very next tool call of a running goal and its helpers.
|
||||
if (preset !== MANUAL_PRESET && agent.session.header?.origin === 'subagent' && ctx.approval.overrideOf(agent.session) === 'ask') {
|
||||
agent.session.append('approval/policy', { policy: 'never' });
|
||||
}
|
||||
if (preset === PLAN_PRESET) return planDecision(exec) ?? next();
|
||||
if (preset !== MANUAL_PRESET) return next();
|
||||
const gate = manualDecision(exec);
|
||||
|
||||
@@ -1633,6 +1633,12 @@ async function api(req, res, path, method, url) {
|
||||
try { return json(res, 200, await agent.approve({ chatId: b.sessionId, callId: b.toolId, decision: b.decision })); }
|
||||
catch (e) { return error(res, e.code === 'approval-gone' ? 409 : 400, e.message); }
|
||||
}
|
||||
/* The person changed the chat's mode while a turn runs: it applies to the next tool call, goal and helpers included. */
|
||||
if (path === '/api/chat/mode' && method === 'POST') {
|
||||
const b = await readBody(req);
|
||||
if (typeof b.sessionId !== 'string' || !['manual', 'plan', 'bypass'].includes(b.mode)) return error(res, 400, 'sessionId and mode (manual, plan or bypass) are required');
|
||||
try { return json(res, 200, await agent.setMode(b.sessionId, b.mode)); } catch (e) { return error(res, e.code === 'mode-unavailable' ? 409 : 502, e.message); }
|
||||
}
|
||||
/* Stop one chat's turn. Resolves once the turn has really ended, not when the cancel was admitted. */
|
||||
if (path === '/api/chat/stop' && method === 'POST') {
|
||||
const b = await readBody(req);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { tr } from '../lib/i18n';
|
||||
import type { TimeSkipFile } from '../lib/time-skip';
|
||||
import { diffStats, fileKind, htmlPreviewDocument, lineDiff, segmentLines, timeSkipImageUrl, wordDiff, type Segment } from '../lib/time-skip-compare';
|
||||
import { HTML_PREVIEW_SANDBOX, diffStats, fileKind, htmlPreviewDocument, needsOutsideFiles, lineDiff, segmentLines, timeSkipImageUrl, wordDiff, type Segment } from '../lib/time-skip-compare';
|
||||
import { Btn, Dialog, Icon } from './ui';
|
||||
|
||||
const baseName = (path: string) => path.split('/').pop() || path;
|
||||
@@ -77,10 +77,12 @@ function FileView({ jobId, file }: { jobId: string; file: TimeSkipFile }) {
|
||||
if (kind === 'html') return <>
|
||||
<div className="tsc-tools"><Btn size="sm" variant="ghost" icon={code ? 'image' : 'file'} aria-pressed={code} onClick={() => setCode(v => !v)}>{tr(code ? 'View preview' : 'View code')}</Btn></div>
|
||||
{code ? <DiffView original={original} updated={updated}/> : <>{heads}<div className="tsc-pair tsc-pair--html">
|
||||
{/* No permissions at all: no scripts, no forms, no navigation. The page also carries a policy that blocks every outside request. */}
|
||||
<iframe title={tr("Original page")} sandbox="" srcDoc={htmlPreviewDocument(original)} loading="lazy"/>
|
||||
<iframe title={tr("Updated page")} sandbox="" srcDoc={htmlPreviewDocument(updated)} loading="lazy"/>
|
||||
</div></>}
|
||||
{/* The page may run its own scripts in an isolated frame; the policy inside blocks every outside request. */}
|
||||
{file.status === 'added' ? <div className="tsc-picture tsc-picture--empty"><span>{tr("Not there before.")}</span></div>
|
||||
: <iframe title={tr("Original page")} sandbox={HTML_PREVIEW_SANDBOX} srcDoc={htmlPreviewDocument(original)} loading="lazy"/>}
|
||||
{file.status === 'removed' ? <div className="tsc-picture tsc-picture--empty"><span>{tr("Removed.")}</span></div>
|
||||
: <iframe title={tr("Updated page")} sandbox={HTML_PREVIEW_SANDBOX} srcDoc={htmlPreviewDocument(updated)} loading="lazy"/>}
|
||||
</div>{needsOutsideFiles(updated) ? <p className="tsc-note">{tr("This page asks for files from the internet, which the preview does not load, so it may look incomplete. View code shows exactly what was written.")}</p> : null}</>}
|
||||
</>;
|
||||
if (words) return <>{heads}<div className="tsc-pair tsc-pair--text">
|
||||
<MarkedDoc segments={words.original} markdown={kind === 'markdown'}/>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import type { PreviewArtifact } from '../lib/artifacts';
|
||||
import { plainTimeSkipError, replayTimeSkip, setTimeSkipResult, stopTimeSkip } from '../lib/store';
|
||||
import { realTimeSkipDocuments, timeSkipCheckOutcomes, timeSkipDocumentMarkdown, timeSkipDocuments, timeSkipExample, timeSkipResultState, type TimeSkipDocument, type TimeSkipRun, type TimeSkipVersion } from '../lib/time-skip';
|
||||
import { TimeSkipWorking } from './TimeSkipWorking';
|
||||
import { FloatingMenu } from './FloatingMenu';
|
||||
import { TimeSkipCompare } from './TimeSkipCompare';
|
||||
import { Btn, Dialog, Icon } from './ui';
|
||||
@@ -142,7 +143,7 @@ export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onC
|
||||
<div className="ts-content">
|
||||
<div className="ts-heading"><h2 aria-live="polite"><span className="ts-status-icon">{tr(!frame.done ? <span className="ts-activity"/> : <Icon name={kept === 'original' ? 'file' : 'shield'} size={21}/>)}</span><span>{tr(status)}</span></h2></div>
|
||||
<p className="ts-caption">{tr(frame.done ? kept === 'original' ? 'The updated result is still available.' : 'The original is always available.' : frame.pass === 2 ? 'Trying one more revision. Your progress is saved.' : 'Improving the saved draft.')}</p>
|
||||
{tr(compareReal ? <TimeSkipCompare jobId={run.job!.id} files={run.job!.files!} more={run.job!.moreFiles ?? 0}/> : <>
|
||||
{tr(real && !frame.done ? <TimeSkipWorking run={run} sessionId={sessionId}/> : compareReal ? <TimeSkipCompare jobId={run.job!.id} files={run.job!.files!} more={run.job!.moreFiles ?? 0}/> : <>
|
||||
{tr(expanded ? <div className="ts-compare-heading"><h3>{tr("Compare results")}</h3><Btn size="sm" variant="ghost" icon="contract" onClick={() => onCompare(false)}>{tr(inline ? 'Back to chat' : 'Done comparing')}</Btn></div> : null)}
|
||||
<div className="ts-switch-row" data-comparing={expanded || undefined}>
|
||||
<VersionTabs version={version} onChange={which => { setVersion(which); setImageCompare(false); }} done={frame.done}/>
|
||||
|
||||
@@ -1012,6 +1012,8 @@ export function newSession(): Session {
|
||||
export function setChatPreferences(id: string | undefined, preferences: NonNullable<Session['preferences']>) {
|
||||
const sessionId = id ?? newSession().id;
|
||||
patchSession(sessionId, s => ({ ...s, preferences: { ...s.preferences, ...preferences } }));
|
||||
// A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included).
|
||||
if (preferences.mode && liveTurns.get(sessionId)?.agent) void api.post('/api/chat/mode', { sessionId, mode: preferences.mode }).catch(() => undefined);
|
||||
}
|
||||
export function setPreviewTabClosed(sessionId:string|undefined, artifactId:string, closed:boolean, selected:string|null) {
|
||||
if(!sessionId)return;
|
||||
@@ -1217,10 +1219,14 @@ export async function followTimeSkip(sessionId: string, runId: string) {
|
||||
catch { misses += 1; }
|
||||
if (job && TS_TERMINAL.includes(job.phase)) {
|
||||
let files: TimeSkipFile[] = [], extra: Partial<TimeSkipJob> = {};
|
||||
try {
|
||||
const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id));
|
||||
files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more };
|
||||
} catch { /* the list is a convenience; the job's record stands */ }
|
||||
// The changed files are what the person came for: ask again a few times before settling for "nothing to compare".
|
||||
for (let tryNo = 0; tryNo < 4; tryNo++) {
|
||||
try {
|
||||
const found = await api.get<{ files: TimeSkipFile[]; applyAttempt: number | null; more: number }>('/api/timeskip/files?id=' + encodeURIComponent(job.id));
|
||||
files = found.files; extra = { files: found.files, applyAttempt: found.applyAttempt, moreFiles: found.more };
|
||||
break;
|
||||
} catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); }
|
||||
}
|
||||
const finished = job;
|
||||
patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files));
|
||||
// A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab.
|
||||
|
||||
@@ -117,17 +117,22 @@ export function lineDiff(original: string, updated: string, context = 2): DiffRo
|
||||
export const diffStats = (rows: DiffRow[]) => ({ added: rows.filter(r => r.t === 'add').length, removed: rows.filter(r => r.t === 'del').length });
|
||||
|
||||
/**
|
||||
* A page for the preview frame. The frame itself is sandboxed with no permissions (no scripts, no forms, no navigation); this adds a content
|
||||
* policy so the page also cannot fetch anything from the internet: it shows what was written, nothing more.
|
||||
* A page for the preview frame. The frame is sandboxed without a same-origin right, forms, navigation or pop-ups; it may run the page's own
|
||||
* scripts, because most pages people ask for (a 3D scene, a game, a chart) draw themselves with a script and would show as an empty dark
|
||||
* page without one. The content policy still blocks every request to the internet: only what was written is shown.
|
||||
*/
|
||||
export const HTML_PREVIEW_SANDBOX = 'allow-scripts';
|
||||
export function htmlPreviewDocument(html: string): string {
|
||||
const policy = '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src data:; style-src \'unsafe-inline\'; font-src data:; media-src data:">';
|
||||
const policy = '<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'unsafe-inline\' \'unsafe-eval\'; img-src data: blob:; style-src \'unsafe-inline\'; font-src data:; media-src data: blob:">';
|
||||
const base = '<base target="_blank">';
|
||||
const head = /<head[^>]*>/i.exec(html);
|
||||
if (head) return html.slice(0, head.index + head[0].length) + policy + base + html.slice(head.index + head[0].length);
|
||||
return `<!doctype html><html><head><meta charset="utf-8">${policy}${base}</head><body>${html}</body></html>`;
|
||||
}
|
||||
|
||||
/** True when the page asks for something from the internet (a script, style or picture by web address): the preview cannot load it. */
|
||||
export const needsOutsideFiles = (html: string) => /<(?:script|link|img|iframe|source)\b[^>]*(?:src|href)\s*=\s*["']?(?:https?:)?\/\//i.test(html);
|
||||
|
||||
/** The address of one side of a changed picture on the host. */
|
||||
export const timeSkipImageUrl = (jobId: string, path: string, version: 'original' | 'updated') =>
|
||||
`/api/timeskip/file?id=${encodeURIComponent(jobId)}&path=${encodeURIComponent(path)}&version=${version}`;
|
||||
@@ -246,3 +246,39 @@ test('goal bar: the state, pause, edit and remove work from outside a turn, and
|
||||
assert.equal(await r.bridge.goalState('bar'), null);
|
||||
await assert.rejects(r.bridge.goalControl({ chatId: 'bar', action: 'explode' }), /no goal|not known/i);
|
||||
});
|
||||
|
||||
test('mode change mid-run: Manual to Bypass settles the question already waiting and the very next tool call does not ask again', { skip }, async (t) => {
|
||||
const r = await rig(t);
|
||||
const first = join(r.ws, 'before.txt');
|
||||
let asked = null; const cards = [];
|
||||
const run = r.run('mid', `SCRIPT:spawn 1 call write ${JSON.stringify({ file_path: fwd(first), content: 'one' })}`, { mode: 'manual', onFrame: f => { if (f.type === 'agent-tool') { cards.push(f.tool); if (f.tool.state === 'proposed') asked = f.tool; } } });
|
||||
for (let i = 0; i < 200 && !asked; i++) await new Promise(res => setTimeout(res, 50));
|
||||
assert.ok(asked, 'Manual asked first');
|
||||
const switched = await r.bridge.setMode('mid', 'bypass');
|
||||
assert.deepEqual({ applied: switched.applied, mode: switched.mode }, { applied: true, mode: 'bypass' });
|
||||
assert.equal(switched.settled, 1, 'the waiting question was settled by the new mode');
|
||||
await run;
|
||||
assert.equal(readFileSync(first, 'utf8').trim(), 'one');
|
||||
assert.equal(r.bridge.pendingFor('mid').length, 0);
|
||||
// Bypass then Plan: nothing waiting, and the chat now reports Plan to the next call.
|
||||
assert.equal((await r.bridge.setMode('mid', 'plan')).mode, 'plan');
|
||||
assert.deepEqual(await r.bridge.setMode('nobody-yet', 'manual'), { applied: false, mode: 'manual', reason: 'no session yet' });
|
||||
});
|
||||
|
||||
test('the gate stops a helper asking once the chat has left Manual', async () => {
|
||||
const { apply, MANUAL_PRESET } = await import('../server/agent/plugins/strata-gate.mjs');
|
||||
let handler; const appended = [];
|
||||
const parent = { header: { origin: 'user' } };
|
||||
const child = { header: { origin: 'subagent', parentSession: 'p' }, append: (type, data) => appended.push([type, data.policy]) };
|
||||
let preset = MANUAL_PRESET; let override = 'ask';
|
||||
apply({ on: (_e, h) => { handler = h; }, inject: () => {}, sessions: new Map([['p', parent]]), permissionPresets: { current: () => preset }, approval: { overrideOf: () => override } });
|
||||
const exec = { name: 'write', agent: { session: child }, input: { file_path: 'x' } };
|
||||
await handler(exec, async () => ({ kind: 'allow' }));
|
||||
assert.deepEqual(appended, [], 'in Manual the helper keeps asking');
|
||||
preset = 'strata-bypass-ish';
|
||||
await handler(exec, async () => ({ kind: 'allow' }));
|
||||
assert.deepEqual(appended, [['approval/policy', 'never']], 'the first call after the switch un-pins the helper');
|
||||
override = 'never';
|
||||
await handler(exec, async () => ({ kind: 'allow' }));
|
||||
assert.equal(appended.length, 1, 'and does it once');
|
||||
});
|
||||
@@ -71,6 +71,12 @@ test('the working view says what is happening, from the host\'s words or the pha
|
||||
assert.equal(act.activityWords({ phase: 'checking' }), 'Checking the result…');
|
||||
assert.ok(act.phaseFraction('generating') > act.phaseFraction('checkpointing') && act.phaseFraction('checking') > act.phaseFraction('generating'));
|
||||
const panel = await readFile(new URL('../src/components/TimeSkipCompare.tsx', import.meta.url), 'utf8');
|
||||
assert.match(panel, /sandbox=""/, 'the preview frames carry no permissions');
|
||||
assert.ok(!/allow-scripts|allow-same-origin/.test(panel));
|
||||
// A page that draws itself with a script (a 3D scene) must run, or it shows as an empty dark page; the frame stays isolated and offline.
|
||||
assert.equal(cmp.HTML_PREVIEW_SANDBOX, 'allow-scripts');
|
||||
assert.match(panel, /sandbox={HTML_PREVIEW_SANDBOX}/);
|
||||
assert.ok(!/allow-same-origin|allow-forms|allow-popups|allow-top-navigation/.test(panel + cmp.HTML_PREVIEW_SANDBOX));
|
||||
const policy = cmp.htmlPreviewDocument('<p>x</p>');
|
||||
assert.match(policy, /script-src 'unsafe-inline'/); assert.ok(!/connect-src|https?:\/\//.test(policy.split('<body>')[0]), 'nothing may be fetched');
|
||||
assert.equal(cmp.needsOutsideFiles('<script src="https://cdn.example/three.js"></script>'), true);
|
||||
assert.equal(cmp.needsOutsideFiles('<script>draw()</script><a href="https://x.example">link</a>'), false);
|
||||
});
|
||||
Reference in new issue
Block a user