diff --git a/apps/host/server/engine-step.mjs b/apps/host/server/engine-step.mjs index fa40d0e6..da774247 100644 --- a/apps/host/server/engine-step.mjs +++ b/apps/host/server/engine-step.mjs @@ -32,7 +32,7 @@ export function createEngineStep({ control, signal = null, onChange = () => {} } try { report = await control.updateCheck(); } catch (error) { - if (usable) { set({ state: 'skipped', message: 'The engine for this PC is installed.', details: 'The update server could not be reached, so a newer engine was not looked for.' }); return { ...part }; } + if (usable) { set({ state: 'skipped', message: 'The engine for this PC is installed.' }); return { ...part }; } throw error; } const engine = report.engine ?? {}; diff --git a/apps/host/src/components/ChatModelPicker.tsx b/apps/host/src/components/ChatModelPicker.tsx index eb0eeb4b..bc759c03 100644 --- a/apps/host/src/components/ChatModelPicker.tsx +++ b/apps/host/src/components/ChatModelPicker.tsx @@ -3,7 +3,7 @@ import { modelFamilyIcon } from '../lib/model-icons'; import { useId, useRef, useState } from 'react'; import { FloatingMenu } from './FloatingMenu'; import { Bar, Btn, Dialog, ErrorNotice, Icon } from './ui'; -import { go, lifecycleStatus, loadVariant, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; +import { go, useLifecycle, loadVariant, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; import { pickerGroups, pickerVersionState } from '../lib/model-picker'; import { versionFit } from '../lib/model-versions'; import type { ModelVariant } from '../lib/types'; @@ -28,7 +28,7 @@ function LegacyChatModelPicker() { const providers = useStore(s => s.providers), remote = useStore(s => s.remoteModel), streaming = useStore(s => s.streaming); const connection = providers?.connections.find(c => c.id === remote?.connectionId); const apiModel = connection?.models.find(m => m.id === remote?.modelId); - const lifecycle = lifecycleStatus(useStore(s => s)); + const lifecycle = useLifecycle(); const [open, setOpen] = useState(false), [selected, setSelected] = useState(null); const [pending, setPending] = useState(false), [error, setError] = useState(''); const [expanded, setExpanded] = useState([]); diff --git a/apps/host/src/components/ComposerControls.tsx b/apps/host/src/components/ComposerControls.tsx index 485cfe97..fd680d8e 100644 --- a/apps/host/src/components/ComposerControls.tsx +++ b/apps/host/src/components/ComposerControls.tsx @@ -48,6 +48,7 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas const trigger = useRef(null), modeTrigger = useRef(null), thinkingTrigger = useRef(null); const attachLatest = useRef(onAttach); attachLatest.current = onAttach; + const addFilesLatest = useRef<(files: File[]) => Promise>(async () => { }); const mode = modes.find(m => m.value === session?.preferences?.mode) ?? modes[0]; const effort = efforts.includes(session?.preferences?.thinking ?? '') ? session!.preferences!.thinking! : 'Medium'; const budget = session?.preferences?.thinkingBudget ?? 0; @@ -117,6 +118,7 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas setReading(false); } } + addFilesLatest.current = files => addFiles(files); useEffect(() => { folder.current?.setAttribute('webkitdirectory', ''); const key = (e: KeyboardEvent) => { @@ -127,10 +129,12 @@ export function ComposerControls({ session, onPreview, onAttach, onError, onSlas }; const website = () => { setUrlOpen(true); setError(''); }; const preview = () => previewFile.current?.click(); + const dropped = (e: Event) => { if (!streaming && !reading) void addFilesLatest.current((e as CustomEvent).detail ?? []); }; + window.addEventListener('strata:drop-files', dropped); window.addEventListener('keydown', key); window.addEventListener('strata:open-website', website); window.addEventListener('strata:open-preview', preview); - return () => { window.removeEventListener('keydown', key); window.removeEventListener('strata:open-website', website); window.removeEventListener('strata:open-preview', preview); }; + return () => { window.removeEventListener('strata:drop-files', dropped); window.removeEventListener('keydown', key); window.removeEventListener('strata:open-website', website); window.removeEventListener('strata:open-preview', preview); }; }, [streaming, reading]); useEffect(() => { if (preferences !== 'mode') diff --git a/apps/host/src/components/Deliverables.tsx b/apps/host/src/components/Deliverables.tsx new file mode 100644 index 00000000..48b850a0 --- /dev/null +++ b/apps/host/src/components/Deliverables.tsx @@ -0,0 +1,73 @@ +import { useRef, useState } from 'react'; +import { tr } from '../lib/i18n'; +import { fileAction, fileSize, fileTypeLabel, previewOf, rawUrlOf, type ActivityGroup, type Deliverable } from '../lib/deliverables'; +import type { PreviewArtifact } from '../lib/artifacts'; +import { pushToast } from '../lib/store'; +import { plainFailureText } from '../lib/plain-errors'; +import { FloatingMenu } from './FloatingMenu'; +import { Icon } from './ui'; + +const problem = (title: string, e: unknown) => pushToast('error', tr(title), plainFailureText(e instanceof Error ? e.message : String(e)).message); + +/** A line's numbers ("+225 −0") shown as a pair of small figures; the sentence itself stays plain grey. */ +export function Plusminus({ added, removed }: { added: number; removed: number }) { + return +{added}−{removed}; +} + +const showOf = (file: { path: string; name: string }, sessionId: string, onPreview: (a: PreviewArtifact) => void, kind?: string) => + previewOf(sessionId, file).then(onPreview, e => { + // A file with no preview opens in its own app instead. + if (kind === 'other') return fileAction.open(sessionId, file.path, 'app').catch(err => problem('The file was not opened', err)); + return problem('The file has no preview', e); + }); + +/** One file the assistant made or changed: its type, name and size, and Open (in the sidebar) with a menu for the other things to do with it. */ +export function FileCard({ file, sessionId, onPreview }: { file: Deliverable; sessionId: string; onPreview: (a: PreviewArtifact) => void }) { + const more = useRef(null); + const [menu, setMenu] = useState(false), [busy, setBusy] = useState(false); + const run = async (fn: () => Promise, failed: string) => { setMenu(false); try { await fn(); } catch (e) { problem(failed, e); } }; + return
+ {fileTypeLabel(file)} + {file.name}{fileSize(file.size)} + + + + + {tr(menu ? setMenu(false)}> + + + + : null)} +
; +} + +/** "Edited N files": each with its lines added and removed, and the total under See all. */ +export function EditedFiles({ files, sessionId, onPreview }: { files: Deliverable[]; sessionId: string; onPreview: (a: PreviewArtifact) => void }) { + const [all, setAll] = useState(false); + const textual = files.filter(f => f.lines !== null); + if (textual.length < 2) return null; + const shown = all ? textual : textual.slice(0, 3); + const added = textual.reduce((n, f) => n + f.added, 0), removed = textual.reduce((n, f) => n + f.removed, 0); + return
+
{tr('Edited {0} files', [textual.length])}
+ {shown.map(f => )} + +
; +} + +/** A run of tool use between two pieces of text, as one quiet line: "Ran 2 commands, read monitor.png", with a thumbnail when it touched a picture. */ +export function ActivityLine({ group, sessionId, onPreview }: { group: ActivityGroup; sessionId: string; onPreview: (a: PreviewArtifact) => void }) { + const [open, setOpen] = useState(false); + const picture = group.files.find(f => f.kind === 'image'); + // The host's sentence may end with the numbers ("… +225 −0"): they are drawn as figures instead. + const sentence = group.line.replace(/\s*\+\d+\s*[−-]\s*\d+\s*$/, ''); + return
+ + {picture ? void showOf(picture, sessionId, onPreview)}/> : null} + {open ?
    {group.files.map(f =>
  • )}
: null} +
; +} diff --git a/apps/host/src/components/DropZone.tsx b/apps/host/src/components/DropZone.tsx new file mode 100644 index 00000000..44c935a6 --- /dev/null +++ b/apps/host/src/components/DropZone.tsx @@ -0,0 +1,21 @@ +import { useRef, useState, type ReactNode } from 'react'; +import { tr } from '../lib/i18n'; +import { Icon } from './ui'; + +/** Files dropped on the chat go where the attach button would put them: the composer reads the 'strata:drop-files' event. */ +export const DROP_EVENT = 'strata:drop-files'; +const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files'); + +/** The conversation column, with a calm highlight while something is dragged over it. */ +export function DropZone({ children, className }: { children: ReactNode; className?: string }) { + const [over, setOver] = useState(false); + const depth = useRef(0); + return
{ if (!hasFiles(e)) return; e.preventDefault(); depth.current++; setOver(true); }} + onDragOver={e => { if (!hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }} + onDragLeave={e => { if (!hasFiles(e)) return; depth.current = Math.max(0, depth.current - 1); if (!depth.current) setOver(false); }} + onDrop={e => { if (!hasFiles(e)) return; e.preventDefault(); depth.current = 0; setOver(false); const files = Array.from(e.dataTransfer.files); if (files.length) window.dispatchEvent(new CustomEvent(DROP_EVENT, { detail: files })); }}> + {children} + {over ? : null} +
; +} diff --git a/apps/host/src/components/FamilySwitch.tsx b/apps/host/src/components/FamilySwitch.tsx index 27d55f59..7b7c2a4b 100644 --- a/apps/host/src/components/FamilySwitch.tsx +++ b/apps/host/src/components/FamilySwitch.tsx @@ -1,12 +1,30 @@ +import { useRef, useState } from 'react'; import { tr } from '../lib/i18n'; import type { CatalogModel } from '../lib/native-catalog'; +import { FloatingMenu } from './FloatingMenu'; +import { Icon } from './ui'; -/** The model families of the catalog as a switch in the navbar (Qwen3.8-Flash-Next, Qwen3.6-35B-A3B). A single family is just its name. */ +/** + * The model family in the Models navbar: its icon, its name and a chevron. Opening it lists the families of the catalog (Qwen3.8-Flash-Next, + * Qwen3.6-35B-A3B, and future ones) to switch between. One family still shows as the same control, so the page looks the same as families arrive. + */ export function FamilySwitch({ families, selected, onPick }: { families: CatalogModel[]; selected?: string; onPick: (family: CatalogModel) => void }) { const shown = families.filter(f => f.sizes.length); - if (shown.length < 2) return shown[0] ? {tr(shown[0].title)} : null; - return
- {shown.map(f => )} -
; + const trigger = useRef(null); + const [open, setOpen] = useState(false); + if (!shown.length) return null; + const current = shown.find(f => f.family === selected) ?? shown[0]; + return <> + + {tr(open ? setOpen(false)}> +
+ {shown.map(f => )} +
+
: null)} + ; } diff --git a/apps/host/src/components/FloatingMenu.tsx b/apps/host/src/components/FloatingMenu.tsx index ac6fcb3f..ab903435 100644 --- a/apps/host/src/components/FloatingMenu.tsx +++ b/apps/host/src/components/FloatingMenu.tsx @@ -14,7 +14,7 @@ export function FloatingMenu({ anchor, title, onClose, children, width = 232 }: const rect = anchor?.getBoundingClientRect(); const height = ref.current?.getBoundingClientRect().height ?? 200; const left = Math.max(12, Math.min(rect?.left ?? 12, window.innerWidth - Math.min(width, window.innerWidth - 24) - 12)); - const below = rect?.bottom ?? 12; + const below = (rect?.bottom ?? 12) + 8; // a little air between the button and its panel const top = below + height + 12 <= window.innerHeight ? below : Math.max(12, (rect?.top ?? window.innerHeight) - height - 6); setPlaced({ left, top }); ref.current?.querySelector('[role="menuitem"]:not(:disabled), [role="menuitemradio"]:not(:disabled)')?.focus(); diff --git a/apps/host/src/components/FolderChip.tsx b/apps/host/src/components/FolderChip.tsx new file mode 100644 index 00000000..56b121c1 --- /dev/null +++ b/apps/host/src/components/FolderChip.tsx @@ -0,0 +1,28 @@ +import { useState } from 'react'; +import { tr } from '../lib/i18n'; +import { chooseChatFolder, setChatFolder, useChatFolder } from '../lib/chat-folder'; +import { pushToast } from '../lib/store'; +import { plainFailureText } from '../lib/plain-errors'; +import { Icon } from './ui'; + +/** + * The chat's project folder, above the message box on the left: its name (the full path on hover), or "Select a folder". A click opens the + * system folder picker; the small x goes back to the default folder. The assistant works inside this folder and nowhere else. + */ +export function FolderChip({ chatId, disabled }: { chatId: string | null | undefined; disabled?: boolean }) { + const folder = useChatFolder(chatId); + const [busy, setBusy] = useState(false); + if (!chatId) return null; + const run = async (fn: () => Promise) => { + setBusy(true); + try { await fn(); } catch (e) { pushToast('error', tr("The folder was not changed"), plainFailureText(e instanceof Error ? e.message : String(e)).message); } + finally { setBusy(false); } + }; + const label = folder ? folder.name : tr("Select a folder"); + return
+ + {folder ? : null} +
; +} diff --git a/apps/host/src/components/LifecycleNotice.tsx b/apps/host/src/components/LifecycleNotice.tsx index aa4cdcd1..30bd19c2 100644 --- a/apps/host/src/components/LifecycleNotice.tsx +++ b/apps/host/src/components/LifecycleNotice.tsx @@ -1,10 +1,10 @@ import { tr } from '../lib/i18n'; -import { go, lifecycleStatus, useStore } from '../lib/store'; +import { go, useLifecycle } from '../lib/store'; import { Btn } from './ui'; export function LifecycleNotice({ showScope = true }: { showScope?: boolean; }) { - const status = lifecycleStatus(useStore(s => s)); + const status = useLifecycle(); if (!showScope && status.allowed) return null; return
{tr(showScope ? {tr("Global \u00B7 all chats")} : null)}{tr(!status.allowed ? <>{tr(status.reason)} go('serving')}>{tr("View requests")} : null)}
; diff --git a/apps/host/src/components/ManagedModelLibrary.tsx b/apps/host/src/components/ManagedModelLibrary.tsx index ecedf0b2..5f69013d 100644 --- a/apps/host/src/components/ManagedModelLibrary.tsx +++ b/apps/host/src/components/ManagedModelLibrary.tsx @@ -10,7 +10,7 @@ import { familyVersion, modelFamilies, modelVersions, versionFit } from '../lib/ import { contextTokens, estimate, execution } from '../lib/experience'; import { planMemory } from '../lib/run-memory'; import type { ModelVariant } from '../lib/types'; -import { cancelInstall, installVariant, lifecycleStatus, loadVariant, removeVariant, runtimeModelAction, useStore } from '../lib/store'; +import { cancelInstall, installVariant, useLifecycle, loadVariant, removeVariant, runtimeModelAction, useStore } from '../lib/store'; export function ManagedModelLibrary({ contextOverride, familyOverride, selectedVariant, onChoose }: { contextOverride?: number; familyOverride?: string; @@ -19,7 +19,7 @@ export function ManagedModelLibrary({ contextOverride, familyOverride, selectedV }) { const library = useStore(s => s.library), hardware = useStore(s => s.hardware), engine = useStore(s => s.engine); const runtime = useStore(s => s.runtime), serving = useStore(s => s.serving); - const lifecycle = lifecycleStatus(useStore(s => s)); + const lifecycle = useLifecycle(); const [selected, setSelected] = useState(selectedVariant ?? ''); const [familyChoice, setFamilyChoice] = useState(familyOverride ?? ''); const [pending, setPending] = useState(false), [error, setError] = useState(''); diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index daddadb0..65785517 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -17,6 +17,7 @@ import { tuneEffective } from '../lib/native-tune'; import { tunedFields } from '../lib/tune-values'; import { NativeSettings } from './NativeSettings'; import { RunImageModel } from './RunImageModel'; +import { IMAGE_GENERATION_VISIBLE } from '../lib/features'; import { useStore } from '../lib/store'; import { NativePresets } from './NativePresets'; import { NativeTune } from './NativeTune'; @@ -127,7 +128,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
{tr("Conversation context")} setVision(e.target.checked ? 'yes' : 'no')}/>{tr("Read pictures ")}{tr("Optional")}{tr("Understand photos, screenshots and charts. Vision files download automatically. Enable them when loading this model.")}{tr(expert && vision !== 'no' ? setVision(e.target.checked ? 'yes' : 'no')}/>{tr("Read pictures ")}{tr("Optional")}{tr("Understand photos, screenshots and charts. Vision files download automatically. Enable them when loading this model.")}{tr(expert && vision !== 'no' ? ({ value: String(g.index), label: `GPU ${g.index + 1} · ${g.name}` })), ...((native?.hardware?.gpus.length ?? 0) > 1 ? [{ value: 'split', label: 'Split across GPUs…' }] : [])]} onChange={value => { setDeviceChoice(value); setGpus(value === 'auto' ? [] : value === 'split' ? (native?.hardware?.gpus ?? []).map(g => g.index) : [Number(value)]); }}/>{tr(deviceChoice === 'split' ?
{tr(native?.hardware?.gpus.map(g => ))}
: null)}{tr(gpus.length > 1 ? : null)}
{tr(installed ? :

{tr("More engine parameters become available after preparing this version.")}

)} : null)}
@@ -171,4 +172,4 @@ catch (e) { } finally { setStopping(false); -} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : job.kind === 'autotune' || job.kind === 'recheck' ? 'Tuning your model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' || job.kind === 'autotune' || job.kind === 'recheck' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? installStepLabel(job.result?.install?.step) : job.summary)}

