diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs index 4b97ae1d..c8d2cead 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, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import * as hardware from './hardware.mjs'; @@ -53,11 +53,11 @@ import { createRuntimeModels } from './runtime-models.mjs'; import { createNativeControl } from './native-control.mjs'; import { findControl, createControl, componentsDirectory } from './control-runtime.mjs'; import { forbidden as acquisitionForbidden } from './acquisition.mjs'; -import { timingSafeEqual } from 'node:crypto'; +import { randomBytes, timingSafeEqual } from 'node:crypto'; import { nativeGateway } from './native-gateway.mjs'; import { proxyCompletion } from './inference.mjs'; import { validateChatImages } from './chat-images.mjs'; -import { createTimeSkip } from './timeskip.mjs'; +import { createTimeSkip, measureFolder, timeskipRevisionMessage } from './timeskip.mjs'; const HERE = fileURLToPath(new URL('.', import.meta.url)); const ROOT = resolve(HERE, '..'); @@ -618,8 +618,13 @@ const REVISE_SCRIPT = resolve(REPO_ROOT, 'integrations', 'harness', 'revise_once // script — which is a *Python* program, so it is invoked with the interpreter, not with Node. // This is a configured path, never a value an HTTP caller supplies: accepting one would hand a // remote caller command execution on the user's machine. +// The default revision step is the app's own assistant (server/timeskip-revise.mjs, run by Node), not the Harness's Python bridge, which +// needs a Harness build next to the checkout that the installed app does not have. +const REVISE_NODE_SCRIPT = resolve(HERE, 'timeskip-revise.mjs'); const TIMESKIP_REVISE = process.env.STRATA_TIMESKIP_REVISE - ?? `${shellPrefix(PYTHON)} "${REVISE_SCRIPT}"`; + ?? `"${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'); /** * Tuning, from the App Host. * @@ -910,23 +915,61 @@ async function api(req, res, path, method, url) { } if (path === '/api/timeskip/start' && method === 'POST') { const body = await readBody(req); - const workspace = String(body.workspace ?? '').trim(); + const workspaceId = typeof body.workspaceId === 'string' ? body.workspaceId : null; + const workspace = String(body.workspace ?? '').trim() || ((workspaceId ? workspaces.find(w => w.id === workspaceId)?.path : null) ?? WORKSPACE); const prompt = String(body.prompt ?? '').trim().slice(0, 4000); const reviseCommand = body.useAgent === false ? null : TIMESKIP_REVISE; - const result = await timeskip.start({ + // A trial copies the folder (twice), so a huge folder is refused in plain words instead of filling the disk. + if (existsSync(workspace)) { + const size = measureFolder(workspace); + if (size.tooBig) return error(res, 400, 'This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.'); + } + const result = await timeskip.startDetached({ workspace, prompt, - attempts: body.attempts ?? 2, + attempts: body.attempts ?? 1, reviseCommand, - signal: AbortSignal.timeout(Number(process.env.STRATA_TIMESKIP_TIMEOUT_MS ?? 30 * 60 * 1000)), + 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); return json(res, 200, { run: result.run, simulated: false }); } + if (path === '/api/timeskip/files' && method === 'GET') { + const found = timeskip.files(url.searchParams.get('id')); + if (!found) return error(res, 404, 'No such Time-skip run.'); + return json(res, 200, found); + } + if (path === '/api/timeskip/stop' && method === 'POST') { + const body = await readBody(req); + return json(res, 200, { stopped: timeskip.cancel(String(body.id ?? '')) }); + } + // One revision attempt for a job this host started: the app's assistant works inside the candidate folder. + if (path === '/api/internal/timeskip-revise' && method === 'POST') { + const given = Buffer.from(String(req.headers['x-strata-internal'] ?? '')); + const want = Buffer.from(INTERNAL_SECRET); + if (given.length !== want.length || !timingSafeEqual(given, want)) return error(res, 403, 'Not allowed.'); + const body = await readBody(req); + const cwd = String(body.cwd ?? ''); + // 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; } })(); + 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; + try { + await agent.runTurn({ chatId, message: timeskipRevisionMessage(String(body.prompt ?? '')), workspacePath: cwd, choice: chosen, mode: 'bypass', thinking: 'low', history: [], onFrame: frame => { + if (frame.type === 'delta') text += frame.text ?? ''; + else if (frame.type === 'error') failure = frame.message; + } }); + } finally { agent.forget(chatId); } + if (failure) return error(res, 502, failure); + return json(res, 200, { text: text.slice(-600) }); + } if (path === '/api/timeskip/apply' && method === 'POST') { const body = await readBody(req); const result = await timeskip.apply({ id: body.id, workspace: body.workspace ?? null, - dryRun: Boolean(body.dryRun), restore: Boolean(body.restore), + dryRun: Boolean(body.dryRun), restore: Boolean(body.restore), attempt: body.attempt ?? null, }); if (!result.ok) { // A concurrent user edit is a conflict the caller must see, not a server error to retry. diff --git a/apps/host/server/timeskip-revise.mjs b/apps/host/server/timeskip-revise.mjs new file mode 100644 index 00000000..9656414a --- /dev/null +++ b/apps/host/server/timeskip-revise.mjs @@ -0,0 +1,36 @@ +#!/usr/bin/env node +/** + * One revision attempt for Time-skip, performed by the app's own assistant. + * + * Strata Control runs this as its `--revise-command`, with the candidate folder (an isolated copy of + * the user's work) as the working directory, the request in STRATA_TIMESKIP_PROMPT and the attempt + * number in STRATA_TIMESKIP_ATTEMPT. It asks the host (which owns the model and the Harness) for one + * agent turn inside that folder and returns when the turn ends. Exit 0 means "an attempt was made", + * not "it helped": whether it helped is decided by the checks and, failing those, by the person. + */ +const base = process.env.STRATA_HOST_URL; +const secret = process.env.STRATA_INTERNAL_SECRET; +const prompt = process.env.STRATA_TIMESKIP_PROMPT ?? ''; +const attempt = Number(process.env.STRATA_TIMESKIP_ATTEMPT ?? 1); + +if (!base || !secret || !prompt) { + console.error('The revision step needs the Strata app to be running.'); + process.exit(2); +} + +try { + const res = await fetch(`${base}/api/internal/timeskip-revise`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-strata-internal': secret }, + body: JSON.stringify({ cwd: process.cwd(), prompt, attempt }), + }); + const body = await res.json().catch(() => ({})); + if (!res.ok) { + console.error(body.error ?? `The assistant could not make the change (HTTP ${res.status}).`); + process.exit(1); + } + console.log(String(body.text ?? '').trim()); +} catch (e) { + console.error(`The assistant could not be reached: ${e.message}`); + process.exit(1); +} diff --git a/apps/host/server/timeskip.mjs b/apps/host/server/timeskip.mjs index 1b8804ef..0b05d592 100644 --- a/apps/host/server/timeskip.mjs +++ b/apps/host/server/timeskip.mjs @@ -18,8 +18,8 @@ * run id immediately and the client follows it with `/api/timeskip/status`. */ import { spawn } from 'node:child_process'; -import { existsSync, readFileSync, readdirSync } from 'node:fs'; -import { join } from 'node:path'; +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; import { timeSkipDir } from './platform-paths.mjs'; /** Where runs are recorded. Mirrors the CLI's own default resolution. */ @@ -87,6 +87,111 @@ function summarise(run) { }; } +const TERMINAL = new Set(['completed', 'cancelled', 'failed', 'interrupted']); +const SKIP_DIRS = new Set(['.git', '.strata', '__pycache__', 'node_modules']); +const MAX_TEXT_BYTES = 200_000; +const MAX_LISTED = 60; +const MAX_WITH_TEXT = 12; + +/** Every file under a folder, as relative forward-slash paths. */ +function walkFiles(root) { + const out = []; + if (!root || !existsSync(root)) return out; + const walk = dir => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (out.length > 5000) return; + const full = join(dir, entry.name); + if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) walk(full); } + else if (entry.isFile()) out.push(relative(root, full).split('\\').join('/')); + } + }; + walk(root); + return out.sort(); +} + +function readText(path) { + try { + if (statSync(path).size > MAX_TEXT_BYTES) return { big: true }; + const buffer = readFileSync(path); + if (buffer.subarray(0, 4096).includes(0)) return { binary: true }; + return { text: buffer.toString('utf8') }; + } catch { return { missing: true }; } +} + +/** What the assistant is told for one revision attempt. It works on a copy, so it is told to stay in it and to say what it did. */ +export function timeskipRevisionMessage(request) { + return [ + 'You are improving a copy of the user\'s work. The current folder is that copy: the original is safe and you cannot see it.', + 'Rules:', + '1. Work only inside the current folder. Never read or write outside it.', + '2. Make the change the user asked for by creating or editing files here. If the folder is empty, create the file(s) the request needs.', + '3. Do not delete the user\'s files unless the request says to.', + '4. Do not run long programs or start servers.', + '5. When you are done, answer in one or two plain sentences: what you changed.', + '', + 'The request:', + String(request).trim(), + ].join('\n'); +} + +/** How big a folder is, stopping early once it is clearly too big to copy for a trial. */ +export function measureFolder(root, { maxFiles = 3000, maxBytes = 300 * 1024 * 1024 } = {}) { + let files = 0, bytes = 0, tooBig = false; + const walk = dir => { + if (tooBig) return; + let entries; + try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const entry of entries) { + const full = join(dir, entry.name); + if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) walk(full); } + else if (entry.isFile()) { + files += 1; + try { bytes += statSync(full).size; } catch { /* ignore */ } + if (files > maxFiles || bytes > maxBytes) { tooBig = true; return; } + } + if (tooBig) return; + } + }; + walk(root); + return { files, bytes, tooBig }; +} + +/** + * What a run changed, file by file: the saved original against the revision, for the Compare view. + * Reads the folders the job itself kept; it decides nothing. + */ +export function diffRun(record) { + const baseline = (record.checkpoints ?? []).find(c => c.label === 'baseline'); + const selected = (record.checkpoints ?? []).find(c => c.id === record.selected_checkpoint); + const attempts = record.attempts ?? []; + const last = attempts[attempts.length - 1] ?? null; + // A kept checkpoint is the revision; when nothing was kept (the checks could not decide) the person looks at the last attempt. + const useAttempt = !selected || selected.id === baseline?.id; + const updatedRoot = useAttempt ? last?.path : selected?.path; + const baseRoot = baseline?.path; + if (!baseRoot || !updatedRoot) return { files: [], applyAttempt: null, more: 0 }; + const paths = [...new Set([...walkFiles(baseRoot), ...walkFiles(updatedRoot)])].sort(); + const files = []; + let withText = 0, more = 0; + for (const path of paths) { + const a = readText(join(baseRoot, path)), b = readText(join(updatedRoot, path)); + const status = a.missing ? 'added' : b.missing ? 'removed' : null; + const same = !status && a.text !== undefined && a.text === b.text; + if (same) continue; + if (!status && !a.text && !b.text && !a.big && !b.big) { + // Both binary: compare sizes only. + try { if (statSync(join(baseRoot, path)).size === statSync(join(updatedRoot, path)).size && readFileSync(join(baseRoot, path)).equals(readFileSync(join(updatedRoot, path)))) continue; } catch { /* treat as changed */ } + } + if (files.length >= MAX_LISTED) { more += 1; continue; } + const entry = { path, status: status ?? 'changed' }; + const textual = (a.text !== undefined || a.missing) && (b.text !== undefined || b.missing); + if (textual && withText < MAX_WITH_TEXT) { entry.original = a.text ?? ''; entry.updated = b.text ?? ''; withText += 1; } + else entry.unreadable = true; + files.push(entry); + } + return { files, applyAttempt: useAttempt ? (last?.index ?? null) : null, more }; +} + /** * Run one `strata timeskip …` command and collect its result. * @@ -97,6 +202,10 @@ function summarise(run) { export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = 30 * 60 * 1000, env = process.env } = {}) { const cli = join(repoRoot, 'strata.py'); + /** Runs this host started and is still driving. A run that is not terminal and not in here died with its host. */ + const live = new Map(); + const withLive = summary => (summary && !TERMINAL.has(summary.phase) && !live.has(summary.id) ? { ...summary, phase: 'interrupted' } : summary); + function runCli(args, { signal } = {}) { return new Promise((resolve) => { const root = stateDir(env); @@ -165,13 +274,28 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = stateDir: () => stateDir(env), /** Every recorded run, newest first. */ - list: () => listRuns(stateDir(env)), + list: () => listRuns(stateDir(env)).map(withLive), /** One run's durable record, or null. */ status: (id) => { if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null; const run = readRun(stateDir(env), id); - return run ? summarise(run) : null; + return run ? withLive(summarise(run)) : null; + }, + + /** The changed files of a run (saved original against the revision), for the Compare view. */ + files: id => { + if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null; + const run = readRun(stateDir(env), id); + return run ? diffRun(run) : null; + }, + + /** Stop a run this host is driving. The saved version stays; the run reads as interrupted. */ + cancel: id => { + const child = live.get(id); + if (!child) return false; + try { child.kill('SIGTERM'); } catch { /* already gone */ } + return true; }, /** @@ -198,8 +322,54 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = return run ? { ok: true, run: summarise(run) } : { ok: false, code: 6, error: 'the job reported success but wrote no run record' }; }, + /** + * Start a run and return as soon as its record exists; the job goes on without the caller waiting. + * The caller follows the run id with `status`. A command that ends before any record appears is an error, in the command's words. + */ + async startDetached({ workspace, prompt, attempts = 1, reviseCommand = null, extraEnv = {} } = {}) { + if (!workspace || typeof workspace !== 'string') return { ok: false, code: 2, error: 'workspace is required' }; + if (!prompt || typeof prompt !== 'string') return { ok: false, code: 2, error: 'prompt is required' }; + const root = stateDir(env); + const before = new Set(existsSync(root) ? readdirSync(root) : []); + const args = ['timeskip', 'run', '--workspace', workspace, '--prompt', prompt, + '--attempts', String(Math.max(0, Math.min(10, Number(attempts) || 0))), '--output', 'json']; + if (reviseCommand) args.push('--revise-command', reviseCommand); + const child = spawn(python, [...pythonArgs, cli, ...args], { + cwd: repoRoot, windowsHide: true, env: { ...env, ...extraEnv, STRATA_TIMESKIP_DIR: root }, stdio: ['ignore', 'pipe', 'pipe'], + }); + let out = '', err = '', closed = null; + child.stdout.on('data', b => { out += b.toString(); }); + child.stderr.on('data', b => { err += b.toString(); }); + const ended = new Promise(resolve => { + child.on('error', e => { closed = { code: null, error: `could not start the Time-skip command: ${e.message}` }; resolve(); }); + child.on('close', code => { closed = { code }; resolve(); }); + }); + const deadline = Date.now() + 20_000; + let id = null; + while (!id && Date.now() < deadline) { + if (existsSync(root)) { + for (const name of readdirSync(root)) { + if (before.has(name)) continue; + const run = readRun(root, name); + if (run && run.prompt === prompt) { id = name; break; } + } + } + if (id || closed) break; + await new Promise(r => setTimeout(r, 100)); + } + if (!id) { + if (!closed) { try { child.kill('SIGTERM'); } catch { /* gone */ } return { ok: false, code: 6, error: 'the Time-skip job did not start in time' }; } + let message = closed.error ?? ''; + try { const parsed = JSON.parse(out.trim().split('\n').filter(Boolean).pop() ?? ''); message = message || parsed?.error?.message || parsed?.error || ''; } catch { /* not JSON */ } + return { ok: false, code: closed.code ?? 6, error: String(message || err.trim() || out.trim() || 'the Time-skip command ended without a run').slice(0, 600) }; + } + live.set(id, child); + void ended.then(() => live.delete(id)); + return { ok: true, run: withLive(summarise(readRun(root, id))) }; + }, + /** Apply the retained result, or preview it. Refuses when the destination changed. */ - async apply({ id, workspace = null, dryRun = false, restore = false, signal } = {}) { + async apply({ id, workspace = null, dryRun = false, restore = false, attempt = null, signal } = {}) { if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) { return { ok: false, code: 2, error: 'a run id is required' }; } @@ -207,6 +377,7 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = if (workspace) args.push('--workspace', workspace); if (dryRun) args.push('--dry-run'); if (restore) args.push('--restore'); + if (attempt !== null && attempt !== undefined) args.push('--attempt', String(Math.max(1, Math.floor(Number(attempt)) || 1))); const result = await runCli(args, { signal }); if (!result.ok) { // Exit 6 is the documented "refused / uncertain" code, which is how a concurrent user edit diff --git a/apps/host/src/components/OnboardingArt.tsx b/apps/host/src/components/OnboardingArt.tsx index 1e506b5a..38b8286b 100644 --- a/apps/host/src/components/OnboardingArt.tsx +++ b/apps/host/src/components/OnboardingArt.tsx @@ -55,9 +55,9 @@ function DownloadCounter({ value, label }: { return
; } const tour = [ - { label: 'Time-skip', command: '/time-skip', prompt: 'Improve this launch plan.', title: 'Keep the stronger idea.', description: 'Type /time-skip and what you want to improve. Strata explores a revision, compares it with the original, and keeps the stronger version.', badge: 'Preview', steps: ['Save the original', 'Explore a revision', 'Compare and keep'] }, - { label: 'Goal', command: '/goal', prompt: 'Get my portfolio ready to publish.', title: 'Give your AI a finish line.', description: 'A goal describes the outcome you want. Strata will plan the work, check its progress, and keep going until that outcome is reached.', badge: 'Coming soon', steps: ['Set the outcome', 'Work through the plan', 'Check the result'] }, - { label: 'Loop', command: '/loop', prompt: '', title: 'Let useful work repeat.', description: 'Type /loop to open Tasks. Choose a task, set its schedule, and let Strata repeat it — like a daily briefing every weekday at 8.', badge: '', steps: ['Open Tasks', 'Pick a schedule', 'Repeat automatically'] }, + { label: 'Time-skip', command: '/time-skip', prompt: 'Improve this launch plan.', title: 'Keep the stronger idea.', description: 'Type /time-skip and what you want to improve. Strata explores a revision, compares it with the original, and keeps the stronger version.', badge: '', steps: ['Save the original', 'Explore a revision', 'Compare and keep'] }, + { label: 'Goal', command: '/goal', prompt: 'Get my portfolio ready to publish.', title: 'Give your AI a finish line.', description: 'A goal describes the outcome you want. Strata will plan the work, check its progress, and keep going until that outcome is reached.', badge: '', steps: ['Set the outcome', 'Work through the plan', 'Check the result'] }, + { label: 'Loop', command: '/loop', prompt: '10m check whether the build passes.', title: 'Let useful work repeat.', description: 'Type /loop, how often, and what to do — for example /loop 10m check the build. Strata sends it again and again while the chat is open. For work that must go on with Strata closed, use Tasks.', badge: '', steps: ['Say how often', 'Say what to do', 'Stop any time'] }, { label: 'Subagents', command: 'Spawn subagents', prompt: 'to research, draft and review my launch plan.', title: 'More hands, one conversation.', description: 'Ask “spawn subagents” in chat and describe the jobs. Separate agents can research, write and review in parallel, then bring their work back to you.', badge: '', steps: ['Describe the jobs', 'Agents work in parallel', 'Bring the results together'] }, ] as const; export function OnboardingTour({ page, onChange }: { diff --git a/apps/host/src/components/TimeSkipPanel.tsx b/apps/host/src/components/TimeSkipPanel.tsx index dc6b42f5..b5a3b3c6 100644 --- a/apps/host/src/components/TimeSkipPanel.tsx +++ b/apps/host/src/components/TimeSkipPanel.tsx @@ -1,8 +1,8 @@ import { tr } from '../lib/i18n'; import { useEffect, useRef, useState } from 'react'; import type { PreviewArtifact } from '../lib/artifacts'; -import { replayTimeSkip, setTimeSkipResult } from '../lib/store'; -import { timeSkipDocumentMarkdown, timeSkipDocuments, timeSkipExample, timeSkipResultState, type TimeSkipDocument, type TimeSkipRun, type TimeSkipVersion } from '../lib/time-skip'; +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 { FloatingMenu } from './FloatingMenu'; import { Btn, Dialog, Icon } from './ui'; function VersionTabs({ version, onChange, done }: { @@ -62,6 +62,21 @@ function ResultDocument({ document, original, highlight = false, label, imageCom {tr(!document.image ?

{tr("Success check")}{tr(goal ? {tr("Setup goal")} : null)}

{tr(document.successCheck)}

{tr(goal ? : null)}
: null)} ; } +function RealDetails({ run }: { run: TimeSkipRun }) { + const job = run.job!; + const outcomes = timeSkipCheckOutcomes(run); + return <> +

{tr("Checks")}

+ {outcomes.length ?
+
{tr("Check")}{tr("Result")}
+ {outcomes.map(c =>
{c.id}{c.outcome}
)} +
:

{tr("No checks are set up for this folder, so nothing was judged automatically. Look at the two versions and choose which to keep.")}

} +

{tr("History")}

+
  1. {tr("Original saved")}{tr("Preserved before any changes.")}
  2. + {job.attempts.map(a =>
  3. {tr('Revision {0}', [a.index])}{a.reason}
  4. )}
+ {job.error ?

{tr("What went wrong")}{plainTimeSkipError(job.error)}

: null} + ; +} export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onClose, onPreview }: { run: TimeSkipRun; sessionId: string; @@ -80,7 +95,8 @@ export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onC const panel = useRef(null); const menuAnchor = useRef(null); const { frame, ready, kept, status } = timeSkipResultState(run, now); - const documents = timeSkipDocuments(run.prompt); + const real = !!run.job; + const documents = run.job ? realTimeSkipDocuments(run.job) : timeSkipDocuments(run.prompt); const checks = timeSkipExample(run.prompt); const sideBySide = expanded && wide; useEffect(() => { @@ -100,6 +116,10 @@ export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onC useEffect(() => { setVersion(run.retainedVersion ?? 'updated'); setDetails(false); setMenu(false); setImageCompare(false); }, [run.id, run.startedAt, run.retainedVersion]); function openResult(which: TimeSkipVersion) { const document = documents[which]; + if (real) { + onPreview({ id: `${run.id}-${run.startedAt}-${which}`, kind: 'markdown', title: `${which === 'original' ? 'Original' : 'Updated'} · ${document.title}`, content: timeSkipDocumentMarkdown(document) }); + return; + } if (document.image) { onPreview({ id: `${run.id}-${run.startedAt}-${which}`, kind: 'image', title: `${which}-fieldnotes-cover.svg`, url: document.image.url, demo: true }); return; @@ -135,26 +155,30 @@ export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onC {tr(result(which))} ))} :
{tr(result(version))}
)} - {tr(ready ?

{tr("What changed")}{tr(documents.changes.length)}{tr(" updates")}

    {tr(documents.changes.map((change, i) =>
  • {tr(change)}
  • ))}
: null)} - {tr(kept === 'original' && frame.done ?
{tr("Original restored in this example.")}
: null)} + {tr(ready && (!real || documents.changes.length > 0) ?

{tr("What changed")}{tr(documents.changes.length)}{tr(" updates")}

    {tr(documents.changes.map((change, i) =>
  • {tr(change)}
  • ))}
: null)} + {tr(!real && kept === 'original' && frame.done ?
{tr("Original restored in this example.")}
: null)} + {real && frame.done && (run.job?.files?.length ?? 0) > 0 ?
+

{tr(run.retainedVersion === 'updated' ? 'The update is in your files. You can put the original back.' : 'Your files are unchanged. Keep the update to put it in your folder; you can put the original back later.')}

+ {run.retainedVersion === 'updated' ? restore('original')}>{tr('Put the original back')} : restore('updated')}>{tr('Keep the update')}} +
: null}

{tr("Request")}{run.prompt}

-

{tr("Same checks, both versions")}

+ {real ? : <>

{tr("Same checks, both versions")}

{tr("Check")}{tr("Original")}{tr("Updated")}
{tr(checks.labels.map((label, i) =>
{tr(label)}{tr(checks.original[i])}{tr(frame.index >= 4 ? checks.improved[i] : 'Pending')}
))}

{tr("History")}

  1. {tr("Original saved")}{tr("Preserved before any revisions.")}
  2. {tr(ready ?
  3. {tr(frame.index >= 4 ? 'Update passed the example checks' : 'Update ready for checking')}{tr(checks.correction)}
  4. : null)}{tr(frame.index >= 5 ?
  5. = 7 ? 'x' : 'clock'} size={14}/>{tr(frame.index >= 7 ? 'Later revision not kept' : 'Checking a later revision')}{tr(frame.index >= 7 ? checks.rejection : 'The saved update stays available.')}
  6. : null)}
- {tr(frame.index >= 7 ?
{tr("View the rejected revision")}
: null)} + {tr(frame.index >= 7 ?
{tr("View the rejected revision")}
: null)}}
{tr(sideBySide ? openResult('original')} icon="file">{tr("Open original")} : null)} openResult(sideBySide ? 'updated' : version)}>{tr(!sideBySide && version === 'original' ? 'Open original' : 'Open result')}
- {tr(menu ? setMenu(false)}> : null)} + {tr(menu ? setMenu(false)}>{real ? (!frame.done ? : null) : } : null)} ; return inline ? content : {tr(content)}; } diff --git a/apps/host/src/lib/commands.ts b/apps/host/src/lib/commands.ts index 8f0b962a..f09d2b12 100644 --- a/apps/host/src/lib/commands.ts +++ b/apps/host/src/lib/commands.ts @@ -39,7 +39,6 @@ export const DESTINATIONS: { route: Route; label: string; icon: IconName; keywor { route: 'settings', label: 'Settings', icon: 'settings', keywords: 'preferences theme appearance text size', key: '8' }, ]; export const APP_COMMANDS: AppCommand[] = [ - { id: 'go:loop', label: 'Tasks', hint: 'Set up a repeating task', group: 'Navigation', icon: 'clock', palette: false, slash: ['loop'], run: () => go('tasks') }, { id: 'new', label: 'New chat', hint: 'Start a new conversation; keep this one', group: 'Session', key: 'n', icon: 'new-chat', slash: ['new'], run: () => { const s = newSession(); go('chat', s.id); } }, { id: 'palette', label: 'Command palette', group: 'Session', key: 'k', icon: 'search', palette: false, run: () => setPalette(!getState().paletteOpen) }, { id: 'sidebar', label: 'Show or hide sidebar', group: 'Session', key: 'b', icon: 'panel', run: () => window.innerWidth < 1280 ? setNavOpen(!getState().navOpen) : toggleRail() }, diff --git a/apps/host/src/lib/loop.ts b/apps/host/src/lib/loop.ts new file mode 100644 index 00000000..5698c1cf --- /dev/null +++ b/apps/host/src/lib/loop.ts @@ -0,0 +1,48 @@ +/** + * /loop: send the same message again and again, every few minutes, while this chat is open. + * + * /loop 10m check whether the build passes start (the message is sent now, then every 10 minutes) + * /loop stop stop + * /loop say whether a loop is running + * + * The loop lives in the app window: it waits for the chat to be idle, and it stops when the window closes. + * For work that must go on with the app closed, a task on the Tasks screen is the right tool. + */ + +export const LOOP_MIN_MS = 60_000; +export const LOOP_MAX_MS = 24 * 3_600_000; +export const LOOP_MAX_RUNS = 100; + +export type LoopCommand = + | { kind: 'start'; everyMs: number; prompt: string } + | { kind: 'stop' } + | { kind: 'status' } + | { kind: 'help'; problem: string }; + +const UNITS: Record = { s: 1000, sec: 1000, second: 1000, seconds: 1000, m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000, h: 3_600_000, hr: 3_600_000, hour: 3_600_000, hours: 3_600_000 }; + +/** The words shown when a /loop line is not understood. */ +export const LOOP_USAGE = 'Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Use /loop stop to stop.'; + +/** null means the text is an ordinary message. */ +export function parseLoop(text: string): LoopCommand | null { + const match = text.trim().match(/^\/loop(?:\s+([\s\S]*))?$/i); + if (!match) return null; + const rest = (match[1] ?? '').trim(); + if (!rest) return { kind: 'status' }; + if (/^(stop|off|cancel|end)$/i.test(rest)) return { kind: 'stop' }; + const timed = rest.match(/^(?:every\s+)?(\d+(?:\.\d+)?)\s*([a-z]+)\s+([\s\S]+)$/i); + const unit = timed ? UNITS[timed[2].toLowerCase()] : undefined; + if (!timed || !unit) return { kind: 'help', problem: 'Say how often first, like 10m (minutes) or 2h (hours), then what to do.' }; + const everyMs = Math.round(Number(timed[1]) * unit); + if (everyMs < LOOP_MIN_MS) return { kind: 'help', problem: 'The shortest time between runs is 1 minute, so the model has time to finish each one.' }; + if (everyMs > LOOP_MAX_MS) return { kind: 'help', problem: 'The longest time between runs is 24 hours. For longer waits, use a task on the Tasks screen.' }; + return { kind: 'start', everyMs, prompt: timed[3].trim() }; +} + +/** "every 10 minutes", "every hour". */ +export function loopEvery(ms: number): string { + if (ms % 3_600_000 === 0) { const h = ms / 3_600_000; return h === 1 ? 'every hour' : `every ${h} hours`; } + const m = Math.round(ms / 60_000); + return m === 1 ? 'every minute' : `every ${m} minutes`; +} diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index 5dd878fd..64aecd24 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -1,13 +1,14 @@ import { plainFailure, plainFailureText } from './plain-errors'; import { showcaseMessages, SHOWCASE_AGENTS } from './chat-showcase'; import { updateAgent } from './agents'; -import { TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; +import { LOOP_MAX_RUNS, LOOP_USAGE, loopEvery, parseLoop, type LoopCommand } from './loop'; +import { TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; import { PREVIEW_EXAMPLES, type PreviewArtifact } from './artifacts'; import { lifecyclePolicy } from './lifecycle'; import { newestServingState } from './serving-state'; import { photoData, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; import { nativeState } from './native'; -import { setTranslationLanguage, validLanguage, type Language } from './i18n'; +import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n'; /** * Strata app store. * @@ -1076,7 +1077,7 @@ const timeSkipTimers = new Map>(); function scheduleTimeSkip(sessionId: string, run: TimeSkipRun) { const timerId = `${sessionId}:${run.id}`; clearTimeout(timeSkipTimers.get(timerId)); - if (run.completedAt) return; + if (run.completedAt || run.job) return; timeSkipTimers.set(timerId, setTimeout(() => { timeSkipTimers.delete(timerId); const session = state.sessions.find(s => s.id === sessionId); @@ -1102,11 +1103,127 @@ export function replayTimeSkip(sessionId: string, runId: string) { export function setTimeSkipResult(sessionId: string, runId: string, version: TimeSkipVersion) { const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); if (!run) return; + if (run.job) { void keepTimeSkip(sessionId, runId, version); return; } const next = withTimeSkipResult(run, version, Date.now()); if (next === run) return; patchSession(sessionId, s => ({ ...s, timeSkips: s.timeSkips?.map(r => r.id === runId ? next : r) })); } +/* ------------------------------------------------------- Time-skip, for real + The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the + person chooses. The sidebar follows the job's own record; nothing here invents progress. */ +const TS_TERMINAL = ['completed', 'cancelled', 'failed', 'interrupted']; +const TS_WORKING = () => tr('Working on a copy of your files. Your files are not touched until you choose to keep the update. Follow the progress in the sidebar.'); +const TS_READY = () => tr('The result is ready. Switch between Original and Updated, or compare them side by side. Your files stay as they are until you keep the update.'); + +function patchRun(sessionId: string, runId: string, fn: (run: TimeSkipRun) => TimeSkipRun, content?: string) { + patchSession(sessionId, s => ({ ...s, updatedAt: new Date().toISOString(), + timeSkips: s.timeSkips?.map(r => r.id === runId ? fn(r) : r), + messages: content === undefined ? s.messages : s.messages.map(m => m.timeSkipId === runId && m.role === 'assistant' ? { ...m, content } : m), + })); +} + +/** The job's error in a sentence a person can use. */ +export function plainTimeSkipError(raw: string | null | undefined): string { + const text = String(raw ?? '').trim(); + if (!text) return tr('Something went wrong.'); + const afterExit = /\(exit \d+\):\s*([\s\S]*)$/.exec(text); + const body = (afterExit?.[1] ?? text).replace(/^\w*Error:\s*/, '').trim(); + if (/destination changed|refusing to overwrite/i.test(body)) return tr('Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.'); + if (/too big/i.test(body)) return body; + if (/Load a model|model first/i.test(body)) return tr('Load a model first, then try Time-skip again.'); + if (/needs the Strata app|could not be reached/i.test(body)) return tr('The assistant could not be reached. Try again.'); + return body.length > 300 ? body.slice(0, 299) + '…' : body; +} + +function timeSkipEnding(job: TimeSkipJob, files: TimeSkipFile[]): string { + if (job.phase === 'failed') return tr('Time-skip stopped. {0} Your files were not changed.', [plainTimeSkipError(job.error)]); + if (job.phase === 'cancelled' || job.phase === 'interrupted') return tr('Time-skip was stopped before it finished. Your files were not changed.'); + if (!files.length) return tr('The assistant did not change anything, so there is nothing to compare. Your files were not changed.'); + return TS_READY(); +} + +async function startTimeSkipReal(prompt: string) { + const sessionId = state.activeSession ?? newSession().id; + const run: TimeSkipRun = { id: uid('ts'), prompt, startedAt: Date.now(), + job: { id: '', phase: 'queued', attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null } }; + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, + defaultTitle: false, + title: s.messages.length ? s.title : prompt.length > 48 ? prompt.slice(0, 47).trimEnd() + '…' : prompt, updatedAt: at, + timeSkips: [...(s.timeSkips ?? []), run], previewOpen: timeSkipTabId(run.id), + messages: [...s.messages, + { id: uid('m'), role: 'user', at, content: '/time-skip ' + prompt, timeSkipId: run.id }, + { id: uid('m'), role: 'assistant', at, timeSkipId: run.id, content: TS_WORKING() }, + ], + })); + go('chat', sessionId); + try { + const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, workspaceId: state.activeWorkspace, attempts: 1 }); + patchRun(sessionId, run.id, r => ({ ...r, job: started.run })); + void followTimeSkip(sessionId, run.id); + } catch (e) { + const message = plainTimeSkipError(e instanceof Error ? e.message : String(e)); + patchRun(sessionId, run.id, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'failed', error: message } }), tr('Time-skip could not start. {0}', [message])); + } +} + +const followingTimeSkips = new Set(); +/** Read the job's record until it ends. Safe to call again for a run already being followed. */ +export async function followTimeSkip(sessionId: string, runId: string) { + const key = sessionId + ':' + runId; + if (followingTimeSkips.has(key)) return; + followingTimeSkips.add(key); + let misses = 0; + try { + for (;;) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + if (!run?.job?.id || run.completedAt) return; + let job: TimeSkipJob | null = null; + try { job = (await api.get<{ run: TimeSkipJob }>('/api/timeskip/status?id=' + encodeURIComponent(run.job.id))).run; misses = 0; } + catch { misses += 1; } + if (job && TS_TERMINAL.includes(job.phase)) { + let files: TimeSkipFile[] = [], extra: Partial = {}; + 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 */ } + const finished = job; + patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files)); + return; + } + if (job) { const live = job; patchRun(sessionId, runId, r => ({ ...r, job: { ...r.job!, ...live } })); } + if (misses >= 6) { + patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, phase: 'interrupted' } }), tr('Time-skip lost contact with the app and stopped. Your files were not changed.')); + return; + } + await new Promise(r => setTimeout(r, 2000)); + } + } finally { followingTimeSkips.delete(key); } +} + +/** Ask the host to stop a running trial. The saved version stays. */ +export async function stopTimeSkip(sessionId: string, runId: string) { + const id = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId)?.job?.id; + if (id) await api.post('/api/timeskip/stop', { id }).catch(() => undefined); +} + +/** Put the update into the person's files, or put the original back. Both are checked and undoable. */ +export async function keepTimeSkip(sessionId: string, runId: string, version: TimeSkipVersion) { + const run = state.sessions.find(s => s.id === sessionId)?.timeSkips?.find(r => r.id === runId); + const job = run?.job; + if (!run || !job?.id || !job.phase || !TS_TERMINAL.includes(job.phase)) return; + if ((run.retainedVersion ?? 'original') === version) { patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); return; } + try { + if (version === 'updated') await api.post('/api/timeskip/apply', { id: job.id, attempt: job.applyAttempt ?? null }); + else await api.post('/api/timeskip/apply', { id: job.id, restore: true }); + patchRun(sessionId, runId, r => ({ ...r, retainedVersion: version })); + pushToast('success', version === 'updated' ? tr('The update is now in your files') : tr('Your original files are back'), version === 'updated' ? tr('You can switch back to the original any time from this panel.') : undefined); + } catch (e) { + pushToast('error', tr('Your files were not changed'), plainTimeSkipError(e instanceof Error ? e.message : String(e))); + } +} + function startTimeSkipDemo(prompt: string) { if (!prompt) { pushToast('info', 'Add a prompt after /time-skip', 'For example: /time-skip Make a launch plan for my app'); return; } const sessionId = state.activeSession ?? newSession().id; @@ -1255,10 +1372,72 @@ export function exportConversation() { setTimeout(() => URL.revokeObjectURL(url), 1000); } -export async function sendMessage(text: string) { +/* ---------------------------------------------------------------- /loop + The same message, again and again, while the chat is open. See lib/loop.ts. */ +interface LoopState { everyMs: number; prompt: string; runs: number; timer: ReturnType | null } +const loops = new Map(); + +/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */ +function addNote(sessionId: string, content: string) { + const at = new Date().toISOString(); + patchSession(sessionId, s => ({ ...s, updatedAt: at, messages: [...s.messages, { id: uid('m'), role: 'assistant', at, content, local: true }] })); +} + +export function loopIsRunning(sessionId: string | null): boolean { return !!sessionId && loops.has(sessionId); } + +function stopLoop(sessionId: string): boolean { + const loop = loops.get(sessionId); + if (!loop) return false; + if (loop.timer) clearTimeout(loop.timer); + loops.delete(sessionId); + return true; +} + +function scheduleLoop(sessionId: string) { + const loop = loops.get(sessionId); + if (!loop) return; + loop.timer = setTimeout(() => void tickLoop(sessionId), loop.everyMs); +} + +async function tickLoop(sessionId: string) { + const loop = loops.get(sessionId); + if (!loop) return; + if (!state.sessions.some(s => s.id === sessionId)) { stopLoop(sessionId); return; } + // Wait for a quiet moment: this chat is open and nothing is being answered. + if (state.activeSession !== sessionId || state.streaming) { loop.timer = setTimeout(() => void tickLoop(sessionId), 15_000); return; } + loop.runs += 1; + if (loop.runs > LOOP_MAX_RUNS) { stopLoop(sessionId); addNote(sessionId, tr('The loop stopped after {0} runs. Type /loop again to start it again.', [LOOP_MAX_RUNS])); return; } + await sendMessage(loop.prompt, { fromLoop: true }); + scheduleLoop(sessionId); +} + +async function runLoopCommand(command: LoopCommand) { + const sessionId = state.activeSession ?? newSession().id; + const say = (content: string) => { addNote(sessionId, content); go('chat', sessionId); }; + if (command.kind === 'help') { say(tr(command.problem) + '\n\n' + tr(LOOP_USAGE)); return; } + if (command.kind === 'status') { + const loop = loops.get(sessionId); + say(loop ? tr('A loop is running in this chat: it sends "{0}" {1}, while this chat is open. Type /loop stop to stop it.', [loop.prompt, loopEvery(loop.everyMs)]) : tr('No loop is running in this chat.') + '\n\n' + tr(LOOP_USAGE)); + return; + } + if (command.kind === 'stop') { say(stopLoop(sessionId) ? tr('The loop is stopped.') : tr('No loop is running in this chat.')); return; } + if (loops.has(sessionId)) { say(tr('This chat already has a loop. Type /loop stop first, then start a new one.')); return; } + loops.set(sessionId, { everyMs: command.everyMs, prompt: command.prompt, runs: 1, timer: null }); + addNote(sessionId, tr('Loop started: "{0}" {1}, while this chat is open. Type /loop stop to stop it. For work that must go on with Strata closed, use the Tasks screen.', [command.prompt, loopEvery(command.everyMs)])); + go('chat', sessionId); + await sendMessage(command.prompt, { fromLoop: true }); + scheduleLoop(sessionId); +} + +export async function sendMessage(text: string, options: { fromLoop?: boolean } = {}) { if(state.streaming)return; + const loopCommand = options.fromLoop ? null : parseLoop(text.trim()); + if (loopCommand) { await runLoopCommand(loopCommand); return; } const demoPrompt = timeSkipPrompt(text.trim()); - if (demoPrompt !== null) { startTimeSkipDemo(demoPrompt); return; } + if (demoPrompt !== null) { + if (demoPrompt && nativeState()?.instances.some(i => i.status === 'ready') && !state.remoteModel) void startTimeSkipReal(demoPrompt); else startTimeSkipDemo(demoPrompt); + return; + } const imageTarget=nativeState()?.instances.find(i=>i.id===nativeState()?.defaultId);const canSendPictures=!state.remoteModel&&imageTarget?.status==='ready'&&imageTarget.vision; if(pendingChatPhotos(state.activeSession).length&&!canSendPictures){pushToast('error','Choose an image-reading model','Switch to a local model with Read pictures enabled, or remove the attachments.');return;} const pictures=takeChatPhotos(state.activeSession); @@ -1290,7 +1469,7 @@ export async function sendMessage(text: string) { The context meter was reading the same empty array, which is why it sat at ~350 tokens however long the conversation grew. */ const prior = (state.sessions.find((s) => s.id === sessionId)?.messages ?? []) - .filter(m => !m.timeSkipId) + .filter(m => !m.timeSkipId && !m.local) .filter((m) => m.role === 'user' || m.role === 'assistant') .filter((m) => m.content.trim()) .map((m) => ({ role: m.role, content: m.content,photos:m.photos })) @@ -1488,7 +1667,7 @@ export function go(route: Route, param?: string) { export function bootOnce() { if ((globalThis as { __strataBooted?: boolean }).__strataBooted) return; (globalThis as { __strataBooted?: boolean }).__strataBooted = true; - for (const session of state.sessions) for (const run of session.timeSkips ?? []) scheduleTimeSkip(session.id, run); + for (const session of state.sessions) for (const run of session.timeSkips ?? []) { scheduleTimeSkip(session.id, run); if (run.job && !run.completedAt) void followTimeSkip(session.id, run.id); } void bootstrap(); void reconcileAgentTools(); } diff --git a/apps/host/src/lib/time-skip.ts b/apps/host/src/lib/time-skip.ts index 749a3009..a02fe687 100644 --- a/apps/host/src/lib/time-skip.ts +++ b/apps/host/src/lib/time-skip.ts @@ -34,6 +34,21 @@ export interface TimeSkipJob { needsUserReview: boolean; error: string | null; finishedAt?: number | null; + /** The files the run changed (saved original against the revision), read from the job's own folders. */ + files?: TimeSkipFile[]; + /** More changed files than are listed. */ + moreFiles?: number; + /** The revision attempt "Keep the update" applies when the checks did not keep one themselves. */ + applyAttempt?: number | null; +} + +export interface TimeSkipFile { + path: string; + status: 'added' | 'changed' | 'removed'; + original?: string; + updated?: string; + /** Too big or not text: listed, but not shown. */ + unreadable?: boolean; } export type TimeSkipVersion = 'original' | 'updated'; @@ -72,7 +87,7 @@ export function withTimeSkipResult(run: TimeSkipRun, version: TimeSkipVersion, n } export function timeSkipResultState(run: TimeSkipRun, now: number) { - if (run.job) return realResultState(run.job); + if (run.job) return realResultState(run.job, run.retainedVersion); const frame = timeSkipFrame(run, now); const ready = frame.index >= 3; const kept: TimeSkipVersion = frame.done && run.retainedVersion === 'original' ? 'original' : frame.chosen === 'b' ? 'updated' : 'original'; @@ -95,7 +110,7 @@ export function timeSkipResultState(run: TimeSkipRun, now: number) { * * `unknown` check outcomes are surfaced as unknown. A phase is not a percentage and this * returns none. */ -function realResultState(job: TimeSkipJob) { +function realResultState(job: TimeSkipJob, chosen?: TimeSkipVersion) { const done = ['completed', 'cancelled', 'failed', 'interrupted'].includes(job.phase); const index = job.phase === 'queued' ? 0 @@ -107,7 +122,7 @@ function realResultState(job: TimeSkipJob) { // The decision's `improvements` is the job's own answer about what got better; nothing here // re-derives a verdict from the attempt list. const improved = (job.decision?.improvements?.length ?? 0) > 0; - const kept: TimeSkipVersion = improved ? 'updated' : 'original'; + const kept: TimeSkipVersion = chosen ?? (improved ? 'updated' : 'original'); const outcome = job.decision?.outcome ?? null; let status: string; @@ -120,8 +135,12 @@ function realResultState(job: TimeSkipJob) { : job.phase === 'checking' ? 'Checking the changes…' : job.phase === 'decision' ? 'Deciding from the checks…' : 'Starting…'; + } else if (chosen === 'updated') { + status = 'Update kept · your files now have it'; + } else if (chosen === 'original') { + status = 'Original kept · your files are unchanged'; } else if (job.needsUserReview || outcome === 'inconclusive' || outcome === 'conflict') { - status = 'Ready to compare · the checks were inconclusive'; + status = 'Ready to compare · you choose which to keep'; } else if (outcome === 'accepted') { status = 'Update kept · the checks improved'; } else { @@ -157,6 +176,8 @@ export interface TimeSkipDocument { successCheck: string; code?: string; image?: { url: string; alt: string }; + /** A real run has no sample "success check" to show. */ + hideCheck?: boolean; } /** Immutable paired sample outputs, separate from the later rejected attempt. */ @@ -182,9 +203,28 @@ export function timeSkipDocuments(prompt: string): Record `${i + 1}. ${step}`).join('\n')}\n\n## Success check\n\n${document.successCheck}\n\n*Time-skip example · sample output, simulated checks.*`; } +const FILE_VERB = { added: 'Added', changed: 'Changed', removed: 'Removed' } as const; + +/** The two sides of a real run as documents: the changed files, one after another. */ +export function realTimeSkipDocuments(job: TimeSkipJob): Record & { changes: string[] } { + const files = job.files ?? []; + const side = (which: 'original' | 'updated') => files.map(f => { + const text = f.unreadable ? '(too big or not text, so it is not shown here)' + : which === 'original' ? (f.status === 'added' ? '(this file did not exist)' : f.original ?? '') + : (f.status === 'removed' ? '(this file was removed)' : f.updated ?? ''); + return files.length === 1 ? text : '── ' + f.path + ' ──\n' + text; + }).join('\n\n'); + const title = files.length === 1 ? files[0].path : files.length ? files.length + ' files' : 'Nothing changed'; + const make = (which: 'original' | 'updated'): TimeSkipDocument => ({ title, steps: [], successCheck: '', hideCheck: true, code: files.length ? side(which) : '(nothing changed)' }); + const changes = files.map(f => FILE_VERB[f.status] + ' ' + f.path); + if (job.moreFiles) changes.push('and ' + job.moreFiles + ' more files'); + return { original: make('original'), updated: make('updated'), revision: make('updated'), changes }; +} + export function timeSkipExample(prompt: string) { if (/image|photo|poster|illustration/i.test(prompt)) return { labels: ['Visual style', 'Headline', 'Composition'], diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 02a434b8..f48b403a 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -318,6 +318,8 @@ export interface ChatMessage { /** Reply came from a saved API connection, rather than the local engine. */ remoteModel?: boolean; timeSkipId?: string; + /** A line from the app itself (for example from /loop), never sent to the model. */ + local?: boolean; ttftMs?: number; example?: boolean; media?: {kind: 'image' | 'video' | 'gif'; src:string; title:string; caption?:string; poster?:string}[]; diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 89fad83a..ad92fd70 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -374,7 +374,7 @@ export function ChatScreen() { {tr("Latest")}) : null)}
{tr(session.messages.length === 0 ? (session.statsAvailable === false ?

{tr("Editing from an earlier message. Update the prompt below.")}

: - ) : (session.messages.map((m, i) => ( r.id === m.timeSkipId)?.completedAt} onOpenLink={openLink}/>))))} + ) : (session.messages.map((m, i) => ( r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!timeSkipRuns.find(r => r.id === m.timeSkipId)?.job} onOpenLink={openLink}/>))))}
@@ -395,7 +395,9 @@ interface SlashCommand { function useSlashCommands(clear: () => void, setDraft: (value: string) => void): SlashCommand[] { const demo = useStore(s => s.library?.mode === 'simulated'); return [ - { id: 'time-skip', label: '/time-skip', hint: 'Try two versions and keep the better one', icon: 'branch', run: () => setDraft('/time-skip ') }, + { id: 'time-skip', label: '/time-skip', hint: 'Try a change on a copy, check it, and keep it only if it is better', icon: 'branch', run: () => setDraft('/time-skip ') }, + { id: 'goal', label: '/goal', hint: 'Set a goal and let the assistant keep working until it is done', icon: 'bolt', run: () => setDraft('/goal ') }, + { id: 'loop', label: '/loop', hint: 'Repeat a message every few minutes while this chat is open', icon: 'refresh', run: () => setDraft('/loop 10m ') }, { id: 'website', label: '/website', hint: 'Open a website in the preview sidebar', icon: 'link', run: () => { clear(); window.dispatchEvent(new Event('strata:open-website')); } }, { id: 'preview', label: '/preview', hint: 'Open a local file in the preview sidebar', icon: 'file', run: () => { clear(); window.dispatchEvent(new Event('strata:open-preview')); } }, ...(demo ? [{ id: 'subagents', label: '/subagents', hint: 'Preview subagent statistics', icon: 'experts' as const, run: () => { clear(); createSubagentExample(); } }] : []), @@ -523,7 +525,7 @@ function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session ) : null)} ); } -function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, }: { +function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, }: { message: ChatMessage; isLast: boolean; onEditPrompt: (text: string) => void; @@ -531,6 +533,7 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp onOpenLink: (url: string) => void; onOpenTimeSkip: (id: string) => void; timeSkipDone: boolean; + timeSkipReal?: boolean; }) { const streaming = useStore(s => s.streaming); const [sentTime, setSentTime] = useState(() => relTime(m.at)); @@ -566,7 +569,7 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
{tr(m.error ? () : null)} - {tr(m.content ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming ? ( + {tr(m.content ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming ? ( diff --git a/apps/host/tests/slash-commands.test.mjs b/apps/host/tests/slash-commands.test.mjs new file mode 100644 index 00000000..b0a12b12 --- /dev/null +++ b/apps/host/tests/slash-commands.test.mjs @@ -0,0 +1,52 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { build } from 'esbuild'; + +const bundled = await build({ entryPoints: ['src/lib/loop.ts'], bundle: true, write: false, format: 'esm', platform: 'node' }); +const { parseLoop, loopEvery, LOOP_MIN_MS } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`); + +test('/loop reads how often, then what to do', () => { + assert.deepEqual(parseLoop('/loop 10m check the build'), { kind: 'start', everyMs: 600000, prompt: 'check the build' }); + assert.deepEqual(parseLoop('/loop 2h summarise my inbox notes'), { kind: 'start', everyMs: 7200000, prompt: 'summarise my inbox notes' }); + assert.deepEqual(parseLoop('/loop every 5 minutes say hi'), { kind: 'start', everyMs: 300000, prompt: 'say hi' }); + assert.equal(parseLoop('hello /loop'), null, 'only a message that starts with /loop is a loop'); + assert.equal(parseLoop('/looping'), null); +}); + +test('/loop with no time, a tiny time or a huge time is explained in plain words, never run', () => { + assert.equal(parseLoop('/loop check the build').kind, 'help'); + assert.match(parseLoop('/loop check the build').problem, /how often/); + assert.match(parseLoop('/loop 10s ping').problem, /1 minute/); + assert.match(parseLoop('/loop 48h ping').problem, /24 hours/); + assert.equal(LOOP_MIN_MS, 60000); +}); + +test('/loop, /loop stop and the words for how often', () => { + assert.deepEqual(parseLoop('/loop'), { kind: 'status' }); + assert.deepEqual(parseLoop('/loop stop'), { kind: 'stop' }); + assert.deepEqual(parseLoop('/loop OFF'), { kind: 'stop' }); + assert.equal(loopEvery(60000), 'every minute'); + assert.equal(loopEvery(600000), 'every 10 minutes'); + assert.equal(loopEvery(3600000), 'every hour'); + assert.equal(loopEvery(7200000), 'every 2 hours'); +}); + +test('the slash menu lists /time-skip, /goal and /loop with plain descriptions, and /loop no longer just opens Tasks', async () => { + const chat = await readFile('src/screens/Chat.tsx', 'utf8'); + for (const [label, words] of [['/time-skip', 'Try a change on a copy'], ['/goal', 'keep working until it is done'], ['/loop', 'every few minutes']]) { + const line = chat.split('\n').find(l => l.includes(`label: '${label}'`)); + assert.ok(line, `${label} is in the menu`); + assert.ok(line.includes(words), `${label} has a plain description`); + } + const commands = await readFile('src/lib/commands.ts', 'utf8'); + assert.ok(!/slash: \['loop'\]/.test(commands), 'the old /loop alias that only opened Tasks is gone'); +}); + +test('the store sends /loop to the loop and /time-skip to a real job when a local model is ready', async () => { + const store = await readFile('src/lib/store.ts', 'utf8'); + assert.match(store, /parseLoop\(text\.trim\(\)\)/); + assert.match(store, /startTimeSkipReal\(demoPrompt\)/); + assert.match(store, /nativeState\(\)\?\.instances\.some\(i => i\.status === 'ready'\)/); + assert.match(store, /!m\.timeSkipId && !m\.local/, 'notes from the app and trial turns are not sent back to the model'); +}); diff --git a/apps/host/tests/timeskip-real.test.mjs b/apps/host/tests/timeskip-real.test.mjs new file mode 100644 index 00000000..c52b0b80 --- /dev/null +++ b/apps/host/tests/timeskip-real.test.mjs @@ -0,0 +1,96 @@ +/** + * Time-skip in the app, for real: the host starts the job without waiting for it, follows its record, lists the changed files and + * applies a revision the person chose. The revision step here is a small script (the assistant's turn is covered by the box runs). + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createTimeSkip, diffRun, measureFolder, timeskipRevisionMessage } from '../server/timeskip.mjs'; + +const REPO = resolve(fileURLToPath(new URL('.', import.meta.url)), '..', '..', '..'); +const PYTHON = process.env.STRATA_TEST_PYTHON ?? (process.platform === 'win32' ? 'python' : 'python3'); +const hasPython = spawnSync(PYTHON, ['--version'], { windowsHide: true }).status === 0; + +function sleep(ms) { return new Promise(r => setTimeout(r, ms)); } + +test('the revision request tells the assistant to stay in the copy and to say what it did', () => { + const text = timeskipRevisionMessage('make a launch plan'); + assert.match(text, /current folder is that copy/); + assert.match(text, /Never read or write outside it/); + assert.match(text, /make a launch plan$/); +}); + +test('measureFolder stops early on a folder that is too big to copy', () => { + const dir = mkdtempSync(join(tmpdir(), 'ts-measure-')); + try { + for (let i = 0; i < 30; i++) writeFileSync(join(dir, `f${i}.txt`), 'x'); + assert.equal(measureFolder(dir).tooBig, false); + assert.equal(measureFolder(dir, { maxFiles: 10 }).tooBig, true); + mkdirSync(join(dir, 'node_modules')); + writeFileSync(join(dir, 'node_modules', 'big.txt'), 'y'.repeat(1000)); + assert.equal(measureFolder(dir, { maxBytes: 100 }).tooBig, false, 'node_modules is not copied for a trial, so it does not count'); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('diffRun lists added, changed and removed files and says which revision to apply', () => { + const dir = mkdtempSync(join(tmpdir(), 'ts-diff-')); + try { + const base = join(dir, 'base'), cand = join(dir, 'cand'); + mkdirSync(base); mkdirSync(cand); + writeFileSync(join(base, 'same.txt'), 'same'); writeFileSync(join(cand, 'same.txt'), 'same'); + writeFileSync(join(base, 'edit.txt'), 'one'); writeFileSync(join(cand, 'edit.txt'), 'one two'); + writeFileSync(join(base, 'gone.txt'), 'bye'); + writeFileSync(join(cand, 'new.md'), '# new'); + const found = diffRun({ checkpoints: [{ id: 'cp1-baseline', label: 'baseline', path: base }], selected_checkpoint: 'cp1-baseline', attempts: [{ index: 1, path: cand }] }); + assert.deepEqual(found.files.map(f => [f.path, f.status]), [['edit.txt', 'changed'], ['gone.txt', 'removed'], ['new.md', 'added']]); + assert.equal(found.files[0].original, 'one'); assert.equal(found.files[0].updated, 'one two'); + assert.equal(found.applyAttempt, 1, 'nothing was kept by the checks, so the person applies the last revision'); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('a run starts without the caller waiting, shows its changed files, and applies the chosen revision with a rollback copy', { skip: !hasPython && 'no python on this machine', timeout: 120000 }, async () => { + const dir = mkdtempSync(join(tmpdir(), 'ts-run-')); + try { + const workspace = join(dir, 'work'); mkdirSync(workspace); + writeFileSync(join(workspace, 'plan.md'), 'first draft\n'); + const script = join(dir, 'revise.mjs'); + writeFileSync(script, "import { writeFileSync, appendFileSync } from 'node:fs'; await new Promise(r => setTimeout(r, 1500)); appendFileSync('plan.md', 'second line\\n'); writeFileSync('extra.md', process.env.STRATA_TIMESKIP_PROMPT);"); + const state = join(dir, 'state'); + const ts = createTimeSkip({ repoRoot: REPO, python: PYTHON, env: { ...process.env, STRATA_TIMESKIP_DIR: state } }); + const started = Date.now(); + const result = await ts.startDetached({ workspace, prompt: 'extend the plan', attempts: 1, reviseCommand: `"${process.execPath}" "${script}"` }); + assert.ok(result.ok, JSON.stringify(result)); + assert.ok(Date.now() - started < 1400, 'the call returned while the revision was still running'); + const id = result.run.id; + let run; + for (let i = 0; i < 100; i++) { run = ts.status(id); if (['completed', 'failed'].includes(run.phase)) break; await sleep(300); } + assert.equal(run.phase, 'completed', JSON.stringify(run)); + assert.equal(run.needsUserReview, true, 'no checks were declared, so the person decides'); + const files = ts.files(id); + assert.deepEqual(files.files.map(f => [f.path, f.status]), [['extra.md', 'added'], ['plan.md', 'changed']]); + assert.equal(files.applyAttempt, 1); + assert.equal(readFileSync(join(workspace, 'plan.md'), 'utf8'), 'first draft\n', 'the person\'s files are untouched until they choose'); + const applied = await ts.apply({ id, attempt: files.applyAttempt }); + assert.ok(applied.ok, JSON.stringify(applied)); + assert.match(readFileSync(join(workspace, 'plan.md'), 'utf8'), /second line/); + assert.equal(readFileSync(join(workspace, 'extra.md'), 'utf8'), 'extend the plan'); + const restored = await ts.apply({ id, restore: true }); + assert.ok(restored.ok, JSON.stringify(restored)); + assert.equal(readFileSync(join(workspace, 'plan.md'), 'utf8'), 'first draft\n'); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); + +test('a run whose host is gone reads as interrupted, not as still working', { skip: !hasPython && 'no python on this machine', timeout: 60000 }, async () => { + const dir = mkdtempSync(join(tmpdir(), 'ts-gone-')); + try { + const state = join(dir, 'state'), id = 'a'.repeat(32); + mkdirSync(join(state, id), { recursive: true }); + writeFileSync(join(state, id, 'run.json'), JSON.stringify({ id, state: 'generating', workspace: dir, prompt: 'x', checkpoints: [], attempts: [] })); + const ts = createTimeSkip({ repoRoot: REPO, python: PYTHON, env: { ...process.env, STRATA_TIMESKIP_DIR: state } }); + assert.equal(ts.status(id).phase, 'interrupted'); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 2bf3cdb6..0ab1c107 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -346,6 +346,9 @@ def parser() -> argparse.ArgumentParser: ts_apply.add_argument("run_id") ts_apply.add_argument("--workspace", default=None, help="destination (default: the workspace the run recorded)") + ts_apply.add_argument("--attempt", type=int, default=None, + help="apply this revision attempt (chosen by the person after review) " + "instead of the retained checkpoint") ts_apply.add_argument("--dry-run", action="store_true", help="report what would change without writing anything") ts_apply.add_argument("--restore", action="store_true", @@ -1243,7 +1246,7 @@ def _timeskip(a: argparse.Namespace) -> int: return _success({"restore": outcome}, machine=True) print(f"restored {outcome['checkpoint']} to {destination or data['workspace']}") return 0 - outcome = run.apply(destination, dry_run=a.dry_run) + outcome = run.apply(destination, dry_run=a.dry_run, attempt=a.attempt) except time_skip.TimeSkipError as e: return _error(str(e), 2, a.output == "json") if outcome.get("conflict"): diff --git a/strata_control/time_skip.py b/strata_control/time_skip.py index abfb8975..94f4e3ff 100644 --- a/strata_control/time_skip.py +++ b/strata_control/time_skip.py @@ -592,15 +592,26 @@ class TimeSkipRun: # ---- applying -------------------------------------------------------- - def apply(self, destination: Path | None = None, dry_run: bool = False) -> dict[str, Any]: + def apply(self, destination: Path | None = None, dry_run: bool = False, + attempt: int | None = None) -> dict[str, Any]: """Apply the retained checkpoint to the workspace, transactionally. + ``attempt`` names a revision attempt the *person* chose after looking at it (a run whose checks + could not decide leaves the baseline retained, and the person is asked). The same safety + applies: a changed destination is a conflict, and a failure rolls back. + Refuses when the destination no longer matches what was captured, which is how a concurrent user edit becomes a conflict instead of being overwritten. On any failure the previous content is restored from the rollback copy. """ dest = Path(destination or self.workspace) - kept = self._source_of(self.selected_checkpoint) + if attempt is None: + kept = self._source_of(self.selected_checkpoint) + else: + chosen = next((a for a in self.attempts if a.index == attempt), None) + if chosen is None or not Path(chosen.path).is_dir(): + raise TimeSkipError(f"this run has no revision attempt {attempt} to apply") + kept = Path(chosen.path) baseline = next((c for c in self.checkpoints if c.label == "baseline"), None) if baseline is None: raise TimeSkipError("this run has no baseline to compare the destination against") @@ -635,7 +646,8 @@ class TimeSkipRun: return {"applied": False, "rolled_back": True, "reason": f"apply failed and was rolled back: {type(e).__name__}: {e}"} return {"applied": True, "wrote": applied, "removed": removed, - "rollback": str(rollback), "checkpoint": self.selected_checkpoint} + "rollback": str(rollback), + "checkpoint": self.selected_checkpoint if attempt is None else f"attempt{attempt}"} def restore_original(self, destination: Path | None = None) -> dict[str, Any]: """Put the baseline back, whatever else has happened.""" diff --git a/tests/time_skip/test_apply_attempt.py b/tests/time_skip/test_apply_attempt.py new file mode 100644 index 00000000..973b2aa5 --- /dev/null +++ b/tests/time_skip/test_apply_attempt.py @@ -0,0 +1,50 @@ +"""Applying a revision attempt the person chose after review (a run with no deciding checks keeps the baseline).""" + +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from strata_control import time_skip as ts # noqa: E402 + +from test_time_skip import TimeSkipCase # noqa: E402 + + +class TestApplyChosenAttempt(TimeSkipCase): + def test_a_reviewed_attempt_can_be_applied_and_undone(self): + def revise(candidate: Path, prompt: str, index: int) -> str: + (candidate / "doc.txt").write_text("one\ntwo\nthree\n", encoding="utf-8") + return "added three" + + run, result = self.start(revise, checks=[]) + self.assertTrue(result["decision"]["needs_user_review"]) + self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), "one\ntwo\n") + outcome = run.apply(attempt=1) + self.assertTrue(outcome["applied"], outcome) + self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), "one\ntwo\nthree\n") + run.restore_original() + self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), "one\ntwo\n") + + def test_a_missing_attempt_is_refused(self): + run, _ = self.start(lambda c, p, i: None, checks=[]) + with self.assertRaises(ts.TimeSkipError): + run.apply(attempt=9) + + def test_a_reviewed_attempt_is_still_refused_after_a_user_edit(self): + def revise(candidate: Path, prompt: str, index: int) -> str: + (candidate / "doc.txt").write_text("changed\n", encoding="utf-8") + return "x" + + run, _ = self.start(revise, checks=[]) + (self.ws / "doc.txt").write_text("the user rewrote this\n", encoding="utf-8") + outcome = run.apply(attempt=1) + self.assertTrue(outcome["conflict"]) + self.assertEqual((self.ws / "doc.txt").read_text(encoding="utf-8"), "the user rewrote this\n") + + +if __name__ == "__main__": + unittest.main()