Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Time-skip: streamed revision answer with a beat (a slow turn no longer ends in 'could not be reached'), Stop ends the job tree and deletes the copies, activity in the status route and SSE, sidebar only when there is an update, Stop button while it runs

Niko1221ee8b23bcc74a
diff --git a/apps/host/server/index.mjs b/apps/host/server/index.mjs
index b11d871c5..cfa5f86c6 100644
--- a/apps/host/server/index.mjs
+++ b/apps/host/server/index.mjs
@@ -654,6 +654,44 @@ const TIMESKIP_REVISE = process.env.STRATA_TIMESKIP_REVISE
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();
+/** Trials this host is driving: run id -> { chatId (the chat that asked), turnChat (the assistant's own chat id), controller, step (the assistant's current status), lastSent }. */
+const trials = new Map();
+const trialByChat = new Map();
+/** What the job is doing, in the person's words, from its phase and the assistant's own current step (notes-split-agent3.md). */
+function trialActivity(run) {
+ const trial = trials.get(run.id);
+ switch (run.phase) {
+ case 'queued': case 'checkpointing': return { code: 'reading-files', text: 'Reading your files…' };
+ case 'generating': return { code: 'trying-version', text: 'Trying an improved version…', ...(trial?.step ? { args: { step: trial.step.text, stepCode: trial.step.code, ...(trial.step.args ? { stepArgs: trial.step.args } : {}) } } : {}) };
+ case 'checking': return { code: 'checking-result', text: 'Checking the result…' };
+ case 'decision': return { code: 'comparing', text: 'Comparing the two versions…' };
+ default: return null;
+ }
+}
+/** Tell the page when the job's phase or the assistant's step changed (SSE `timeskip`), at most every 2 s. */
+function watchTrial(id) {
+ const trial = trials.get(id);
+ if (!trial) return;
+ const timer = setInterval(() => {
+ const run = timeskip.status(id);
+ if (!run) { clearInterval(timer); return; }
+ const activity = trialActivity(run);
+ const key = JSON.stringify([run.phase, activity]);
+ if (key !== trial.lastSent) { trial.lastSent = key; hub.send('timeskip', { id, phase: run.phase, activity }); }
+ if (['completed', 'cancelled', 'failed', 'interrupted'].includes(run.phase)) { clearInterval(timer); trials.delete(id); if (trial.chatId) trialByChat.delete(trial.chatId); }
+ }, 2000);
+ timer.unref?.();
+ trial.timer = timer;
+}
+/** Stop a trial the person stopped: the assistant's turn, the job and its processes, and the copies. */
+async function stopTrial(id) {
+ const trial = trials.get(id);
+ if (trial) { trial.controller?.abort(); if (trial.turnChat) void agent.stop(trial.turnChat).catch(() => {}); }
+ const stopped = await timeskip.stop(id);
+ if (trial) { clearInterval(trial.timer); trials.delete(id); if (trial.chatId) trialByChat.delete(trial.chatId); }
+ if (stopped) hub.send('timeskip', { id, phase: 'cancelled', activity: null });
+ return stopped;
+}
/**
* Tuning, from the App Host.
*
@@ -940,7 +978,7 @@ async function api(req, res, path, method, url) {
const id = url.searchParams.get('id');
const run = id ? timeskip.status(id) : null;
if (!run) return error(res, 404, 'No such Time-skip run.');
- return json(res, 200, { run });
+ return json(res, 200, { run: { ...run, activity: trialActivity(run) } });
}
if (path === '/api/timeskip/start' && method === 'POST') {
const body = await readBody(req);
@@ -962,8 +1000,12 @@ 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);
+ const chatId = typeof body.sessionId === 'string' && body.sessionId ? body.sessionId : null;
+ trials.set(result.run.id, { chatId, turnChat: null, controller: null, step: null, lastSent: '' });
+ if (chatId) trialByChat.set(chatId, result.run.id);
+ watchTrial(result.run.id);
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 });
+ return json(res, 200, { run: { ...result.run, activity: trialActivity(result.run) }, simulated: false });
}
if (path === '/api/timeskip/files' && method === 'GET') {
const found = timeskip.files(url.searchParams.get('id'));
@@ -972,7 +1014,7 @@ async function api(req, res, path, method, url) {
}
if (path === '/api/timeskip/stop' && method === 'POST') {
const body = await readBody(req);
- return json(res, 200, { stopped: timeskip.cancel(String(body.id ?? '')) });
+ return json(res, 200, { stopped: await stopTrial(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') {
@@ -988,15 +1030,31 @@ async function api(req, res, path, method, url) {
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')}`;
+ // The answer is a stream that starts at once and carries a beat every 15 s: a turn on a slow computer can run for many minutes with
+ // nothing to say, and a caller that hears no byte for five minutes gives up (that was "The assistant could not be reached").
+ res.writeHead(200, { 'content-type': 'application/x-ndjson; charset=utf-8', 'cache-control': 'no-cache, no-transform' });
+ const write = frame => { if (!res.writableEnded && !res.destroyed) res.write(`${JSON.stringify(frame)}\n`); };
+ write({ type: 'beat' });
+ const beat = setInterval(() => write({ type: 'beat' }), 15_000);
+ const controller = new AbortController();
+ const trial = trials.get(runId);
+ if (trial) { trial.turnChat = chatId; trial.controller = controller; }
+ res.on('close', () => { clearInterval(beat); if (!res.writableEnded) { controller.abort(); void agent.stop(chatId).catch(() => {}); } });
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 => {
+ await agent.runTurn({ chatId, message: timeskipRevisionMessage(String(body.prompt ?? '')), workspacePath: cwd, choice: chosen, mode: 'bypass', thinking: 'low', history: [], signal: controller.signal, onFrame: frame => {
if (frame.type === 'delta') text += frame.text ?? '';
else if (frame.type === 'error') failure = frame.message;
+ else if (frame.type === 'status' && trial) {
+ // the assistant's own current step (what it is writing or running) rides along with the job's phase
+ trial.step = frame.phase === 'idle' ? null : { code: frame.code, text: frame.text, args: frame.args };
+ }
} });
- } finally { agent.forget(chatId); }
- if (failure) return error(res, 502, failure);
- return json(res, 200, { text: text.slice(-600) });
+ } catch (e) { failure = failure ?? e.message; } finally { agent.forget(chatId); clearInterval(beat); if (trial) trial.step = null; }
+ if (controller.signal.aborted) failure = failure ?? 'The trial was stopped.';
+ write(failure ? { type: 'error', message: failure } : { type: 'result', text: text.slice(-600) });
+ res.end();
+ return undefined;
}
if (path === '/api/timeskip/apply' && method === 'POST') {
const body = await readBody(req);
@@ -1529,6 +1587,9 @@ async function api(req, res, path, method, url) {
if (path === '/api/chat/stop' && method === 'POST') {
const b = await readBody(req);
if (typeof b.sessionId !== 'string') return error(res, 400, 'sessionId is required');
+ // A Time-skip trial of this chat is stopped by the same Stop button (and cleans up its copies).
+ const trialId = trialByChat.get(b.sessionId);
+ if (trialId) return json(res, 200, { stopped: await stopTrial(trialId), ended: 'time-skip' });
try { return json(res, 200, await agent.stop(b.sessionId)); } catch (e) { return error(res, 502, e.message); }
}
diff --git a/apps/host/server/timeskip-revise.mjs b/apps/host/server/timeskip-revise.mjs
index 9656414ad..47543f884 100644
--- a/apps/host/server/timeskip-revise.mjs
+++ b/apps/host/server/timeskip-revise.mjs
@@ -2,11 +2,14 @@
/**
* 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.
+ * 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.
+ *
+ * The host answers with a STREAM of one-line JSON messages (`beat`, `activity`, then `result` or `error`) and sends the first one at once.
+ * A turn on a slow computer can take many minutes with nothing to say; an answer that sends no byte for five minutes is abandoned by
+ * Node's fetch, which is how a Time-skip used to end with "The assistant could not be reached".
*/
const base = process.env.STRATA_HOST_URL;
const secret = process.env.STRATA_INTERNAL_SECRET;
@@ -24,12 +27,31 @@ try {
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) {
+ if (!res.ok || !res.body) {
+ const body = await res.json().catch(() => ({}));
console.error(body.error ?? `The assistant could not make the change (HTTP ${res.status}).`);
process.exit(1);
}
- console.log(String(body.text ?? '').trim());
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let result = null, failure = null;
+ const take = line => {
+ if (!line.trim()) return;
+ let message;
+ try { message = JSON.parse(line); } catch { return; }
+ if (message.type === 'result') result = String(message.text ?? '').trim();
+ else if (message.type === 'error') failure = String(message.message ?? 'The assistant could not make the change.');
+ };
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (value) { buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() ?? ''; lines.forEach(take); }
+ if (done) break;
+ }
+ take(buffer);
+ if (failure) { console.error(failure); process.exit(1); }
+ if (result === null) { console.error('The assistant stopped before it finished.'); process.exit(1); }
+ console.log(result);
} 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 0b05d592e..cae1e357e 100644
--- a/apps/host/server/timeskip.mjs
+++ b/apps/host/server/timeskip.mjs
@@ -17,8 +17,8 @@
* A run is a job, not a request: it outlives the HTTP call that started it. The endpoint returns the
* run id immediately and the client follows it with `/api/timeskip/status`.
*/
-import { spawn } from 'node:child_process';
-import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { timeSkipDir } from './platform-paths.mjs';
@@ -134,6 +134,14 @@ export function timeskipRevisionMessage(request) {
].join('\n');
}
+/** End a process and everything it started (the job, the Python it runs, the revision command and its Node). */
+function killTree(child) {
+ try {
+ if (process.platform === 'win32' && child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
+ else child.kill('SIGTERM');
+ } catch { /* already gone */ }
+}
+
/** 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;
@@ -204,6 +212,10 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs =
/** 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();
+ /** id -> promise that settles when the job's process has ended. */
+ const endedOf = new Map();
+ /** Runs the person stopped: their folders are deleted, so the answer to "what became of it" is kept here (until the host restarts). */
+ const stopped = new Set();
const withLive = summary => (summary && !TERMINAL.has(summary.phase) && !live.has(summary.id) ? { ...summary, phase: 'interrupted' } : summary);
function runCli(args, { signal } = {}) {
@@ -279,6 +291,7 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs =
/** One run's durable record, or null. */
status: (id) => {
if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return null;
+ if (stopped.has(id)) return { id, phase: 'cancelled', workspace: null, prompt: null, startedAt: null, finishedAt: null, attempts: [], checkpoints: [], selectedCheckpoint: null, decision: null, needsUserReview: false, error: null };
const run = readRun(stateDir(env), id);
return run ? withLive(summarise(run)) : null;
},
@@ -290,14 +303,29 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs =
return run ? diffRun(run) : null;
},
- /** Stop a run this host is driving. The saved version stays; the run reads as interrupted. */
- cancel: id => {
+ /** Settles when the job's process has ended (immediately for a run this host is not driving). */
+ whenEnded: id => endedOf.get(id) ?? Promise.resolve(),
+
+ /**
+ * Stop a run and clean up after it: the job and everything it started are ended (the whole process tree), and the run's folder, which
+ * holds the copies of the person's files, is deleted. The person's own files were never touched by the run. Afterwards the run reads as
+ * cancelled. Returns false for an id that is not a run.
+ */
+ async stop(id) {
+ if (!/^[0-9a-f]{8,64}$/.test(String(id ?? ''))) return false;
+ const folder = join(stateDir(env), id);
+ if (!live.has(id) && !existsSync(folder) && !stopped.has(id)) return false;
+ stopped.add(id);
const child = live.get(id);
- if (!child) return false;
- try { child.kill('SIGTERM'); } catch { /* already gone */ }
+ if (child) killTree(child);
+ await Promise.race([endedOf.get(id) ?? Promise.resolve(), new Promise(r => setTimeout(r, 8000))]);
+ for (let i = 0; i < 6 && existsSync(folder); i++) {
+ try { rmSync(folder, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); } catch { await new Promise(r => setTimeout(r, 400)); }
+ }
return true;
},
+
/**
* Start a run. Returns as soon as the job has been *accepted*; the caller follows the run id.
*
@@ -364,6 +392,7 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs =
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);
+ endedOf.set(id, ended);
void ended.then(() => live.delete(id));
return { ok: true, run: withLive(summarise(readRun(root, id))) };
},
diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts
index c71e7ac30..2adfb95ed 100644
--- a/apps/host/src/lib/store.ts
+++ b/apps/host/src/lib/store.ts
@@ -1162,20 +1162,23 @@ async function startTimeSkipReal(prompt: string) {
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),
+ // The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works.
+ timeSkips: [...(s.timeSkips ?? []), run],
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);
+ markTurn(sessionId, { abort: new AbortController(), agent: false });
try {
- const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) });
+ const started = await api.post<{ run: TimeSkipJob }>('/api/timeskip/start', { prompt, sessionId, workspaceId: state.activeWorkspace, attempts: 1, ...(state.remoteModel ? { remoteModel: state.remoteModel } : {}) });
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]));
+ markTurn(sessionId, null);
}
}
@@ -1201,11 +1204,14 @@ export async function followTimeSkip(sessionId: string, runId: string) {
} 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));
+ if (finished.phase === 'completed' && files.length > 0) patchSession(sessionId, s => ({ ...s, previewOpen: timeSkipTabId(runId) }));
+ markTurn(sessionId, null);
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.'));
+ markTurn(sessionId, null);
return;
}
await new Promise(r => setTimeout(r, 2000));
diff --git a/apps/host/src/lib/time-skip.ts b/apps/host/src/lib/time-skip.ts
index a02fe6878..ca7e21ea1 100644
--- a/apps/host/src/lib/time-skip.ts
+++ b/apps/host/src/lib/time-skip.ts
@@ -38,6 +38,8 @@ export interface TimeSkipJob {
files?: TimeSkipFile[];
/** More changed files than are listed. */
moreFiles?: number;
+ /** What the job is doing right now in the person's words (reading-files, trying-version, checking-result, comparing), from the host. */
+ activity?: { code: string; text: string; args?: Record<string, unknown> } | null;
/** The revision attempt "Keep the update" applies when the checks did not keep one themselves. */
applyAttempt?: number | null;
}
diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx
index 236981776..01db2dd7d 100644
--- a/apps/host/src/screens/Chat.tsx
+++ b/apps/host/src/screens/Chat.tsx
@@ -100,7 +100,7 @@ export function ChatScreen() {
}, [expanded]);
const [previews, setPreviews] = useState<PreviewArtifact[]>([]);
const [selectedPreview, setSelectedPreview] = useState<string | null>(null);
- const timeSkipRuns = (session?.timeSkips ?? []).filter(run => session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant'));
+ const timeSkipRuns = (session?.timeSkips ?? []).filter(run => session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant') && (!run.job || (run.job.files?.length ?? 0) > 0));
const extraTabs = timeSkipRuns.map((run, i) => ({ id: timeSkipTabId(run.id), title: timeSkipRuns.length > 1 ? `Time-skip ${i + 1}` : 'Time-skip', icon: 'branch' as const, controls: 'time-skip-content' })).filter(tab => !session?.closedPreviews?.includes(tab.id));
const selectedRun = timeSkipRuns.find(run => timeSkipTabId(run.id) === selectedPreview);
const inlinePreview = splitWidth >= (selectedRun ? 760 : 1120);
@@ -375,7 +375,7 @@ export function ChatScreen() {
<Icon name="chevron" size={14} style={{ transform: 'rotate(90deg)' }}/>{tr("Latest")}</button>) : null)}
<div className="chat__inner">
{tr(session.messages.length === 0 ? (session.statsAvailable === false ? <p className="small muted">{tr("Editing from an earlier message. Update the prompt below.")}</p> :
- <UsageDashboard loaded={!!loaded}/>) : (session.messages.map((m, i) => (<Message key={m.id} message={m} isLast={i === session.messages.length - 1} onEditPrompt={editPrompt} onPreview={openPreview} onOpenTimeSkip={openTimeSkip} timeSkipDone={!!timeSkipRuns.find(r => r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!timeSkipRuns.find(r => r.id === m.timeSkipId)?.job} onOpenLink={openLink}/>))))}
+ <UsageDashboard loaded={!!loaded}/>) : (session.messages.map((m, i) => (<Message key={m.id} message={m} isLast={i === session.messages.length - 1} onEditPrompt={editPrompt} onPreview={openPreview} onOpenTimeSkip={openTimeSkip} timeSkipDone={!!(session.timeSkips ?? []).find(r => r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!(session.timeSkips ?? []).find(r => r.id === m.timeSkipId)?.job} timeSkipTab={timeSkipRuns.some(r => r.id === m.timeSkipId)} onOpenLink={openLink}/>))))}
</div>
</div>
<Composer draft={draft} setDraft={updateDraft} loaded={!!loaded} streaming={streaming} onSubmit={submit} onKey={onComposerKey} session={session} onPreview={openPreview} textareaRef={textarea}/>
@@ -526,7 +526,7 @@ function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session
</div>) : null)}
</div>);
}
-function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, }: {
+function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, timeSkipTab = true, }: {
message: ChatMessage;
isLast: boolean;
onEditPrompt: (text: string) => void;
@@ -535,6 +535,8 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
onOpenTimeSkip: (id: string) => void;
timeSkipDone: boolean;
timeSkipReal?: boolean;
+ /** The comparison sidebar tab exists (a finished run with changes): only then is there something for the card to open. */
+ timeSkipTab?: boolean;
}) {
const streaming = useStore(s => s.streaming);
const [sentTime, setSentTime] = useState(() => relTime(m.at));
@@ -578,7 +580,7 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp
{tr(m.streaming && m.content ? <span className="caret" aria-hidden="true"/> : null)}
</div>
- {tr(m.timeSkipId ? <button className="timeskip-chat-card" onClick={() => onOpenTimeSkip(m.timeSkipId!)}><Icon name="branch" size={20}/><span><strong>{tr("Time-skip")}</strong><span>{tr(timeSkipDone ? 'Result ready · compare versions' : 'Revising · follow progress')}</span></span><Icon name="chevron" size={16} className="timeskip-card-arrow"/></button> : null)}
+ {tr(m.timeSkipId && timeSkipTab ? <button className="timeskip-chat-card" onClick={() => onOpenTimeSkip(m.timeSkipId!)}><Icon name="branch" size={20}/><span><strong>{tr("Time-skip")}</strong><span>{tr(timeSkipDone ? 'Result ready · compare versions' : 'Revising · follow progress')}</span></span><Icon name="chevron" size={16} className="timeskip-card-arrow"/></button> : null)}
{tr(m.media?.length ? <ChatMedia items={m.media} onPreview={onPreview}/> : null)}
{tr(m.artifacts?.length ? <div className="artifact-cards">{tr(m.artifacts.map(a => <ArtifactCard key={a.id} artifact={a} onPreview={onPreview}/>))}</div> : null)}
diff --git a/apps/host/tests/timeskip-real.test.mjs b/apps/host/tests/timeskip-real.test.mjs
index c52b0b80e..47f9ee805 100644
--- a/apps/host/tests/timeskip-real.test.mjs
+++ b/apps/host/tests/timeskip-real.test.mjs
@@ -5,7 +5,7 @@
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 { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -94,3 +94,66 @@ test('a run whose host is gone reads as interrupted, not as still working', { sk
assert.equal(ts.status(id).phase, 'interrupted');
} finally { rmSync(dir, { recursive: true, force: true }); }
});
+
+test('Stop ends the job and everything it started, deletes the copies, leaves the person\'s files alone, and the run then reads as cancelled', { skip: !hasPython && 'no python on this machine', timeout: 120000 }, async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ts-stop-'));
+ try {
+ const workspace = join(dir, 'work'); mkdirSync(workspace);
+ writeFileSync(join(workspace, 'plan.md'), 'first draft\n');
+ const pidFile = join(dir, 'revise.pid');
+ const script = join(dir, 'slow.mjs');
+ writeFileSync(script, `import { writeFileSync } from 'node:fs'; writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); writeFileSync('half-done.md', 'x'); await new Promise(r => setTimeout(r, 120000));`);
+ const state = join(dir, 'state');
+ const ts = createTimeSkip({ repoRoot: REPO, python: PYTHON, env: { ...process.env, STRATA_TIMESKIP_DIR: state } });
+ const started = await ts.startDetached({ workspace, prompt: 'slow one', attempts: 1, reviseCommand: `"${process.execPath}" "${script}"` });
+ assert.ok(started.ok, JSON.stringify(started));
+ const id = started.run.id;
+ for (let i = 0; i < 100 && !existsSync(pidFile); i++) await sleep(200);
+ assert.ok(existsSync(pidFile), 'the revision step is running');
+ const pid = Number(readFileSync(pidFile, 'utf8'));
+ assert.equal(ts.status(id).phase, 'generating');
+ assert.equal(await ts.stop(id), true);
+ assert.equal(existsSync(join(state, id)), false, 'the copies are deleted');
+ assert.equal(ts.status(id).phase, 'cancelled');
+ let alive = true; for (let i = 0; i < 40 && alive; i++) { try { process.kill(pid, 0); await sleep(150); } catch { alive = false; } }
+ assert.equal(alive, false, 'the revision command (a grandchild of the job) was ended too');
+ assert.equal(readFileSync(join(workspace, 'plan.md'), 'utf8'), 'first draft\n');
+ assert.equal(existsSync(join(workspace, 'half-done.md')), false, 'nothing reached the person\'s folder');
+ assert.equal(await ts.stop('b'.repeat(32)), false, 'an id that is not a run is not "stopped"');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('the revision step reads the host\'s stream: a long silent turn is fine, a failure is told in the host\'s words, a vanished host is "could not be reached"', { timeout: 60000 }, async () => {
+ const http = await import('node:http');
+ const { spawn } = await import('node:child_process');
+ const script = join(REPO, 'apps', 'host', 'server', 'timeskip-revise.mjs');
+ const mode = { current: 'ok' };
+ const server = http.createServer((req, res) => {
+ if (req.headers['x-strata-internal'] !== 's3cret') { res.writeHead(403, { 'content-type': 'application/json' }); res.end('{"error":"Not allowed."}'); return; }
+ if (mode.current === 'refuse') { res.writeHead(503, { 'content-type': 'application/json' }); res.end('{"error":"Load a model first, then try Time-skip again."}'); return; }
+ res.writeHead(200, { 'content-type': 'application/x-ndjson' });
+ res.write('{"type":"beat"}\n');
+ setTimeout(() => res.write('{"type":"beat"}\n'), 300);
+ setTimeout(() => {
+ if (mode.current === 'ok') res.end('{"type":"result","text":"I added a second line."}\n');
+ else if (mode.current === 'error') res.end('{"type":"error","message":"The model stopped answering."}\n');
+ else res.end(); // the stream ends with no result
+ }, 900);
+ });
+ await new Promise(r => server.listen(0, '127.0.0.1', r));
+ const run = (env = {}) => new Promise(resolve => {
+ const child = spawn(process.execPath, [script], { env: { ...process.env, STRATA_HOST_URL: `http://127.0.0.1:${server.address().port}`, STRATA_INTERNAL_SECRET: 's3cret', STRATA_TIMESKIP_PROMPT: 'x', ...env } });
+ let out = '', err = ''; child.stdout.on('data', d => { out += d; }); child.stderr.on('data', d => { err += d; });
+ child.on('close', code => resolve({ code, out: out.trim(), err: err.trim() }));
+ });
+ try {
+ mode.current = 'ok'; assert.deepEqual(await run(), { code: 0, out: 'I added a second line.', err: '' });
+ mode.current = 'error'; const bad = await run(); assert.equal(bad.code, 1); assert.equal(bad.err, 'The model stopped answering.');
+ mode.current = 'cut'; const cut = await run(); assert.equal(cut.code, 1); assert.match(cut.err, /stopped before it finished/);
+ mode.current = 'refuse'; assert.match((await run()).err, /Load a model first/);
+ assert.match((await run({ STRATA_INTERNAL_SECRET: 'wrong' })).err, /Not allowed/);
+ assert.match((await run({ STRATA_INTERNAL_SECRET: '' })).err, /needs the Strata app/);
+ } finally { server.close(); }
+ const gone = await new Promise(resolve => { const child = spawn(process.execPath, [script], { env: { ...process.env, STRATA_HOST_URL: 'http://127.0.0.1:9', STRATA_INTERNAL_SECRET: 's', STRATA_TIMESKIP_PROMPT: 'x' } }); let err = ''; child.stderr.on('data', d => { err += d; }); child.on('close', code => resolve({ code, err })); });
+ assert.equal(gone.code, 1); assert.match(gone.err, /could not be reached/);
+});
diff --git a/apps/host/tests/tune-and-timeskip-routes.test.mjs b/apps/host/tests/tune-and-timeskip-routes.test.mjs
index 9dbadde1b..9ee71a39a 100644
--- a/apps/host/tests/tune-and-timeskip-routes.test.mjs
+++ b/apps/host/tests/tune-and-timeskip-routes.test.mjs
@@ -45,6 +45,8 @@ async function startHost({ python } = {}) {
env: {
...process.env,
STRATA_HOME: home,
+ // the Time-skip runs of whoever uses this PC live in their own state folder; a test must not read (or write) them
+ STRATA_TIMESKIP_DIR: join(home, 'time-skip'),
STRATA_PORT: String(port),
STRATA_REAL_ENGINE: '0',
...(python ? { STRATA_PYTHON: python } : {}),