{tr(download ? <>

{tr(download.file === 'model files' ? 'Model files' : download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}
{tr("Details")}

{tr("Completed files are retained. Downloading, packing and loading are separate stages; readiness is confirmed by the engine.")}

{tr(detailsText ?
{detailsText}
: null)}
{tr(error ? : null)}
; } +} } return

{tr(job.kind === 'install' ? 'Preparing your model' : job.kind === 'load' ? 'Loading model' : job.kind === 'autotune' || job.kind === 'recheck' ? 'Tuning your model' : 'Engine operation')}

{tr(job.kind === 'install' || job.kind === 'load' || job.kind === 'autotune' || job.kind === 'recheck' ?
{tr(eta ? {eta} : null)} void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}
: null)}

{tr(job.kind === 'install' ? installStepLabel(job.result?.install?.step) : job.summary)}

{tr(download ? <>

{tr(download.file === 'model files' ? 'Model files' : download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}

: null)}{tr(detailsText ?
{tr("Details")}
{detailsText}
: null)}{tr(error ? : null)}
; } diff --git a/apps/host/src/components/TimeSkipPanel.tsx b/apps/host/src/components/TimeSkipPanel.tsx index a12d1fbe..b6450f18 100644 --- a/apps/host/src/components/TimeSkipPanel.tsx +++ b/apps/host/src/components/TimeSkipPanel.tsx @@ -4,10 +4,12 @@ import type { PreviewArtifact } from '../lib/artifacts'; import { plainTimeSkipError, replayTimeSkip, setTimeSkipResult, stopTimeSkip } from '../lib/store'; import { realTimeSkipDocuments, timeSkipCheckOutcomes, timeSkipDocumentMarkdown, timeSkipDocuments, timeSkipExample, timeSkipResultState, type TimeSkipDocument, type TimeSkipRun, type TimeSkipVersion } from '../lib/time-skip'; import { TimeSkipWorking } from './TimeSkipWorking'; +import { isForkJob } from '../lib/time-skip'; import { FloatingMenu } from './FloatingMenu'; import { TimeSkipCompare } from './TimeSkipCompare'; import { Btn, Dialog, Icon } from './ui'; -function VersionTabs({ version, onChange, done }: { +function VersionTabs({ version, onChange, done, fork }: { + fork?: boolean; version: TimeSkipVersion; onChange: (version: TimeSkipVersion) => void; done: boolean; @@ -22,7 +24,7 @@ function VersionTabs({ version, onChange, done }: { const next = event.key === 'Home' ? 0 : event.key === 'End' ? 1 : (i + 1) % 2; onChange(options[next]); event.currentTarget.parentElement?.querySelectorAll('[role="tab"]')[next]?.focus(); - }}>{tr(which === 'original' ? 'Original' : done ? 'Updated' : 'Update')}))} + }}>{tr(fork ? (which === 'original' ? 'A' : 'B') : which === 'original' ? 'Original' : done ? 'Updated' : 'Update')}))} ; } function ImageResult({ document, original, compare }: { @@ -133,6 +135,7 @@ export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onC // Snapshot IDs include the run clock, so replaying never reuses an old artifact. onPreview({ id: `${run.id}-${run.startedAt}-${which}`, kind: 'markdown', title: `${which}-${document.code ? 'counter' : 'launch-plan'}.md`, content: timeSkipDocumentMarkdown(document), demo: true }); } + const forkRun = isForkJob(run.job); function restore(which: TimeSkipVersion) { setTimeSkipResult(sessionId, run.id, which); setVersion(which); @@ -143,12 +146,12 @@ export function TimeSkipPanel({ run, sessionId, inline, expanded, onCompare, onC const content = ; return inline ? content : {tr(content)}; diff --git a/apps/host/src/components/TimeSkipWorking.tsx b/apps/host/src/components/TimeSkipWorking.tsx index c659f6c7..e45c8ae6 100644 --- a/apps/host/src/components/TimeSkipWorking.tsx +++ b/apps/host/src/components/TimeSkipWorking.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { tr } from '../lib/i18n'; -import type { TimeSkipRun } from '../lib/time-skip'; +import { isForkJob, type ForkLane, type TimeSkipJob, type TimeSkipRun } from '../lib/time-skip'; import { activityWords, phaseFraction } from '../lib/time-skip-activity'; import { stopTimeSkip } from '../lib/store'; import { Btn } from './ui'; @@ -16,16 +16,56 @@ export function TimeSkipWorking({ run, sessionId }: { run: TimeSkipRun; sessionI const [stopping, setStopping] = useState(false); useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []); const fraction = phaseFraction(run.job?.phase); + const fork = isForkJob(run.job); return
+ {fork ? : null}
{activityWords(run.job)}{clock(now - run.startedAt)} -
+ {fork ? null :
}
{ setStopping(true); void stopTimeSkip(sessionId, run.id).finally(() => setStopping(false)); }}>{tr("Stop")}
; } + +const laneFraction = (l: ForkLane | null | undefined) => (l && l.total > 0 ? Math.min(1, (l.state === 'done' ? l.total : Math.max(0, l.step - 1)) / l.total) : 0); + +function Lane({ name, lane, waitingText }: { name: string; lane: ForkLane | null | undefined; waitingText: string }) { + const pct = Math.round(laneFraction(lane) * 100); + const words = !lane ? waitingText : lane.waiting ? waitingText : lane.line || (lane.text ? tr('Step {0} of {1}: {2}', [lane.step, lane.total, lane.text]) : tr('Starting…')); + return
+ {name} +
+ {words} +
; +} + +/** + * The fork design (notes-split-agent8.md, item 11): the plan as a list, the one step the assistant chose to check and branch at (with its one-line + * why), and the two agents' progress. B starts at that step from A's work so far. + */ +export function ForkProgress({ job }: { job: TimeSkipJob }) { + const steps = job.plan?.steps ?? [], lever = job.lever; + const reachedA = job.a?.step ?? 0; + const short = !lever && steps.length > 0 && steps.length < 3; + return
+ {steps.length ?
    + {steps.map((s, i) => { + const n = i + 1, state = job.a && job.a.state === 'done' || n < reachedA ? 'done' : n === reachedA ? 'running' : 'pending'; + return
  1. + + {s.text}{lever?.step === n ? {tr("Checking here matters most")}{lever.why ? ' · ' + lever.why : ''}{lever.defaulted ? ' · ' + tr('chosen by default') : ''} : null} +
  2. ; + })} +
: null} + {short ?

{tr("This is a short job, so there is one version. Nothing is worth branching.")}

: null} +
+ + {short ? null : } +
+
; +} diff --git a/apps/host/src/components/VersionPicker.tsx b/apps/host/src/components/VersionPicker.tsx index 03939dc8..b173a737 100644 --- a/apps/host/src/components/VersionPicker.tsx +++ b/apps/host/src/components/VersionPicker.tsx @@ -55,7 +55,7 @@ export function VersionPicker({ versions, selectedId, hardware, onSelect, onOwnG {tr(open ? setOpen(false)}>
diff --git a/apps/host/src/lib/chat-folder.ts b/apps/host/src/lib/chat-folder.ts new file mode 100644 index 00000000..7b3df605 --- /dev/null +++ b/apps/host/src/lib/chat-folder.ts @@ -0,0 +1,48 @@ +import { useEffect, useSyncExternalStore } from 'react'; +import { api } from './client'; + +/** A chat's project folder (notes-split-agent8.md, item 4): the assistant works inside it and can only touch files in it. */ +export interface ChatFolder { path: string; name: string; exists: boolean } +const folders = new Map(); +const listeners = new Set<() => void>(); +const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; }; +const emit = () => listeners.forEach(fn => fn()); + +export function readFolder(raw: unknown): ChatFolder | null { + if (!raw || typeof raw !== 'object') return null; + const f = raw as Record; + if (typeof f.path !== 'string' || !f.path) return null; + return { path: f.path, name: typeof f.name === 'string' && f.name ? f.name : f.path.split(/[\/]/).filter(Boolean).at(-1) ?? f.path, exists: f.exists !== false }; +} + +function put(chatId: string, folder: ChatFolder | null) { + if (JSON.stringify(folders.get(chatId) ?? null) === JSON.stringify(folder) && folders.has(chatId)) return; + folders.set(chatId, folder); emit(); +} + +export const folderOf = (chatId: string | null | undefined) => (chatId ? folders.get(chatId) ?? null : null); + +export function useChatFolder(chatId: string | null | undefined): ChatFolder | null { + const value = useSyncExternalStore(subscribe, () => folderOf(chatId), () => null); + useEffect(() => { if (chatId) void loadFolder(chatId); }, [chatId]); + return value; +} + +export async function loadFolder(chatId: string) { + try { put(chatId, readFolder((await api.get<{ folder: unknown }>(`/api/chat/folder?sessionId=${encodeURIComponent(chatId)}`)).folder)); } + catch { /* an older host has no folder route: no chip */ } +} + +/** Ask the system for a folder (null when the person closes the dialog), then make it this chat's. */ +export async function chooseChatFolder(chatId: string): Promise<'chosen' | 'cancelled'> { + const picked = await api.post<{ path?: string; cancelled?: boolean }>('/api/workspaces/pick', {}); + if (!picked.path) return 'cancelled'; + await setChatFolder(chatId, picked.path); + return 'chosen'; +} + +/** `null` goes back to the default workspace. The host answers a plain sentence when the folder is not allowed (409 while the chat runs). */ +export async function setChatFolder(chatId: string, path: string | null) { + const result = await api.post<{ folder: unknown }>('/api/chat/folder', { sessionId: chatId, path }); + put(chatId, readFolder(result.folder)); +} diff --git a/apps/host/src/lib/chat-photos.ts b/apps/host/src/lib/chat-photos.ts index 4fb53773..684eebee 100644 --- a/apps/host/src/lib/chat-photos.ts +++ b/apps/host/src/lib/chat-photos.ts @@ -8,6 +8,10 @@ export async function attachChatPhoto(file:File,id?:string|null){if(!['image/png export function removeChatPhoto(photo:string,id?:string|null){queues.set(key(id),(queues.get(key(id))??[]).filter(i=>i.id!==photo));listeners.forEach(fn=>fn());} export function pendingChatPhotos(id?:string|null){return queues.get(key(id))??empty;} export function takeChatPhotos(id?:string|null){const value=queues.get(key(id))??[];queues.delete(key(id));listeners.forEach(fn=>fn());return value;} +/** The stored picture itself, for uploading it to the host. */ +export async function photoBlob(photo:ChatPhoto):Promise{const db=await database();const file=await new Promise((resolve,reject)=>{const request=db.transaction('photos','readonly').objectStore('photos').get(photo.id);request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(new Error('Could not read the attached picture.'));});db.close();if(!file)throw new Error(`${photo.name} is no longer in browser storage. Attach it again.`);return file;} +/** Upload the pictures of a message to the chat (POST /api/chat/upload); the host answers an id for each, which the send names as imageIds. */ +export async function uploadChatPhotos(photos:ChatPhoto[],sessionId:string):Promise{const ids:string[]=[];for(const photo of photos){const blob=await photoBlob(photo);const res=await fetch(`${(globalThis as {__STRATA_HOST__?:string}).__STRATA_HOST__??""}/api/chat/upload?sessionId=${encodeURIComponent(sessionId)}&name=${encodeURIComponent(photo.name)}`,{method:'POST',headers:{'content-type':blob.type||'application/octet-stream'},body:blob});const data=await res.json().catch(()=>({})) as {files?:{id:string|null;kind:string}[];error?:string};if(!res.ok)throw new Error(data.error||'The picture could not be sent. Try another one.');const id=data.files?.find(f=>f.kind==='image'&&f.id)?.id;if(!id)throw new Error('The picture could not be read. Use a PNG, JPEG or WebP picture.');ids.push(id);}return ids;} export async function photoData(photo:ChatPhoto){const db=await database();const file=await new Promise((resolve,reject)=>{const request=db.transaction('photos','readonly').objectStore('photos').get(photo.id);request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(new Error('Could not read the attached picture.'));});db.close();if(!file)throw new Error(`${photo.name} is no longer in browser storage. Attach it again.`);return new Promise<{name:string;url:string}>((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve({name:photo.name,url:String(reader.result)});reader.onerror=()=>reject(new Error('Could not read this picture.'));reader.readAsDataURL(file);});} /** Keep at most three pictures in the inference context, including this turn. Originals remain in IndexedDB. */ diff --git a/apps/host/src/lib/deliverables.ts b/apps/host/src/lib/deliverables.ts new file mode 100644 index 00000000..0b597000 --- /dev/null +++ b/apps/host/src/lib/deliverables.ts @@ -0,0 +1,96 @@ +import { api } from './client'; +import type { PreviewArtifact } from './artifacts'; + +/** + * Deliverables and grouped activity (notes-split-agent8.md, item 12). The host sends `deliverable` frames for every file the assistant wrote or + * changed and `activity-group` frames for runs of tool use between two pieces of text. A reply keeps them in the order they came, so the text + * that arrives between activities reads as one continuous piece. + */ +export type DeliverableKind = 'html' | 'markdown' | 'pdf' | 'csv' | 'image' | 'code' | 'text' | 'other'; +export interface Deliverable { path: string; abs: string; name: string; kind: DeliverableKind; status: 'created' | 'changed'; size: number; lines: number | null; added: number; removed: number } +export interface GroupFile { path: string; name: string; kind: DeliverableKind; status: string; added: number; removed: number } +export interface ActivityGroup { id: string; closed: boolean; line: string; added: number; removed: number; files: GroupFile[] } +export type MessageBlock = { kind: 'text'; text: string } | ({ kind: 'group' } & ActivityGroup); + +const KINDS = ['html', 'markdown', 'pdf', 'csv', 'image', 'code', 'text', 'other']; +const num = (v: unknown) => (Number.isFinite(Number(v)) ? Number(v) : 0); + +export function readDeliverable(raw: unknown): Deliverable | null { + if (!raw || typeof raw !== 'object') return null; + const f = raw as Record; + if (typeof f.path !== 'string' || !f.path) return null; + const name = typeof f.name === 'string' && f.name ? f.name : f.path.split(/[\\/]/).at(-1) ?? f.path; + return { + path: f.path, abs: typeof f.abs === 'string' ? f.abs : f.path, name, kind: KINDS.includes(String(f.kind)) ? f.kind as DeliverableKind : 'other', + status: f.status === 'changed' ? 'changed' : 'created', size: num(f.size), lines: f.lines === null || f.lines === undefined ? null : num(f.lines), added: num(f.added), removed: num(f.removed), + }; +} + +export function readGroup(raw: unknown): ActivityGroup | null { + if (!raw || typeof raw !== 'object') return null; + const g = raw as Record; + if (typeof g.id !== 'string' || !g.id) return null; + const files = Array.isArray(g.files) ? g.files.flatMap((x): GroupFile[] => { + const d = readDeliverable(x); + return d ? [{ path: d.path, name: d.name, kind: d.kind, status: d.status, added: d.added, removed: d.removed }] : []; + }) : []; + return { id: g.id, closed: g.closed === true, line: typeof g.line === 'string' ? g.line : '', added: num(g.added), removed: num(g.removed), files }; +} + +/** Add streamed text to the reply's ordered pieces: it continues the last text piece, or starts a new one after an activity line. */ +export function appendText(blocks: MessageBlock[] | undefined, text: string): MessageBlock[] { + const list = blocks ?? [], last = list.at(-1); + if (last?.kind === 'text') return [...list.slice(0, -1), { kind: 'text', text: last.text + text }]; + return [...list, { kind: 'text', text }]; +} + +/** A group frame is re-sent while it grows: the same id replaces its line; a new id goes after what came before. */ +export function upsertGroup(blocks: MessageBlock[] | undefined, group: ActivityGroup): MessageBlock[] { + const list = blocks ?? [], at = list.findIndex(b => b.kind === 'group' && b.id === group.id); + const next: MessageBlock = { kind: 'group', ...group }; + return at >= 0 ? list.map((b, i) => (i === at ? next : b)) : [...list, next]; +} + +/** The same file may be written more than once in a run: one card per path, with its latest numbers. */ +export function mergeDeliverable(list: Deliverable[] | undefined, file: Deliverable): Deliverable[] { + const have = list ?? [], at = have.findIndex(f => f.path === file.path); + if (at < 0) return [...have, file]; + const old = have[at]; + return have.map((f, i) => (i === at ? { ...file, status: old.status === 'created' ? 'created' : file.status, added: old.added + file.added, removed: old.removed + file.removed } : f)); +} + +export const fileTypeLabel = (d: { kind: DeliverableKind; name: string }) => { + const ext = d.name.includes('.') ? d.name.split('.').at(-1)!.toUpperCase() : ''; + return d.kind === 'markdown' ? 'MD' : d.kind === 'html' ? 'HTML' : d.kind === 'csv' ? 'CSV' : d.kind === 'pdf' ? 'PDF' : ext && ext.length <= 10 ? ext : d.kind.toUpperCase(); +}; + +export function fileSize(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10240 ? 1 : 0)} KB`; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +const csvText = (rows: string[][]) => rows.map(r => r.map(c => (/[",\n]/.test(c) ? `"${c.replace(/"/g, '""')}"` : c)).join(',')).join('\n'); + +interface PreviewAnswer { kind: DeliverableKind; name: string; path: string; size: number; url?: string; text?: string; rows?: string[][]; rawUrl?: string; note?: string } + +/** The sidebar preview of a file: the host reads it (only inside the chat's folder) and the page draws it as a website, markdown, table, picture, PDF or code. */ +export async function previewOf(sessionId: string, file: { path: string; name: string }): Promise { + const a = await api.get(`/api/files/preview?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(file.path)}`); + const id = `file:${a.path}`, title = a.name || file.name; + if (a.kind === 'image' && a.rawUrl) return { id, kind: 'image', title, url: a.rawUrl }; + if (a.kind === 'pdf' && a.rawUrl) return { id, kind: 'pdf', title, url: a.rawUrl }; + if (a.kind === 'html' && a.text !== undefined) return { id, kind: 'website', title, content: a.text }; + if (a.kind === 'markdown' && a.text !== undefined) return { id, kind: 'markdown', title, content: a.text }; + if (a.kind === 'csv' && a.rows) return { id, kind: 'table', title, content: csvText(a.rows) }; + if (a.text !== undefined) return { id, kind: 'code', title, content: a.text }; + throw new Error(a.note || 'This file has no preview. Open it in its own app.'); +} + +export const fileAction = { + open: (sessionId: string, path: string, how: 'browser' | 'app' | 'folder') => api.post('/api/files/open', { sessionId, path, how }), + fullPath: async (sessionId: string, path: string) => (await api.get<{ path: string }>(`/api/files/path?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(path)}`)).path, + attach: (sessionId: string, path: string) => api.post('/api/chat/attachments', { sessionId, path }), +}; + +export const rawUrlOf = (sessionId: string, path: string) => `/api/files/raw?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(path)}`; diff --git a/apps/host/src/lib/features.ts b/apps/host/src/lib/features.ts index 86ba6efd..39b5f125 100644 --- a/apps/host/src/lib/features.ts +++ b/apps/host/src/lib/features.ts @@ -1 +1,2 @@ -export const features = { toolAccess: false, thinkingLevels: false, sessionLog: true, demosInComposer: false } as const; +/** Image generation is hidden everywhere in the interface for this version (round 8, item 8). The pieces stay in the code; flip this to bring them back. */ +export const IMAGE_GENERATION_VISIBLE = false; diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 521c68f7..1dda3498 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -6,10 +6,12 @@ export interface NativeFamily {family:string;title:string;about:string;experimen export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean} export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record|null;progress?:Record|null} export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;resourceProfile?:'work'|'performance'|null;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record|null} -export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} +export interface NativeState {available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} let state:NativeState|null=null,timer:ReturnType|null=null,reading:Promise|null=null; const listeners=new Set<()=>void>(); -export function refreshNative(force=false){if(reading)return reading;reading=api.get(`/api/native${force?'?refresh=1':''}`).then(value=>{state=value;listeners.forEach(fn=>fn());}).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{reading=null;});return reading;} +let again=false; +/** A forced refresh (after an action) never joins a read that began before the action: that read cannot know about the new job. It waits for it, then reads again. */ +export function refreshNative(force=false):Promise{if(reading){if(!force)return reading;if(again)return reading;again=true;return reading.then(()=>{again=false;return refreshNative(true);});}reading=api.get(`/api/native${force?'?refresh=1':''}`).then(value=>{if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());}).catch(error=>{if(state){state={...state,error:error.message,instances:state.instances.map(i=>({...i,metrics:null,phase:'unavailable'}))};listeners.forEach(fn=>fn());}}).finally(()=>{reading=null;});return reading;} export function useNative(){const value=useSyncExternalStore(fn=>{listeners.add(fn);return()=>listeners.delete(fn);},()=>state);useEffect(()=>{void refreshNative();if(!timer)timer=setInterval(()=>void refreshNative(),2500);return()=>{if(!listeners.size&&timer){clearInterval(timer);timer=null;}};},[]);return value;} export const nativeState=()=>state; /** Connection-list projection only; memory reservations are not inferred. */ @@ -17,6 +19,10 @@ export function nativeRouting(native:NativeState|null,hardware:Hardware|null):Ru if(!native?.instances.length)return null; return {revision:Date.now(),mode:'real',capabilities:{multipleModels:true,deviceAssignment:true},defaultId:native.defaultId,instances:native.instances.filter(i=>i.status==='ready').map(i=>({id:i.id,apiModelId:i.apiModelId,variantId:i.model,family:i.label,name:i.model,quant:i.model,loadedAt:i.loadedAt,status:'ready',phase:i.phase as RuntimeModels['instances'][number]['phase'],active:i.metrics?.live?.running??0,queued:i.metrics?.live?.queued??0,prompt:{done:0,total:0,pct:0},outputTps:i.metrics?.live?.tok_s??0,promptTps:i.metrics?.live?.prefill_tok_s_mean??0,context:{usedTokens:0,maxTokens:i.metrics?.engine?.max_context??i.context??0,pct:0},gpuIds:i.gpus.map(index=>{const g=hardware?.gpus.find(g=>g.index===index);return g?.id??`${g?.vendor??'native'}:${index}`;}),memory:{context:i.metrics?.engine?.max_context??i.context??0,ramGb:0,gpuGb:0,spillGb:0,reserveGb:0,totalGb:0,devices:[]}})),memory:{ramGb:0,budgetGb:0,reserveGb:0,totalGb:0,fits:true,devices:[]}}; } -export async function nativeAction(path:string,body:unknown={}){const result=await api.post(`/api/native/${path}`,body);await refreshNative(true);return result;} +export async function nativeAction(path:string,body:unknown={}){const result=await api.post(`/api/native/${path}`,body); + // A started operation is a job: show it at once instead of waiting for the next read (the owner saw download progress only after switching tabs). + const job=result as unknown as NativeJob|undefined; + if(state&&job&&typeof job.id==='string'&&path==='operations'&&!state.jobs.some(j=>j.id===job.id)){state={...state,jobs:[...state.jobs,job]};listeners.forEach(fn=>fn());} + await refreshNative(true);return result;} export {nativeVersionLabel} from './native-catalog'; diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.ts index afec584a..e98afd8c 100644 --- a/apps/host/src/lib/store.ts +++ b/apps/host/src/lib/store.ts @@ -4,12 +4,13 @@ import { updateAgent } from './agents'; import { LOOP_MAX_RUNS, LOOP_USAGE, loopEvery, parseLoop, type LoopCommand } from './loop'; import { applyStatusFrame, clearStatus } from './live-status'; import { applyGoalFrame } from './goal'; +import { appendText, mergeDeliverable, readDeliverable, readGroup, upsertGroup } from './deliverables'; import { applyPlanFrame, applyQueueFrame, planApprove, queueMessage } from './plan'; -import { TIME_SKIP_DURATION, timeSkipPrompt, timeSkipTabId, withTimeSkipResult, type TimeSkipFile, type TimeSkipJob, type TimeSkipRun, type TimeSkipVersion } from './time-skip'; +import { forkFields, isForkJob, 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 { photoData, uploadChatPhotos, photoHistorySlots, pendingChatPhotos, takeChatPhotos } from './chat-photos'; import { nativeState } from './native'; import { setTranslationLanguage, tr, validLanguage, type Language } from './i18n'; /** @@ -324,6 +325,14 @@ function libraryResponse(data: ModelLibrary): ModelLibrary { export function lifecycleStatus(s = state) { return lifecyclePolicy({ connected: s.connection === 'live', streaming: !!s.streaming || s.liveChats > 0, stats: s.serving?.stats, busy: s.busy }); } +/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */ +export function useLifecycle() { + const connected = useStore(s => s.connection === 'live'); + const streaming = useStore(s => !!s.streaming || s.liveChats > 0); + const stats = useStore(s => s.serving?.stats); + const busy = useStore(s => s.busy); + return lifecyclePolicy({ connected, streaming, stats, busy }); +} export function lifecycleAvailable(): boolean { const result = lifecycleStatus(); if (!result.allowed) pushToast('warn', 'Model change unavailable', result.reason); @@ -1171,7 +1180,7 @@ function applyTimeSkipEvent(data: Record) { for (const session of state.sessions) { const run = session.timeSkips?.find(r => r.job?.id === id); if (!run || run.completedAt) continue; - patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'] } })); + patchRun(session.id, run.id, r => ({ ...r, job: { ...r.job!, ...(typeof data.phase === 'string' ? { phase: data.phase as TimeSkipJob['phase'] } : {}), activity: data.activity as TimeSkipJob['activity'], ...forkFields(data) } })); } } @@ -1179,7 +1188,7 @@ 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(); + return isForkJob(job) ? tr('Both versions are ready. Compare A and B, then keep one.') : TS_READY(); } async function startTimeSkipReal(prompt: string) { @@ -1234,14 +1243,14 @@ export async function followTimeSkip(sessionId: string, runId: string) { break; } catch { await new Promise(r => setTimeout(r, 700 * (tryNo + 1))); } } - const finished = job; + const finished = { ...job, ...forkFields(job as unknown as Record) }; patchRun(sessionId, runId, r => ({ ...r, completedAt: Date.now(), job: { ...r.job!, ...finished, ...extra } }), timeSkipEnding(finished, files)); // A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab. if (files.length > 0 && !['failed', 'cancelled', 'interrupted'].includes(finished.phase)) 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 (job) { const live = { ...job, ...forkFields(job as unknown as Record) }; 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); @@ -1263,9 +1272,10 @@ export async function keepTimeSkip(sessionId: string, runId: string, version: Ti 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; } + if ((run.retainedVersion ?? 'original') === version && !(isForkJob(job) && run.retainedVersion === undefined)) { 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 }); + if (isForkJob(job)) await api.post('/api/timeskip/apply', { id: job.id, which: version === 'original' ? 'a' : 'b' }); + else 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')); @@ -1509,7 +1519,8 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g if (loopCommand) { await runLoopCommand(loopCommand); return; } const demoPrompt = resume || planStart ? null : timeSkipPrompt(text.trim()); if (demoPrompt !== null) { - if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else startTimeSkipDemo(demoPrompt); + if (demoPrompt && (state.remoteModel || nativeState()?.instances.some(i => i.status === 'ready'))) void startTimeSkipReal(demoPrompt); else if (state.connection === 'live' && demoPrompt) pushToast('info', 'Load a model first', 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.'); + else startTimeSkipDemo(demoPrompt); return; } const imageTarget=nativeState()?.instances.find(i=>i.id===nativeState()?.defaultId);const canSendPictures=!state.remoteModel&&imageTarget?.status==='ready'&&imageTarget.vision; @@ -1584,7 +1595,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g model: state.library?.loaded ?? state.library?.current ?? null, remoteModel: state.remoteModel, nativeModelId:nativeState()?.instances.length?nativeState()?.defaultId:undefined, - images:await Promise.all(pictures.map(photoData)), + ...(pictures.length ? { imageIds: await uploadChatPhotos(pictures, sessionId) } : {}), useTools:state.sessions.find(s=>s.id===sessionId)?.preferences?.useTools===true, // A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly. ...(state.sessions.find(s=>s.id===sessionId)?.preferences?.agent===false?{agent:false}:{}), @@ -1642,7 +1653,13 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g } else if (type === 'agent') { patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) })); } else if (type === 'delta') { - patchAssistant((m) => { const content=m.content+String(frame.text??''); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); + patchAssistant((m) => { const content=m.content+String(frame.text??''); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,String(frame.text??''))}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; }); + } else if (type === 'deliverable') { + const file = readDeliverable(frame); + if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) })); + } else if (type === 'activity-group') { + const group = readGroup(frame); + if (group) patchAssistant(m => ({ ...m, blocks: upsertGroup(m.blocks ?? (m.content ? appendText(undefined, m.content) : undefined), group) })); } else if (type === 'artifacts' && Array.isArray(frame.artifacts)) { patchAssistant(m => ({ ...m, artifacts: frame.artifacts as PreviewArtifact[] })); } else if(type==='native-tool'){ diff --git a/apps/host/src/lib/time-skip-activity.ts b/apps/host/src/lib/time-skip-activity.ts index 19c4e1fa..1bec06cd 100644 --- a/apps/host/src/lib/time-skip-activity.ts +++ b/apps/host/src/lib/time-skip-activity.ts @@ -4,6 +4,7 @@ import type { TimeSkipJob } from './time-skip'; /** What the working view says it is doing: the host's own words (activity.code / text / args.step, notes-split-agent3.md), else from the phase. */ export function activityWords(job: Pick | undefined): string { const a = job?.activity; + if (a?.code === 'line' && a.text) return a.text; if (a?.code === 'trying-version') { const step = typeof a.args?.step === 'string' && a.args.step ? String(a.args.step) : ''; return step || tr('Trying an improved version…'); diff --git a/apps/host/src/lib/time-skip.ts b/apps/host/src/lib/time-skip.ts index ffdba6c5..48d328a8 100644 --- a/apps/host/src/lib/time-skip.ts +++ b/apps/host/src/lib/time-skip.ts @@ -22,7 +22,7 @@ export interface TimeSkipRun { /** What the App Host reports about a real run. Field names mirror the job's durable record. */ export interface TimeSkipJob { id: string; - phase: 'queued' | 'checkpointing' | 'generating' | 'checking' | 'decision' | 'completed' + phase: 'planning' | 'choosing' | 'running' | 'comparing' | 'queued' | 'checkpointing' | 'generating' | 'checking' | 'decision' | 'completed' | 'cancelled' | 'failed' | 'interrupted' | 'needs_user_review'; attempts: { index: number; decision: string | null; reason: string; checks: { id: string; outcome: string; kind: string }[] }[]; @@ -36,6 +36,11 @@ export interface TimeSkipJob { activity?: { code: string; text: string; args?: Record } | null; error: string | null; finishedAt?: number | null; + /** The fork design (notes-split-agent8.md, item 11): the plan, the one step where checking matters most, and the two agents' progress. */ + plan?: { steps: { id: string; text: string }[] } | null; + lever?: ForkLever | null; + a?: ForkLane | null; + b?: ForkLane | 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. */ @@ -44,6 +49,36 @@ export interface TimeSkipJob { applyAttempt?: number | null; } +export interface ForkLever { step: number; total: number; text: string; why: string; defaulted: boolean } +export interface ForkLane { state: string; step: number; total: number; text: string; line: string; waiting: boolean } + +const lane = (raw: unknown): ForkLane | null => { + if (!raw || typeof raw !== 'object') return null; + const l = raw as Record; + return { state: typeof l.state === 'string' ? l.state : 'waiting', step: Number(l.step) || 0, total: Number(l.total) || 0, text: typeof l.text === 'string' ? l.text : '', line: typeof l.line === 'string' ? l.line : '', waiting: l.waiting === true }; +}; + +/** + * What an event or a status answer adds to a job under the fork design: the plan, the lever with its why, both lanes, and the activity as one + * friendly line (a string there; the older host sends an object, which is left as it is). + */ +export function forkFields(data: Record): Partial { + const out: Partial = {}; + const plan = data.plan as { steps?: unknown } | null | undefined; + if (plan && Array.isArray(plan.steps)) out.plan = { steps: plan.steps.flatMap((s, i) => (s && typeof s === 'object' && typeof (s as { text?: unknown }).text === 'string' ? [{ id: String((s as { id?: unknown }).id ?? i + 1), text: (s as { text: string }).text }] : [])) }; + const lv = data.lever as Record | null | undefined; + if (lv && typeof lv === 'object' && Number(lv.step) > 0) out.lever = { step: Number(lv.step), total: Number(lv.total) || 0, text: typeof lv.text === 'string' ? lv.text : '', why: typeof lv.why === 'string' ? lv.why : '', defaulted: lv.defaulted === true }; + else if (lv === null) out.lever = null; + if ('a' in data) out.a = lane(data.a); + if ('b' in data) out.b = lane(data.b); + if (typeof data.activity === 'string' && data.activity) out.activity = { code: 'line', text: data.activity }; + else if (data.activity && typeof data.activity === 'object') out.activity = data.activity as TimeSkipJob['activity']; + return out; +} + +/** A job that runs as two agents (A, and B forked at the lever step) rather than one revision. */ +export const isForkJob = (job: Pick | undefined | null): boolean => !!job && !!(job.plan || job.lever || job.a || job.b); + export interface TimeSkipFile { path: string; status: 'added' | 'changed' | 'removed'; diff --git a/apps/host/src/lib/types.ts b/apps/host/src/lib/types.ts index 67ff69d2..bfc8613a 100644 --- a/apps/host/src/lib/types.ts +++ b/apps/host/src/lib/types.ts @@ -320,6 +320,10 @@ export interface ChatMessage { timeSkipId?: string; /** The plan this reply proposed: shown as the plan card in place of the reply text. */ planId?: string; + /** The reply in the order it came: text and grouped activity lines (round 8, item 12). Absent on older replies. */ + blocks?: import('./deliverables').MessageBlock[]; + /** Files the assistant made or changed in this reply, one card each. */ + deliverables?: import('./deliverables').Deliverable[]; /** A line from the app itself (for example from /loop), never sent to the model. */ local?: boolean; ttftMs?: number; diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 1c832e9b..492a85e2 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3087,9 +3087,39 @@ "s3091": "übersprungen", "s3092": "Pausiert · {0} von {1} erledigt", "s3093": "Plan genehmigt.", - "s3094": "Der Assistent antwortet noch", - "s3095": "Senden Sie Ihre Nachricht, wenn er fertig ist.", - "s3096": "Die Nachricht wurde nicht eingereiht", - "s3097": "In der Warteschlange — wird danach gesendet", - "s3098": "In der Warteschlange — wird gesendet, wenn das Ziel erreicht ist" + "s3094": "Experimentell", + "s3095": "Weitere Möglichkeiten, {0} zu öffnen", + "s3096": "Dateiaktionen", + "s3097": "Im Ordner anzeigen", + "s3098": "Pfad kopieren", + "s3099": "Als Kontext anhängen", + "s3100": "Pfad kopiert", + "s3101": "An Ihre nächste Nachricht angehängt", + "s3102": "Die Datei wurde nicht geöffnet", + "s3103": "Für diese Datei gibt es keine Vorschau", + "s3104": "Der Ordner wurde nicht geöffnet", + "s3105": "Der Pfad wurde nicht kopiert", + "s3106": "Die Datei wurde nicht angehängt", + "s3107": "Ordner auswählen", + "s3108": "Den Ordner wählen, in dem dieser Chat arbeitet", + "s3109": "Projektordner: {0}. Ändern.", + "s3110": "Standardordner verwenden", + "s3111": "Der Ordner wurde nicht geändert", + "s3112": "Der Plan", + "s3113": "Hier zu prüfen ist am wichtigsten", + "s3114": "standardmäßig gewählt", + "s3115": "Das ist eine kurze Aufgabe, daher gibt es eine Version. Eine Verzweigung lohnt sich nicht.", + "s3116": "Schritt {0} von {1}: {2}", + "s3117": "Startet, wenn A Schritt {0} erreicht", + "s3118": "Wartet auf den Start", + "s3119": "Wartet auf den Plan", + "s3120": "Fortschritt von {0}", + "s3121": "Eine Version behalten", + "s3122": "Version A ist in Ihren Dateien.", + "s3123": "Version B ist in Ihren Dateien.", + "s3124": "Für das Lesen von Bildern fehlen noch einige Dateien auf diesem Computer.", + "s3125": "Dateien zum Lesen von Bildern herunterladen", + "s3126": "Zwei Versionen zum Vergleichen", + "s3127": "A und B sind jeweils vollständig durchgelaufen. Behalten Sie die, die Ihnen gefällt.", + "s3128": "Time-skip funktioniert mit einem geladenen Modell. Wählen Sie eines im Tab „Modelle“ und versuchen Sie es erneut." } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 2cec82a5..427ffa5e 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3087,9 +3087,39 @@ "s3091": "skipped", "s3092": "Paused · {0} of {1} done", "s3093": "Approved the plan.", - "s3094": "The assistant is still answering", - "s3095": "Send your message when it has finished.", - "s3096": "The message was not queued", - "s3097": "Queued — sends after that", - "s3098": "Queued — sends when the goal finishes" + "s3094": "Experimental", + "s3095": "More ways to open {0}", + "s3096": "File actions", + "s3097": "Show in folder", + "s3098": "Copy path", + "s3099": "Attach as context", + "s3100": "Path copied", + "s3101": "Attached to your next message", + "s3102": "The file was not opened", + "s3103": "The file has no preview", + "s3104": "The folder was not opened", + "s3105": "The path was not copied", + "s3106": "The file was not attached", + "s3107": "Select a folder", + "s3108": "Choose the folder this chat works in", + "s3109": "Project folder: {0}. Change it.", + "s3110": "Use the default folder", + "s3111": "The folder was not changed", + "s3112": "The plan", + "s3113": "Checking here matters most", + "s3114": "chosen by default", + "s3115": "This is a short job, so there is one version. Nothing is worth branching.", + "s3116": "Step {0} of {1}: {2}", + "s3117": "Starts when A reaches step {0}", + "s3118": "Waiting to start", + "s3119": "Waiting for the plan", + "s3120": "Progress of {0}", + "s3121": "Keep a version", + "s3122": "Version A is in your files.", + "s3123": "Version B is in your files.", + "s3124": "Picture reading needs a few more files that are not on this computer yet.", + "s3125": "Download picture-reading files", + "s3126": "Two versions to compare", + "s3127": "A and B each went all the way through. Keep the one you like.", + "s3128": "Time-skip works on a loaded model. Choose one on the Models tab, then try again." } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index c9395412..0e5d2316 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3087,9 +3087,39 @@ "s3091": "omitido", "s3092": "En pausa · {0} de {1} hechos", "s3093": "Plan aprobado.", - "s3094": "El asistente aún está respondiendo", - "s3095": "Envía tu mensaje cuando haya terminado.", - "s3096": "No se pudo poner el mensaje en cola", - "s3097": "En cola — se envía después", - "s3098": "En cola — se envía cuando termine el objetivo" + "s3094": "Experimental", + "s3095": "Más formas de abrir {0}", + "s3096": "Acciones del archivo", + "s3097": "Mostrar en la carpeta", + "s3098": "Copiar la ruta", + "s3099": "Adjuntar como contexto", + "s3100": "Ruta copiada", + "s3101": "Adjunto a tu próximo mensaje", + "s3102": "No se abrió el archivo", + "s3103": "Este archivo no tiene vista previa", + "s3104": "No se abrió la carpeta", + "s3105": "No se copió la ruta", + "s3106": "No se adjuntó el archivo", + "s3107": "Elegir una carpeta", + "s3108": "Elige la carpeta en la que trabaja este chat", + "s3109": "Carpeta del proyecto: {0}. Cámbiala.", + "s3110": "Usar la carpeta predeterminada", + "s3111": "No se cambió la carpeta", + "s3112": "El plan", + "s3113": "Revisar aquí es lo más importante", + "s3114": "elegido por defecto", + "s3115": "Es una tarea corta, así que hay una sola versión. No merece la pena bifurcar.", + "s3116": "Paso {0} de {1}: {2}", + "s3117": "Empieza cuando A llegue al paso {0}", + "s3118": "Esperando para empezar", + "s3119": "Esperando el plan", + "s3120": "Progreso de {0}", + "s3121": "Conservar una versión", + "s3122": "La versión A está en tus archivos.", + "s3123": "La versión B está en tus archivos.", + "s3124": "Para leer imágenes faltan algunos archivos que aún no están en este equipo.", + "s3125": "Descargar los archivos para leer imágenes", + "s3126": "Dos versiones para comparar", + "s3127": "A y B llegaron hasta el final. Conserva la que prefieras.", + "s3128": "Time-skip funciona con un modelo cargado. Elige uno en la pestaña Modelos y vuelve a intentarlo." } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index fbb2cda3..d7bc1349 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3087,9 +3087,39 @@ "s3091": "スキップ", "s3092": "一時停止中 · {1} 件中 {0} 件完了", "s3093": "プランを承認しました。", - "s3094": "アシスタントはまだ回答中です", - "s3095": "完了してからメッセージを送ってください。", - "s3096": "メッセージを待機に入れられませんでした", - "s3097": "待機中 — その後に送信", - "s3098": "待機中 — ゴールの完了後に送信" + "s3094": "試験的", + "s3095": "{0} を開くその他の方法", + "s3096": "ファイル操作", + "s3097": "フォルダーで表示", + "s3098": "パスをコピー", + "s3099": "コンテキストとして添付", + "s3100": "パスをコピーしました", + "s3101": "次のメッセージに添付しました", + "s3102": "ファイルを開けませんでした", + "s3103": "このファイルはプレビューできません", + "s3104": "フォルダーを開けませんでした", + "s3105": "パスをコピーできませんでした", + "s3106": "ファイルを添付できませんでした", + "s3107": "フォルダーを選択", + "s3108": "このチャットで作業するフォルダーを選択", + "s3109": "プロジェクトフォルダー:{0}。変更します。", + "s3110": "既定のフォルダーを使う", + "s3111": "フォルダーは変更されませんでした", + "s3112": "プラン", + "s3113": "ここでの確認が最も重要です", + "s3114": "既定で選択", + "s3115": "短い作業なので、バージョンは1つです。分岐する価値はありません。", + "s3116": "ステップ {0}/{1}:{2}", + "s3117": "A がステップ {0} に達したら開始", + "s3118": "開始待ち", + "s3119": "プランを待っています", + "s3120": "{0} の進捗", + "s3121": "バージョンを残す", + "s3122": "バージョン A がファイルに反映されています。", + "s3123": "バージョン B がファイルに反映されています。", + "s3124": "画像の読み取りには、このコンピューターにまだない追加ファイルが必要です。", + "s3125": "画像読み取り用ファイルをダウンロード", + "s3126": "比べる 2 つのバージョン", + "s3127": "A も B も最後まで完了しました。気に入った方を残してください。", + "s3128": "Time-skip は読み込み済みのモデルで動作します。モデルタブで選んでから、もう一度お試しください。" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index e8f77bd1..612df529 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3087,9 +3087,39 @@ "s3091": "건너뜀", "s3092": "일시 중지 · {1}개 중 {0}개 완료", "s3093": "계획을 승인했습니다.", - "s3094": "어시스턴트가 아직 답하는 중입니다", - "s3095": "끝난 뒤에 메시지를 보내 주세요.", - "s3096": "메시지를 대기열에 넣지 못했습니다", - "s3097": "대기 중 — 그 다음에 전송됩니다", - "s3098": "대기 중 — 목표가 끝나면 전송됩니다" + "s3094": "실험적", + "s3095": "{0}을(를) 여는 다른 방법", + "s3096": "파일 작업", + "s3097": "폴더에서 보기", + "s3098": "경로 복사", + "s3099": "컨텍스트로 첨부", + "s3100": "경로를 복사했습니다", + "s3101": "다음 메시지에 첨부했습니다", + "s3102": "파일을 열지 못했습니다", + "s3103": "이 파일은 미리 볼 수 없습니다", + "s3104": "폴더를 열지 못했습니다", + "s3105": "경로를 복사하지 못했습니다", + "s3106": "파일을 첨부하지 못했습니다", + "s3107": "폴더 선택", + "s3108": "이 대화가 작업할 폴더를 선택하세요", + "s3109": "프로젝트 폴더: {0}. 변경합니다.", + "s3110": "기본 폴더 사용", + "s3111": "폴더가 변경되지 않았습니다", + "s3112": "계획", + "s3113": "여기서 확인하는 것이 가장 중요합니다", + "s3114": "기본값으로 선택됨", + "s3115": "짧은 작업이라 버전은 하나입니다. 나눌 필요가 없습니다.", + "s3116": "{1}단계 중 {0}단계: {2}", + "s3117": "A가 {0}단계에 도달하면 시작합니다", + "s3118": "시작 대기 중", + "s3119": "계획을 기다리는 중", + "s3120": "{0}의 진행 상황", + "s3121": "버전 유지", + "s3122": "버전 A가 파일에 적용되었습니다.", + "s3123": "버전 B가 파일에 적용되었습니다.", + "s3124": "사진 읽기에는 아직 이 컴퓨터에 없는 파일이 더 필요합니다.", + "s3125": "사진 읽기 파일 다운로드", + "s3126": "비교할 두 버전", + "s3127": "A와 B 모두 끝까지 진행되었습니다. 마음에 드는 쪽을 유지하세요.", + "s3128": "Time-skip은 불러온 모델에서 작동합니다. 모델 탭에서 하나를 고른 뒤 다시 시도하세요." } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index 5de3161a..9da63764 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3087,9 +3087,39 @@ "s3091": "ignorado", "s3092": "Pausado · {0} de {1} concluídos", "s3093": "Plano aprovado.", - "s3094": "O assistente ainda está respondendo", - "s3095": "Envie sua mensagem quando ele terminar.", - "s3096": "A mensagem não foi colocada na fila", - "s3097": "Na fila — enviada depois disso", - "s3098": "Na fila — enviada quando a meta terminar" + "s3094": "Experimental", + "s3095": "Mais formas de abrir {0}", + "s3096": "Ações do arquivo", + "s3097": "Mostrar na pasta", + "s3098": "Copiar o caminho", + "s3099": "Anexar como contexto", + "s3100": "Caminho copiado", + "s3101": "Anexado à sua próxima mensagem", + "s3102": "O arquivo não foi aberto", + "s3103": "Este arquivo não tem pré-visualização", + "s3104": "A pasta não foi aberta", + "s3105": "O caminho não foi copiado", + "s3106": "O arquivo não foi anexado", + "s3107": "Escolher uma pasta", + "s3108": "Escolha a pasta em que este chat trabalha", + "s3109": "Pasta do projeto: {0}. Alterar.", + "s3110": "Usar a pasta padrão", + "s3111": "A pasta não foi alterada", + "s3112": "O plano", + "s3113": "Verificar aqui é o mais importante", + "s3114": "escolhido por padrão", + "s3115": "É uma tarefa curta, então há uma só versão. Não vale a pena ramificar.", + "s3116": "Passo {0} de {1}: {2}", + "s3117": "Começa quando A chegar ao passo {0}", + "s3118": "Aguardando para começar", + "s3119": "Aguardando o plano", + "s3120": "Progresso de {0}", + "s3121": "Manter uma versão", + "s3122": "A versão A está nos seus arquivos.", + "s3123": "A versão B está nos seus arquivos.", + "s3124": "A leitura de imagens precisa de alguns arquivos que ainda não estão neste computador.", + "s3125": "Baixar os arquivos de leitura de imagens", + "s3126": "Duas versões para comparar", + "s3127": "A e B foram até o fim. Mantenha a que preferir.", + "s3128": "O Time-skip funciona com um modelo carregado. Escolha um na aba Modelos e tente de novo." } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index 3b189491..8f0dc27c 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3087,9 +3087,39 @@ "s3091": "пропущено", "s3092": "Пауза · готово {0} из {1}", "s3093": "План одобрен.", - "s3094": "Ассистент ещё отвечает", - "s3095": "Отправьте сообщение, когда он закончит.", - "s3096": "Сообщение не удалось поставить в очередь", - "s3097": "В очереди — отправится после этого", - "s3098": "В очереди — отправится, когда цель будет достигнута" + "s3094": "Экспериментально", + "s3095": "Другие способы открыть {0}", + "s3096": "Действия с файлом", + "s3097": "Показать в папке", + "s3098": "Копировать путь", + "s3099": "Прикрепить как контекст", + "s3100": "Путь скопирован", + "s3101": "Прикреплено к вашему следующему сообщению", + "s3102": "Файл не удалось открыть", + "s3103": "У этого файла нет предпросмотра", + "s3104": "Папку не удалось открыть", + "s3105": "Путь не удалось скопировать", + "s3106": "Файл не удалось прикрепить", + "s3107": "Выбрать папку", + "s3108": "Выберите папку, в которой работает этот чат", + "s3109": "Папка проекта: {0}. Изменить.", + "s3110": "Использовать папку по умолчанию", + "s3111": "Папка не была изменена", + "s3112": "План", + "s3113": "Проверка здесь важнее всего", + "s3114": "выбрано по умолчанию", + "s3115": "Это короткая задача, поэтому версия одна. Ветвление не нужно.", + "s3116": "Шаг {0} из {1}: {2}", + "s3117": "Начнётся, когда A дойдёт до шага {0}", + "s3118": "Ожидает запуска", + "s3119": "Ожидает план", + "s3120": "Прогресс {0}", + "s3121": "Оставить версию", + "s3122": "Версия A в ваших файлах.", + "s3123": "Версия B в ваших файлах.", + "s3124": "Для чтения изображений нужны дополнительные файлы, которых на этом компьютере ещё нет.", + "s3125": "Скачать файлы для чтения изображений", + "s3126": "Две версии для сравнения", + "s3127": "И A, и B дошли до конца. Оставьте ту, что нравится.", + "s3128": "Time-skip работает с загруженной моделью. Выберите её на вкладке «Модели» и повторите." } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 795518a1..dee0246e 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3087,9 +3087,39 @@ "s3091": "已跳过", "s3092": "已暂停 · 已完成 {0}/{1}", "s3093": "已批准计划。", - "s3094": "助手仍在回答", - "s3095": "等它完成后再发送你的消息。", - "s3096": "消息未能排队", - "s3097": "已排队 — 在此之后发送", - "s3098": "已排队 — 目标完成后发送" + "s3094": "实验性", + "s3095": "打开 {0} 的更多方式", + "s3096": "文件操作", + "s3097": "在文件夹中显示", + "s3098": "复制路径", + "s3099": "作为上下文附加", + "s3100": "路径已复制", + "s3101": "已附加到你的下一条消息", + "s3102": "文件未能打开", + "s3103": "此文件无法预览", + "s3104": "文件夹未能打开", + "s3105": "路径未能复制", + "s3106": "文件未能附加", + "s3107": "选择文件夹", + "s3108": "选择此对话使用的文件夹", + "s3109": "项目文件夹:{0}。点击更改。", + "s3110": "使用默认文件夹", + "s3111": "文件夹未更改", + "s3112": "计划", + "s3113": "在此处检查最关键", + "s3114": "默认选择", + "s3115": "这是一个很短的任务,所以只有一个版本,无需分支。", + "s3116": "第 {0}/{1} 步:{2}", + "s3117": "A 到达第 {0} 步时开始", + "s3118": "等待开始", + "s3119": "等待计划", + "s3120": "{0} 的进度", + "s3121": "保留一个版本", + "s3122": "版本 A 已在你的文件中。", + "s3123": "版本 B 已在你的文件中。", + "s3124": "读取图片还需要一些此电脑上尚没有的文件。", + "s3125": "下载图片读取文件", + "s3126": "两个版本待比较", + "s3127": "A 和 B 都已完整完成。保留你喜欢的那个。", + "s3128": "Time-skip 需要已加载的模型。请在“模型”标签页选择一个,然后重试。" } diff --git a/apps/host/src/screens/Chat.tsx b/apps/host/src/screens/Chat.tsx index 1b898ef3..f23cf305 100644 --- a/apps/host/src/screens/Chat.tsx +++ b/apps/host/src/screens/Chat.tsx @@ -21,6 +21,9 @@ import { ReasoningBlock } from '../components/ReasoningBlock'; import { StatusLine } from '../components/StatusLine'; import { GoalBar } from '../components/GoalBar'; import { PlanCard, PlanPanel, QueuedMessages } from '../components/PlanCard'; +import { FolderChip } from '../components/FolderChip'; +import { DropZone } from '../components/DropZone'; +import { ActivityLine, EditedFiles, FileCard } from '../components/Deliverables'; import { queueMessage, usePlan, usePlanQuiet } from '../lib/plan'; import { plainFailureText } from '../lib/plain-errors'; import { useLiveStatus } from '../lib/live-status'; @@ -116,6 +119,8 @@ export function ChatScreen() { const planShown = planTab.length > 0 && selectedPreview === planTabId; const planRunId = plan?.state === 'running' ? plan.id : ''; useEffect(() => { if (planRunId && planTabId && !session?.closedPreviews?.includes(planTabId)) setSelectedPreview(planTabId); }, [planRunId]); + // The chat shows every run of this chat (a running one has no files yet, so no tab); the sidebar tabs only those with something to compare. + const allTimeSkipRuns = session?.timeSkips ?? []; const extraTabs = [...runTabs, ...planTab]; const selectedRun = timeSkipRuns.find(run => timeSkipTabId(run.id) === selectedPreview); const inlinePreview = splitWidth >= (selectedRun || planShown ? 760 : 1120); @@ -358,7 +363,7 @@ export function ChatScreen() { return (<> { setSelectedPreview(null); setExpanded(false); }} inline={inlinePreview} expanded={expanded} onExpand={() => setExpanded(v => !v)}/>
-
+
{tr(awayFromBottom ? () : null)} @@ -367,7 +372,7 @@ export function ChatScreen() {
-
+ setSelectedPreview(null)} inline={inlinePreview}/> {tr(resizeHandle)}
@@ -380,7 +385,7 @@ export function ChatScreen() { the context panel open, a full-width composer sat underneath the panel and drifted out of alignment with the transcript it belongs to. */}
-
+
{ const el = e.currentTarget; if (session) @@ -396,14 +401,14 @@ export function ChatScreen() {
{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} timeSkipReal={!!timeSkipRuns.find(r => r.id === m.timeSkipId)?.job} timeSkipRun={timeSkipRuns.find(r => r.id === m.timeSkipId)} onOpenLink={openLink}/>))))} + ) : (session.messages.map((m, i) => ( r.id === m.timeSkipId)?.completedAt} timeSkipReal={!!allTimeSkipRuns.find(r => r.id === m.timeSkipId)?.job} timeSkipRun={allTimeSkipRuns.find(r => r.id === m.timeSkipId)} onOpenLink={openLink}/>))))}
{tr(awayFromBottom ? () : null)}
-
+ {tr(!setupVisible && selectedRun && session ? { setSelectedPreview(null); setExpanded(false); }}/> : null)} {tr(!setupVisible && planShown ? : null)} setSelectedPreview(null)} inline={inlinePreview}/> @@ -496,6 +501,7 @@ function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session
{tr(fileError ? setFileError('')}/> : null)} +
{tr(photos.length ? removeChatPhoto(id, session?.id)}/> : null)} @@ -571,6 +577,8 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp // A reply that proposed a plan shows the plan card in place of its closing text (which is the plan in prose). const storedPlan = usePlanQuiet(m.planId ? activeSession : null); const planCard = !!m.planId && storedPlan?.id === m.planId; + // A reply with activity lines is drawn piece by piece in the order it came; one without is the plain text it always was. + const grouped = !!m.blocks?.some(b => b.kind === 'group'); const [sentTime, setSentTime] = useState(() => relTime(m.at)); if (m.role === 'user') { return (
setSentTime(relTime(m.at))} onFocus={() => setSentTime(relTime(m.at))}> @@ -593,18 +601,20 @@ function Message({ message: m, isLast, onEditPrompt, onPreview, onOpenLink, onOp {tr(m.reasoning ? : null)} - {tr((m.tools ?? []).map((t) => ()))} + {tr((m.tools ?? []).filter(t => !grouped || t.state !== 'done').map((t) => ()))} {tr(!(m.timeSkipId && timeSkipReal && !timeSkipDone) && (m.content || m.error || !m.streaming || !liveStatus) ?
{tr(planCard ? : null)} {tr(m.error ? () : null)} - {tr(m.content && !planCard ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? ( + {tr(grouped && !planCard && !m.timeSkipId ? m.blocks!.map((b, i) => b.kind === 'group' ? : onPreview({ id: m.id + '-html-' + i, kind: 'website', title: 'HTML preview', content })}/>) : null)} + {tr(m.content && !planCard && !grouped ? ( onPreview({ id: m.id + '-html', kind: 'website', title: 'HTML preview', content })}/>) : !m.error && m.streaming && !liveStatus ? ( ) : null)} {tr(m.streaming && m.content ?
: null)} + {tr(m.deliverables?.length && !m.streaming ?
{m.deliverables.map(f => )}
: null)} {tr(m.streaming && isLast && !m.timeSkipId ? : null)} {tr(m.timeSkipId && timeSkipReal && !timeSkipDone && timeSkipRun ? : m.timeSkipId && (!timeSkipReal || (timeSkipRun?.job?.files?.length ?? 0) > 0) ? : null)} diff --git a/apps/host/src/screens/ModelRun.tsx b/apps/host/src/screens/ModelRun.tsx index 904196ec..16ec83e9 100644 --- a/apps/host/src/screens/ModelRun.tsx +++ b/apps/host/src/screens/ModelRun.tsx @@ -10,6 +10,7 @@ import { RunningModels } from '../components/RunningModels'; import { LocalModelImport } from '../components/LocalModelImport'; import { gpuId } from '../lib/monitor-hardware'; import { RunImageModel } from '../components/RunImageModel'; +import { IMAGE_GENERATION_VISIBLE } from '../lib/features'; import { FloatingMenu } from '../components/FloatingMenu'; import { ModelsScreen } from './Models'; import { configDocument, configPatch, readConfig, type ConfigDocument } from '../lib/config'; @@ -19,7 +20,7 @@ import { computerIdentity, configIdentity, defaultProfileKey, emptyProfiles, rea import { modelFamilyIcon } from '../lib/model-icons'; import { familyVersion, modelFamilies } from '../lib/model-versions'; import { sizeGb } from '../lib/format'; -import { applyImageModel, getState, lifecycleStatus, loadRuntimeModel, loadVariant, pushToast, restartEngine, saveEngine, selectImageModel, setConfigDraft, useStore, validateEngine } from '../lib/store'; +import { applyImageModel, getState, useLifecycle, loadRuntimeModel, loadVariant, pushToast, restartEngine, saveEngine, selectImageModel, setConfigDraft, useStore, validateEngine } from '../lib/store'; import type { ImageModelChoice, RuntimeModels, RuntimeModel } from '../lib/types'; import { useNative } from '../lib/native'; import { NativeModels } from '../components/NativeModels'; @@ -55,7 +56,7 @@ function LegacyModelRunScreen({ importFirst = false, initialVariant }: { const imageNeedsDownload = imageChoice !== 'off' && imageVersion?.state !== 'installed'; const imageUnavailable = imageChoice !== 'off' && !imageModels?.generationAvailable; const rawDraft = useStore(s => s.configDraft), connected = useStore(s => s.connection === 'live'); - const lifecycle = lifecycleStatus(useStore(s => s)); + const lifecycle = useLifecycle(); const [selected, setSelected] = useState(() => { if (initialVariant) return initialVariant; @@ -424,7 +425,7 @@ function LegacyModelRunScreen({ importFirst = false, initialVariant }: {
{tr("Version")}