Factory recreate mode; chunked uploads with progress everywhere

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Richard ZinkandClaude Sonnet 5.5 committed 2026-11-18 13:49:16 +01:00
1 parent 771c6f5245
commit b309778be8
17 files changed
+477 -47

No files matched your search

+4 -20
View File
@@ -1,4 +1,5 @@
import type { ServerEvent } from "./types";
import { chunkedUpload } from "./uploads";
// Authentication uses an HttpOnly session cookie set by /api/auth/login.
@@ -101,27 +102,10 @@ export function connectEvents(handlers: {
};
}
const CHUNK = 8 * 1024 * 1024;
/**
* Upload a file in 8 MB chunks (stays below reverse proxy body limits; up to the
* server's max_upload_mb). `onProgress` gets the uploaded fraction 0..1.
* Upload a single file in chunks (see uploads.ts). `onProgress` gets the uploaded fraction 0..1.
* Without the progress panel – use `uploadBatch` for user-visible uploads.
*/
export async function uploadFile(path: string, file: Blob, onProgress?: (fraction: number) => void): Promise<void> {
let offset = 0;
do {
const chunk = file.slice(offset, offset + CHUNK);
const res = await fetch(`/api/files/upload?path=${encodeURIComponent(path)}&offset=${offset}`, { method: "PUT", body: chunk, credentials: "same-origin" });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try {
msg = (await res.json()).error ?? msg;
} catch {
if (res.status === 413) msg = "too large for the reverse proxy";
}
throw new Error(msg);
}
offset += chunk.size;
onProgress?.(file.size ? offset / file.size : 1);
} while (offset < file.size);
await chunkedUpload(`/api/files/upload?path=${encodeURIComponent(path)}`, file, (n) => onProgress?.(file.size ? n / file.size : 1));
}
+3 -4
View File
@@ -1,7 +1,7 @@
import { TemplatePicker } from "./TemplatePicker";
import { Icon } from "./Icon";
import { formatSize, imageSrc } from "./FileFigure";
import { uploadFile } from "../api";
import { uploadBatch } from "../uploads";
import { useEffect, useMemo, useRef, useState } from "react";
import { useAgents, useFetch, useModels } from "../hooks";
import { useT, type Key } from "../i18n";
@@ -201,9 +201,8 @@ export function Composer({
await fetch(`/api/files/create?`, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path: `${session.cwd}/.codecraft/uploads`, dir: true }) });
// Keep uploads out of git status without touching the project's .gitignore.
await fetch(`/api/files/upload?path=${encodeURIComponent(`${session.cwd}/.codecraft/uploads/.gitignore`)}`, { method: "PUT", body: "*\n", credentials: "same-origin" });
await uploadFile(path, f).catch((e) => {
throw new Error(`${f.name}: ${e.message}`);
});
const sent = await uploadBatch([{ file: f, path }]);
if (!sent.length) throw new Error(f.name);
setFiles((cur) => [...cur, { name: f.name, path, size: f.size }]);
} catch (e: any) {
toast(e.message ?? String(e));
+10
View File
@@ -6,6 +6,7 @@ import { choiceDialog, confirmDialog, promptDialog, toast } from "../dialogs";
import { Icon } from "./Icon";
import { Spinner } from "./Activity";
import { ModelSelect } from "./ModelSelect";
import { RecreateDialog } from "./FactoryDraft";
import { ReleaseDialog, ReleasesPanel, type ReleaseRow } from "./FactoryRelease";
interface PrInfo {
@@ -173,6 +174,7 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
const [sel, setSel] = useState<string>("");
const [now, setNow] = useState(Date.now());
const [busy, setBusy] = useState(false);
const [recreate, setRecreate] = useState(false);
const reload = () =>
get<Overview>("/factory/overview")
@@ -267,11 +269,15 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
if (data.repos.length === 0)
return (
<div className="empty">
{recreate && <RecreateDialog onClose={() => setRecreate(false)} />}
<p>{t("factory.empty")}</p>
<div className="row" style={{ gap: 8, justifyContent: "center" }}>
<button className="primary" onClick={newProject} disabled={busy}>
<Icon name="plus" /> {t("factory.newProject")}
</button>
<button onClick={() => setRecreate(true)} disabled={busy}>
<Icon name="search" /> {t("recreate.button")}
</button>
<button onClick={onSettings}>{t("factory.tab.settings")}</button>
</div>
</div>
@@ -400,6 +406,9 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
<button className="small primary" onClick={newProject} disabled={busy}>
<Icon name="plus" /> {t("factory.newProject")}
</button>
<button className="small" onClick={() => setRecreate(true)} disabled={busy} title={t("recreate.hint")}>
<Icon name="search" /> {t("recreate.button")}
</button>
<button className="small" onClick={() => issueChat("feature")} disabled={busy} title={t("issues.featureHint")}>
<Icon name="sparkle" /> {t("issues.feature")}
</button>
@@ -449,6 +458,7 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
</div>
<ReleasesPanel releases={(data.releases ?? []).filter((r) => !repo || r.repo === repo)} />
{recreate && <RecreateDialog onClose={() => setRecreate(false)} />}
{releaseRepo && <ReleaseDialog repo={releaseRepo} onClose={() => setReleaseRepo("")} onStarted={() => void reload()} />}
<div className="panel" style={{ marginTop: 16 }}>
+59 -2
View File
@@ -3,6 +3,7 @@ import { get, post } from "../api";
import { useT } from "../i18n";
import { navigate } from "../router";
import { toast } from "../dialogs";
import { uploadBatch } from "../uploads";
import { Icon } from "./Icon";
import { Spinner } from "./Activity";
@@ -11,6 +12,7 @@ interface Draft {
setup?: string | null;
proposal: { name?: string; slug?: string; description?: string } | null;
connections: { id: string; name: string; kind: string; owner: string }[];
recreate?: boolean;
}
export const isDraftChat = (cwd: string) => /\/_drafts\/[^/]+$/.test(cwd);
@@ -88,9 +90,9 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
const create = async () => {
setBusy(true);
try {
const r = await post<{ repo: string; issue: number }>(`/factory/drafts/${sessionId}/create`, { connection, name, slug, description, owner });
const r = await post<{ repo: string; issue: number | null }>(`/factory/drafts/${sessionId}/create`, { connection, name, slug, description, owner });
await post("/factory/poll", {}).catch(() => undefined);
toast(t("draft.created", { repo: r.repo, n: r.issue }), "success");
toast(r.issue == null ? t("draft.createdRecreate", { repo: r.repo }) : t("draft.created", { repo: r.repo, n: r.issue }), "success");
onClose();
navigate("/factory");
} catch (e: any) {
@@ -312,3 +314,58 @@ function CreateIssuesDialog({ sessionId, onClose }: { sessionId: string; onClose
</div>
);
}
/** Start a recreate draft: the original (upload and/or URL) is analysed in depth, then a clean-room spec is written. */
export function RecreateDialog({ onClose }: { onClose: () => void }) {
const t = useT();
const [source, setSource] = useState("");
const [notes, setNotes] = useState("");
const [files, setFiles] = useState<File[]>([]);
const [busy, setBusy] = useState(false);
const start = async () => {
setBusy(true);
try {
const s = await post<{ id: string; cwd: string }>("/factory/drafts", { mode: "recreate", source, notes });
const sent = await uploadBatch(files.map((f) => ({ file: f, path: `${s.cwd}/original/${f.name}` })));
if (sent.length < files.length) throw new Error(t("recreate.uploadFailed"));
await post(`/sessions/${s.id}/prompt`, { text: t("recreate.firstMessage") });
onClose();
navigate(`/s/${s.id}`);
} catch (e: any) {
toast(e.message);
setBusy(false);
}
};
return (
<div className="modal-backdrop" onClick={busy ? undefined : onClose}>
<div className="modal draft-modal" role="dialog" aria-label={t("recreate.title")} onClick={(e) => e.stopPropagation()}>
<h3>{t("recreate.title")}</h3>
<div className="hint" style={{ marginBottom: 8 }}>{t("recreate.hint")}</div>
<div className="factory-form">
<label style={{ gridColumn: "1 / -1" }}>
<span>{t("recreate.source")}</span>
<input autoFocus value={source} placeholder="https://…" onChange={(e) => setSource(e.target.value)} />
</label>
<label style={{ gridColumn: "1 / -1" }}>
<span>{t("recreate.files")}</span>
<input type="file" multiple onChange={(e) => setFiles([...(e.target.files ?? [])])} />
</label>
<label style={{ gridColumn: "1 / -1" }}>
<span>{t("recreate.notes")}</span>
<textarea rows={4} value={notes} placeholder={t("recreate.notesPlaceholder")} onChange={(e) => setNotes(e.target.value)} />
</label>
</div>
<div className="row" style={{ justifyContent: "flex-end", gap: 8, marginTop: 12 }}>
<button onClick={onClose} disabled={busy}>
{t("common.cancel")}
</button>
<button className="primary" onClick={start} disabled={busy || (!source.trim() && files.length === 0)}>
{busy ? <Spinner small /> : <Icon name="search" />} {t("recreate.go")}
</button>
</div>
</div>
</div>
);
}
+2 -4
View File
@@ -1,3 +1,4 @@
import { uploadBatch } from "../uploads";
import { Icon } from "./Icon";
import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { del, get, post, put } from "../api";
@@ -223,10 +224,7 @@ export function Files({ onMenu, embed }: { onMenu?: () => void; embed?: FilesEmb
const upload = async (files: FileList | File[]) => {
if (!listing) return;
for (const f of [...files]) {
const res = await fetch(`/api/files/upload?path=${encodeURIComponent(`${listing.path}/${f.name}`)}`, { method: "PUT", body: f, credentials: "same-origin" });
if (!res.ok) toast(`${f.name}: HTTP ${res.status}${res.status === 413 ? " – too large for the reverse proxy" : ""}`);
}
await uploadBatch([...files].map((f) => ({ file: f, path: `${listing.path}/${f.name}` })));
await load(listing.path);
void refreshGit();
};
+9 -6
View File
@@ -1,6 +1,7 @@
import { Icon } from "./Icon";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { post, uploadFile } from "../api";
import { post } from "../api";
import { uploadBatch } from "../uploads";
import { promptDialog, toast } from "../dialogs";
import { useAgents, useFetch } from "../hooks";
import { useT, type Key } from "../i18n";
@@ -313,12 +314,14 @@ export function NewSession({ onMenu, onCreated }: { onMenu: () => void; onCreate
const send = async (list: File[], dir: string) => {
if (!list.length) return;
await mkdirs(dir);
for (const f of list) {
const jobs = list.map((f) => {
const name = f.name.replace(/[\\/]/g, "_");
setCreating(`${t("wizard.uploading")} ${name}`);
await uploadFile(`${cwd}/${dir}/${name}`, f, (x) => setProgress((p) => ({ ...p, [f.name]: x })));
uploaded.push(`${dir}/${name}`);
}
return { file: f, path: `${cwd}/${dir}/${name}`, name, onProgress: (x: number) => setProgress((p) => ({ ...p, [f.name]: x })) };
});
setCreating(t("wizard.uploading"));
const sent = await uploadBatch(jobs);
if (sent.length < jobs.length) throw new Error(t("recreate.uploadFailed"));
for (const j of jobs) uploaded.push(`${dir}/${j.name}`);
};
// Originals of old software go to original/, everything else to .codecraft/uploads/.
await send(originals, "original");
+51
View File
@@ -0,0 +1,51 @@
import { useT } from "../i18n";
import { closeUploadBatch, useUploads } from "../uploads";
import { Icon } from "./Icon";
import { formatSize } from "./FileFigure";
/** Progress of running uploads: one box per batch with a bar for the total and one per file. */
export function UploadPanel() {
const t = useT();
const batches = useUploads();
if (!batches.length) return null;
return (
<div className="uploads" role="status" aria-live="polite">
{batches.map((b) => {
const total = b.items.reduce((a, i) => a + i.size, 0);
const sent = b.items.reduce((a, i) => a + i.sent, 0);
const finished = b.items.filter((i) => i.status === "done" || i.status === "error").length;
const running = finished < b.items.length;
const pct = (a: number, z: number) => (z ? Math.min(100, Math.round((a / z) * 100)) : 100);
return (
<div key={b.id} className="upload-batch">
<div className="upload-head">
<strong>{running ? t("upload.running", { done: finished, n: b.items.length }) : t("upload.finished", { n: b.items.length })}</strong>
<span className="hint">
{formatSize(sent)} / {formatSize(total)}
</span>
<button className="small ghost" onClick={() => closeUploadBatch(b.id)} aria-label={t("common.close")}>
<Icon name="close" />
</button>
</div>
<div className="upload-bar total" title={`${pct(sent, total)} %`}>
<i style={{ width: `${pct(sent, total)}%` }} />
</div>
<div className="upload-files">
{b.items.map((i) => (
<div key={i.id} className={`upload-file ${i.status}`}>
<span className="name" title={i.name}>
{i.name}
</span>
<span className="hint">{i.status === "error" ? i.error : i.status === "wait" ? formatSize(i.size) : `${pct(i.sent, i.size)} %`}</span>
<div className="upload-bar">
<i style={{ width: `${pct(i.sent, i.size)}%` }} />
</div>
</div>
))}
</div>
</div>
);
})}
</div>
);
}
+6 -1
View File
@@ -1,3 +1,4 @@
import { uploadBatch } from "../../uploads";
import { useEffect, useRef, useState } from "react";
import { api, get, patch, post } from "../../api";
import { confirmDialog, toast } from "../../dialogs";
@@ -100,7 +101,11 @@ export function Backups() {
setRestoring(true);
try {
if ("name" in source) await post(`/backups/${encodeURIComponent(source.name)}/restore`);
else await api("/backups/restore", { method: "POST", body: source.file, headers: { "Content-Type": "application/zip" } });
else {
const sent = await uploadBatch([{ file: source.file, path: "", name: source.file.name, endpoint: "/api/backups/upload" }]);
if (!sent.length) throw new Error(t("backup.uploadFailed"));
await post("/backups/restore-uploaded");
}
toast(t("backup.restarting"), "info");
// Wait until the server is gone and back, then reload with the restored data.
await new Promise((r) => setTimeout(r, 2500));
+2
View File
@@ -1,3 +1,4 @@
import { UploadPanel } from "./components/UploadPanel";
import { Icon } from "./components/Icon";
// In-app dialogs and toasts instead of the browser's alert/confirm/prompt.
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
@@ -158,6 +159,7 @@ export function DialogHost() {
{state.map((d) => (
<DialogView key={d.id} d={d} />
))}
<UploadPanel />
<div className="toasts" role="status" aria-live="polite">
{ts.map((x) => (
<div key={x.id} className={`toast ${x.kind}`} onClick={() => ((toasts = toasts.filter((y) => y.id !== x.id)), emit())}>
+14
View File
@@ -79,6 +79,8 @@ export const de: Messages = {
"files.search": "Dateien suchen…",
"files.newFile": "Neue Datei",
"files.newFolder": "Neuer Ordner",
"upload.running": "Lade hoch {done}/{n} …",
"upload.finished": "{n} Datei(en) hochgeladen",
"files.upload": "Hochladen",
"files.showHidden": "Versteckte Dateien zeigen",
"files.newFileName": "Dateiname:",
@@ -656,6 +658,7 @@ export const de: Messages = {
"backup.restoring": "Wird wiederhergestellt…",
"backup.restoreTitle": "Backup wiederherstellen?",
"backup.restoreConfirm": "Datenbank und Konfiguration durch {file} ersetzen? Alle Sitzungen, Benutzer, Statistiken und Einstellungen werden durch den Stand im Backup ersetzt; Dateien im Workspace bleiben unverändert. Der aktuelle Stand wird vorher gesichert. CodeCraft startet neu – laufende Agents werden beendet.",
"backup.uploadFailed": "Das Backup konnte nicht hochgeladen werden.",
"backup.restarting": "Backup übernommen – CodeCraft startet neu…",
"backup.notBack": "Der Server ist nicht zurückgekommen. Er braucht eine Restart-Policy (Docker: restart: unless-stopped) – bitte von Hand starten.",
"backup.now": "Jetzt sichern",
@@ -1344,6 +1347,17 @@ export const de: Messages = {
"factory.repoToken": "Eigener Token (optional)",
"factory.repoTokenPlaceholder": "leer = Token der Verbindung",
"factory.repoTokenHint": "Nur nötig, wenn dieses Repository einen anderen Token nutzen soll.",
"recreate.button": "Software nachbauen",
"recreate.title": "Bestehende Software nachbauen",
"recreate.hint": "Cleanroom-Modus: Das Original wird bis ins Detail analysiert (Entpacken, Dekompilieren, Formate, Verhalten), danach entsteht eine Spezifikation mit Meilensteinen. Die Bau-Agenten sehen nur diese Spezifikation, nie das Original.",
"recreate.source": "Quelle (Git- oder Download-URL, optional)",
"recreate.files": "Dateien des Originals (Programm, Installer, Archive)",
"recreate.notes": "Hinweise",
"recreate.notesPlaceholder": "Was soll die neue Version anders oder besser machen? Zielplattform, bevorzugte Technik, besonders wichtige Teile …",
"recreate.uploadFailed": "Nicht alle Dateien konnten hochgeladen werden – siehe Upload-Anzeige.",
"recreate.go": "Analyse starten",
"recreate.firstMessage": "Starte jetzt die Analyse. Das Original liegt in original/, recreate.txt nennt Quelle und meine Hinweise.",
"draft.createdRecreate": "{repo} mit der Spezifikation angelegt. Schneide als Nächstes die Meilensteine in Issues (Factory → „Meilenstein zerlegen“).",
"draft.hint": "Spec-Chat: Wenn die Spec fertig ist, lege sie als neues Repository ab.",
"draft.create": "Projekt anlegen",
"draft.createGo": "Repository anlegen und starten",
+14
View File
@@ -78,6 +78,8 @@ export const en = {
"files.search": "Search files…",
"files.newFile": "New file",
"files.newFolder": "New folder",
"upload.running": "Uploading {done}/{n}…",
"upload.finished": "Uploaded {n} file(s)",
"files.upload": "Upload",
"files.showHidden": "Show hidden files",
"files.newFileName": "File name:",
@@ -655,6 +657,7 @@ export const en = {
"backup.restoring": "Restoring…",
"backup.restoreTitle": "Restore backup?",
"backup.restoreConfirm": "Replace the database and the configuration with {file}? All sessions, users, statistics and settings are replaced by the state in the backup; files in the workspace stay as they are. The current state is backed up first. CodeCraft restarts – running agents are stopped.",
"backup.uploadFailed": "The backup could not be uploaded.",
"backup.restarting": "Backup accepted – CodeCraft is restarting…",
"backup.notBack": "The server did not come back. It needs a restart policy (Docker: restart: unless-stopped) – start it again by hand.",
"backup.now": "Back up now",
@@ -1343,6 +1346,17 @@ export const en = {
"factory.repoToken": "Own token (optional)",
"factory.repoTokenPlaceholder": "empty = token of the connection",
"factory.repoTokenHint": "Only needed when this repository should use a different token.",
"recreate.button": "Recreate software",
"recreate.title": "Recreate existing software",
"recreate.hint": "Clean-room mode: the original is analysed in depth (unpacking, decompiling, formats, behaviour), then a specification with milestones is written. The builders only ever see that specification, never the original.",
"recreate.source": "Source (git or download URL, optional)",
"recreate.files": "Files of the original (program, installer, archives)",
"recreate.notes": "Notes",
"recreate.notesPlaceholder": "What should the new version do differently or better? Target platform, preferred technology, parts that matter most…",
"recreate.uploadFailed": "Not every file could be uploaded – see the upload panel.",
"recreate.go": "Start analysis",
"recreate.firstMessage": "Start the analysis now. The original is in original/ and recreate.txt tells you the source and my notes.",
"draft.createdRecreate": "{repo} created with the specification. Cut the milestones into issues next (“Cut a milestone” in the Factory).",
"draft.hint": "Spec chat: when the spec is done, file it as a new repository.",
"draft.create": "Create project",
"draft.createGo": "Create repository and start",
+77
View File
@@ -5202,3 +5202,80 @@ td.fold-indent {
border-top: 1px solid var(--border);
padding: 6px 0;
}
/* --- upload progress ------------------------------------------------------------ */
.uploads {
position: fixed;
left: 16px;
bottom: 16px;
z-index: 55;
display: grid;
gap: 8px;
width: min(380px, calc(100vw - 32px));
max-height: 60vh;
overflow-y: auto;
padding-bottom: env(safe-area-inset-bottom);
}
.upload-batch {
background: var(--bg1);
border: 1px solid var(--bg3);
border-radius: 10px;
box-shadow: var(--shadow);
padding: 10px 12px;
display: grid;
gap: 6px;
}
.upload-head {
display: flex;
align-items: center;
gap: 8px;
}
.upload-head strong {
flex: 1;
font-size: 13px;
}
.upload-bar {
height: 6px;
border-radius: 3px;
background: var(--bg3);
overflow: hidden;
}
.upload-bar.total {
height: 8px;
}
.upload-bar i {
display: block;
height: 100%;
background: var(--accent);
transition: width 0.15s;
}
.upload-files {
display: grid;
gap: 6px;
max-height: 32vh;
overflow-y: auto;
}
.upload-file {
display: grid;
grid-template-columns: 1fr auto;
gap: 2px 8px;
font-size: 12px;
}
.upload-file .name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.upload-file .upload-bar {
grid-column: 1 / -1;
height: 4px;
}
.upload-file.done .upload-bar i {
background: var(--green, var(--accent));
}
.upload-file.error .hint {
color: var(--red, #e5484d);
}
.upload-file.error .upload-bar i {
background: var(--red, #e5484d);
}
+125
View File
@@ -0,0 +1,125 @@
import { useSyncExternalStore } from "react";
/** One file of an upload batch. */
export interface UploadItem {
id: number;
name: string;
size: number;
sent: number;
status: "wait" | "run" | "done" | "error";
error?: string;
}
/** Uploads started together (a drop, a file dialog); shown as one panel with a total bar. */
export interface UploadBatch {
id: number;
items: UploadItem[];
closed: boolean;
}
const CHUNK = 8 * 1024 * 1024;
let seq = 0;
let batches: UploadBatch[] = [];
const listeners = new Set<() => void>();
const emit = () => {
batches = [...batches];
listeners.forEach((l) => l());
};
export const useUploads = () =>
useSyncExternalStore(
(l) => (listeners.add(l), () => listeners.delete(l)),
() => batches,
);
export const closeUploadBatch = (id: number) => {
batches = batches.filter((b) => b.id !== id);
emit();
};
/** PUT one chunk; `onBytes` reports the bytes of this chunk sent so far. */
function putChunk(url: string, chunk: Blob, onBytes: (n: number) => void): Promise<void> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("PUT", url);
xhr.withCredentials = true;
xhr.upload.onprogress = (e) => e.lengthComputable && onBytes(e.loaded);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) return resolve();
let msg = `HTTP ${xhr.status}`;
try {
msg = JSON.parse(xhr.responseText).error ?? msg;
} catch {
if (xhr.status === 413) msg = "too large for the reverse proxy";
}
reject(new Error(msg));
};
xhr.onerror = () => reject(new Error("network error"));
xhr.send(chunk);
});
}
/**
* Upload a file in 8 MB chunks (stays below reverse proxy body limits; the server appends at `offset`).
* `onProgress` gets the bytes sent so far.
*/
export async function chunkedUpload(endpoint: string, file: Blob, onProgress?: (sent: number) => void): Promise<void> {
const sep = endpoint.includes("?") ? "&" : "?";
let offset = 0;
do {
const chunk = file.slice(offset, offset + CHUNK);
const base = offset;
await putChunk(`${endpoint}${sep}offset=${offset}`, chunk, (n) => onProgress?.(base + n));
offset += chunk.size;
onProgress?.(offset);
} while (offset < file.size);
}
export interface UploadJob {
file: File | Blob;
/** Absolute target path on the server (files upload). */
path: string;
/** Other chunked endpoint instead of /api/files/upload. */
endpoint?: string;
name?: string;
/** Called with the fraction 0..1 of this file. */
onProgress?: (fraction: number) => void;
}
/**
* Upload files one after the other with the progress panel (per file and in total).
* Resolves with the paths that arrived; failed files are listed in the panel.
*/
export async function uploadBatch(jobs: UploadJob[]): Promise<string[]> {
if (!jobs.length) return [];
const batch: UploadBatch = {
id: ++seq,
closed: false,
items: jobs.map((j) => ({ id: ++seq, name: j.name ?? (j.file as File).name ?? j.path.split("/").pop() ?? "file", size: j.file.size, sent: 0, status: "wait" as const })),
};
batches = [...batches, batch];
emit();
const done: string[] = [];
for (const [i, j] of jobs.entries()) {
const it = batch.items[i];
it.status = "run";
emit();
try {
await chunkedUpload(j.endpoint ?? `/api/files/upload?path=${encodeURIComponent(j.path)}`, j.file, (n) => {
it.sent = n;
j.onProgress?.(j.file.size ? n / j.file.size : 1);
emit();
});
it.sent = it.size;
it.status = "done";
done.push(j.path);
} catch (e: any) {
it.status = "error";
it.error = e.message ?? String(e);
}
emit();
}
// A clean batch fades away, one with errors stays until it is closed.
if (batch.items.every((x) => x.status === "done")) setTimeout(() => closeUploadBatch(batch.id), 2500);
return done;
}
+4
View File
@@ -3,6 +3,10 @@
* under "unreleased"; scripts/release.sh renames the key to the release version.
*/
export const WHATS_NEW: Record<string, { en: string[]; de: string[] }> = {
unreleased: {
en: ["Uploads are chunked everywhere and show progress per file and in total", "Factory: recreate mode – analyse existing software in depth and rebuild it clean-room from a specification with milestones"],
de: ["Uploads laufen überall in Teilen und zeigen den Fortschritt je Datei und gesamt", "Factory: Nachbau-Modus – bestehende Software bis ins Detail analysieren und Cleanroom aus einer Spezifikation mit Meilensteinen neu bauen"],
},
"202611-00059": {
en: ["The chat list can be folded away on wide screens (menu button in the title bar)"],
de: ["Die Chatliste lässt sich auf breiten Bildschirmen zuklappen (Menü-Button in der Titelleiste)"],