Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa6ee7fd31 | ||
|
|
e1baf6f00f | ||
|
|
c5572cad54 | ||
|
|
b309778be8 | ||
|
|
771c6f5245 | ||
|
|
5fc405d86a | ||
|
|
c82ab5028b | ||
|
|
d8c5a0bf0e | ||
|
|
dad2685ea3 | ||
|
|
84ee68d4da | ||
|
|
43b07aca48 |
No files matched your search
@@ -3,6 +3,41 @@
|
||||
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
|
||||
until 1.0, minor versions may contain breaking changes.
|
||||
|
||||
## [v202611-00061] – 2026-11-18
|
||||
|
||||
### Changed
|
||||
|
||||
- **Factory: project dropdown** instead of one button per project – choose "All projects" or a single one; the choice is remembered.
|
||||
|
||||
## [v202611-00060] – 2026-11-18
|
||||
|
||||
### Changed
|
||||
|
||||
- **All uploads are chunked and show progress**: files page, chat attachments, new-session wizard, recreate dialog and backup restore upload in 8 MB chunks (no more reverse-proxy limits) with a progress panel – one bar per file and one for the total.
|
||||
|
||||
### Added
|
||||
|
||||
- **Factory: recreate mode** ("Recreate software" next to "New project"): upload a program or give a source URL; an analyst chat (craft agent, deep mode, "recreate" skill) unpacks, decompiles and documents the original exhaustively, audits itself against a coverage list and writes a clean-room `spec.md` with milestones. Analysis, originals and notes stay in the private draft folder; the new repository gets only the specification, and the milestones are cut into issues afterwards.
|
||||
|
||||
## [v202611-00059] – 2026-11-17
|
||||
|
||||
### Changed
|
||||
|
||||
- **Collapsible chat list** on wide screens: the menu button in the title bar folds the chat list away (remembered), so chat menus are no longer hidden behind it on small monitors.
|
||||
|
||||
## [v202611-00058] – 2026-11-17
|
||||
|
||||
### Changed
|
||||
|
||||
- **README and screenshots** brought up to date (code factory, skills, new interface); skills labels no longer say "1 files".
|
||||
|
||||
## [v202611-00057] – 2026-11-17
|
||||
|
||||
### Added
|
||||
|
||||
- **Factory: skills per phase.** In the repository settings, each phase (review, build, acceptance) can have
|
||||
skills switched on; the chat of that phase follows them in every turn.
|
||||
|
||||
## [v202611-00056] – 2026-11-17
|
||||
|
||||
### Added
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="Version v202611-00056" src="https://img.shields.io/badge/version-v202611--00056-d69e2e?style=flat-square">
|
||||
<img alt="Version v202611-00061" src="https://img.shields.io/badge/version-v202611--00061-d69e2e?style=flat-square">
|
||||
<img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-689d6a?style=flat-square">
|
||||
<img alt="Rust backend" src="https://img.shields.io/badge/backend-Rust-b7410e?style=flat-square&logo=rust">
|
||||
<img alt="React PWA" src="https://img.shields.io/badge/frontend-React%20PWA-2d81ff?style=flat-square&logo=react">
|
||||
@@ -37,7 +37,7 @@
|
||||
<br>
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/chat.png" alt="A CodeCraft session in the Gruvbox dark theme: a diff of the fix, the task list, and a permission card asking before the test suite runs; the sidebar shows pinned chats, a folder and the archive" width="100%">
|
||||
<img src="docs/images/chat.png" alt="A CodeCraft session in the Gruvbox dark theme: the agent's task list and a permission card with the diff of a one-line fix; the sidebar shows a pinned chat, a folder and today's chats, and the chip in the top bar shows an active skill" width="100%">
|
||||
<br>
|
||||
<sub>A session: the agent works through its task list, shows diffs, and asks before anything outside the rules.</sub>
|
||||
</p>
|
||||
@@ -130,7 +130,7 @@ opens the command palette, and prompt templates with placeholders save typing.
|
||||
<table>
|
||||
<tr>
|
||||
<td width="40%" valign="top">
|
||||
<img src="docs/images/mobile.png" alt="CodeCraft on a phone in a light theme: the agent asks where coupon codes should be stored and offers three options plus free text" width="100%"><br>
|
||||
<img src="docs/images/mobile.png" alt="CodeCraft on a phone in a dark theme: the task list and a permission card with the diff, with Allow once, Always allow and Reject buttons" width="100%"><br>
|
||||
<sub><b>Mobile:</b> answer questions and approve changes from your phone. Share links and text from other apps into a chat.</sub>
|
||||
</td>
|
||||
<td width="60%" valign="top">
|
||||
@@ -154,6 +154,19 @@ slash commands in `.claude/commands` and skills in `.claude/skills` are picked u
|
||||
The agent keeps notes about a project in `.codecraft/memory.md`; your personal memory applies to
|
||||
every project.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/skills.png" alt="Settings, Skills tab: the user's own skills with description and file count, buttons for a new skill and the import from GitHub" width="100%">
|
||||
</p>
|
||||
|
||||
**Skills** are packaged instructions for a kind of task: a folder with a `SKILL.md` (name, description,
|
||||
instructions) and further files. Create them in *Settings → Skills* with a small editor, or import them
|
||||
from a GitHub repository or folder (every folder with a `SKILL.md` is offered; filter and select several).
|
||||
They are stored per user and work next to the skills of your projects and the built-in ones. To keep the
|
||||
context small, you switch skills on **per chat** (menu ⋯ → *Skills for this chat*): only those are part of
|
||||
every turn. All others cost nothing – up to 12 are listed by name, a larger library is not listed at all and
|
||||
the agent finds a skill by keyword and loads it, with its further files, when it needs it. In the
|
||||
[code factory](#code-factory) each phase can have its own skills.
|
||||
|
||||
## Models
|
||||
|
||||
Every provider is an endpoint with a list of models. Each model can have a context size,
|
||||
@@ -204,7 +217,7 @@ platforms: `cargo install --locked --git https://git.familie-zink.org/zink/codec
|
||||
## Automations
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/automations.png" alt="Creating an automation from a template: schedule chips, cron expression, mode, permission mode, model and the task for the agent" width="100%">
|
||||
<img src="docs/images/automations.png" alt="The automation editor: schedule chips with the next runs, mode, approval mode, model, time limit and the instructions file next to an assistant chat" width="100%">
|
||||
</p>
|
||||
|
||||
An automation is an agent that starts on a schedule. Its instructions are a Markdown file
|
||||
@@ -226,6 +239,12 @@ The factory turns issues on your Git forge (Gitea, GitHub or GitLab) into review
|
||||
merged changes – with agents doing the work and you deciding at the points that matter. It is
|
||||
the **Factory** page in the sidebar; all chats it creates live in the sidebar folder *Factory*.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/factory.png" alt="The factory board: columns for review, questions, approved, build, acceptance, failed and done with issue cards, the repository tile with its version, and buttons to plan a feature, cut a milestone and start a release" width="100%">
|
||||
<br>
|
||||
<sub>The factory page: every issue sits in the column of its phase; the repository shows its current version.</sub>
|
||||
</p>
|
||||
|
||||
```
|
||||
issue + label "factory"
|
||||
│
|
||||
@@ -291,8 +310,8 @@ the files attached (Gitea and GitHub).
|
||||
|
||||
**Settings per repository** (*Factory → Repositories*, *New repository*): forge connection and token, label
|
||||
(default `factory`), parallel runs, allowed issue authors (default: the token's owner), and per
|
||||
phase the model, agent (CodeCraft or Claude Code), permission mode, timeout and tries on
|
||||
technical failures, plus the number of rework rounds (default 2). Failed or rejected issues
|
||||
phase the model, agent (CodeCraft or Claude Code), permission mode, timeout, tries on
|
||||
technical failures, the skills that are switched on for it, plus the number of rework rounds (default 2). Failed or rejected issues
|
||||
can be restarted from the board, finished ones are closed with a comment.
|
||||
|
||||
**Files in the repository** (all optional, kept in `.factory/`):
|
||||
|
||||
|
Before Width: | Height: | Size: 118 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 144 KiB After Width: | Height: | Size: 156 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
Before Width: | Height: | Size: 172 KiB After Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 102 KiB After Width: | Height: | Size: 123 KiB |
|
After Width: | Height: | Size: 134 KiB |
|
Before Width: | Height: | Size: 177 KiB After Width: | Height: | Size: 203 KiB |
@@ -150,6 +150,8 @@ pub fn router(app: AppState) -> Router {
|
||||
.route("/backups", get(list_backups).post(run_backup))
|
||||
.route("/backups/{name}", get(download_backup))
|
||||
.route("/backups/{name}/restore", post(restore_stored_backup))
|
||||
.route("/backups/upload", put(upload_backup_chunk))
|
||||
.route("/backups/restore-uploaded", post(restore_chunked_backup))
|
||||
.route("/backups/restore", post(restore_uploaded_backup).layer(axum::extract::DefaultBodyLimit::max(4 * 1024 * 1024 * 1024)))
|
||||
.route("/health", get(health))
|
||||
.route("/tools", get(crate::reverse::status))
|
||||
@@ -1964,6 +1966,43 @@ async fn restore_uploaded_backup(Extension(user): Extension<User>, State(app): S
|
||||
restore_and_restart(&app, &user, body.to_vec(), &format!("upload ({} bytes)", body.len())).await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ChunkQuery {
|
||||
offset: u64,
|
||||
}
|
||||
|
||||
fn restore_upload_path(app: &App) -> std::path::PathBuf {
|
||||
app.config().data_dir().join("restore-upload.tmp")
|
||||
}
|
||||
|
||||
/// One chunk of a backup to restore (offset 0 starts anew); `restore-uploaded` applies the whole file.
|
||||
async fn upload_backup_chunk(Extension(user): Extension<User>, State(app): State<AppState>, Query(q): Query<ChunkQuery>, body: axum::body::Bytes) -> ApiResult {
|
||||
require_admin(&user)?;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let p = restore_upload_path(&app);
|
||||
if q.offset == 0 {
|
||||
tokio::fs::write(&p, &body).await?;
|
||||
} else {
|
||||
let current = tokio::fs::metadata(&p).await.map(|m| m.len()).unwrap_or(0);
|
||||
if current != q.offset {
|
||||
return Err(ApiError(StatusCode::CONFLICT, format!("chunk offset {} does not match the uploaded size {current}", q.offset)));
|
||||
}
|
||||
let mut f = tokio::fs::OpenOptions::new().append(true).open(&p).await?;
|
||||
f.write_all(&body).await?;
|
||||
f.flush().await?;
|
||||
}
|
||||
Ok(Json(json!({"ok": true, "size": q.offset + body.len() as u64})))
|
||||
}
|
||||
|
||||
async fn restore_chunked_backup(Extension(user): Extension<User>, State(app): State<AppState>) -> ApiResult {
|
||||
require_admin(&user)?;
|
||||
let p = restore_upload_path(&app);
|
||||
let bytes = tokio::fs::read(&p).await.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "no uploaded backup".into()))?;
|
||||
let _ = tokio::fs::remove_file(&p).await;
|
||||
let source = format!("upload ({} bytes)", bytes.len());
|
||||
restore_and_restart(&app, &user, bytes, &source).await
|
||||
}
|
||||
|
||||
async fn download_backup(Extension(user): Extension<User>, State(app): State<AppState>, Path(name): Path<String>) -> Result<Response, ApiError> {
|
||||
require_admin(&user)?;
|
||||
if !crate::backup::list(&app).iter().any(|b| b.name == name) {
|
||||
@@ -2914,13 +2953,20 @@ async fn test_factory_connection(Extension(user): Extension<User>, State(app): S
|
||||
struct NewDraft {
|
||||
#[serde(default)]
|
||||
model: Option<String>,
|
||||
/// "recreate": analyse existing software first (clean-room).
|
||||
#[serde(default)]
|
||||
mode: Option<String>,
|
||||
#[serde(default)]
|
||||
source: String,
|
||||
#[serde(default)]
|
||||
notes: String,
|
||||
}
|
||||
|
||||
/// Start a chat in which the user writes a spec with a model.
|
||||
async fn factory_new_draft(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<NewDraft>) -> ApiResult {
|
||||
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||
let model = b.model.filter(|m| !m.is_empty()).unwrap_or(s.defaults.spec_model.clone());
|
||||
let session = crate::factory::start_spec_chat(&app, &user, &model).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||
let session = crate::factory::start_spec_chat(&app, &user, &model, (b.mode.as_deref() == Some("recreate")).then_some((b.source.as_str(), b.notes.as_str()))).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?;
|
||||
Ok(Json(json!(session)))
|
||||
}
|
||||
|
||||
@@ -2937,7 +2983,7 @@ async fn factory_draft(Extension(user): Extension<User>, State(app): State<AppSt
|
||||
let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||
let conns: Vec<Value> = s.connections.iter().map(|c| json!({"id": c.id, "name": c.name, "kind": c.kind, "owner": c.owner})).collect();
|
||||
let setup = std::fs::read_to_string(dir.join("setup.json")).ok().filter(|t| crate::factory::valid_setup(t));
|
||||
Ok(Json(json!({"spec": spec, "setup": setup, "proposal": crate::factory::proposal(&app, &id), "connections": conns})))
|
||||
Ok(Json(json!({"spec": spec, "setup": setup, "proposal": crate::factory::proposal(&app, &id), "connections": conns, "recreate": dir.join("recreate.txt").exists()})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -2957,7 +3003,7 @@ async fn factory_create_project(Extension(user): Extension<User>, State(app): St
|
||||
let spec = std::fs::read_to_string(dir.join("spec.md")).unwrap_or_default();
|
||||
let mut s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?;
|
||||
let setup = std::fs::read_to_string(dir.join("setup.json")).unwrap_or_default();
|
||||
let res = crate::factory::create_project(&app, &user, &mut s, &spec, &setup, &b.connection, &b.name, &b.slug, &b.description, &b.owner).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||
let res = crate::factory::create_project(&app, &user, &mut s, &spec, &setup, &b.connection, &b.name, &b.slug, &b.description, &b.owner, !dir.join("recreate.txt").exists()).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?;
|
||||
app.store.set_user_setting(&user.id, "factory", &s)?;
|
||||
app.audit(Some(&user), "factory.project.create", res["repo"].as_str().unwrap_or(""), &crate::auth::client_ip(&headers));
|
||||
Ok(Json(res))
|
||||
|
||||
@@ -49,6 +49,9 @@ pub struct PhaseCfg {
|
||||
/// Extra instructions appended to the phase prompt.
|
||||
#[serde(default)]
|
||||
pub extra_prompt: String,
|
||||
/// Skills (names) switched on for the chat of this phase; only the CodeCraft agent uses them.
|
||||
#[serde(default)]
|
||||
pub skills: Vec<String>,
|
||||
}
|
||||
|
||||
fn default_agent() -> String {
|
||||
@@ -69,7 +72,7 @@ fn default_rework() -> i64 {
|
||||
|
||||
impl Default for PhaseCfg {
|
||||
fn default() -> Self {
|
||||
Self { model: String::new(), agent: default_agent(), permission_mode: default_mode(), timeout_minutes: default_timeout(), max_attempts: default_attempts(), extra_prompt: String::new() }
|
||||
Self { model: String::new(), agent: default_agent(), permission_mode: default_mode(), timeout_minutes: default_timeout(), max_attempts: default_attempts(), extra_prompt: String::new(), skills: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,6 +174,7 @@ impl RepoCfg {
|
||||
}
|
||||
p.timeout_minutes = p.timeout_minutes.clamp(1, 24 * 60);
|
||||
p.max_attempts = p.max_attempts.clamp(1, 10);
|
||||
p.skills = p.skills.iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty() && n.len() <= 64).take(10).collect();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -881,7 +885,8 @@ fn start_phase(app: &Arc<App>, user: &User, cfg: &RepoCfg, issue: i64, phase: &s
|
||||
telegram_quiet: true,
|
||||
summary: String::new(),
|
||||
color: None,
|
||||
icon: None, skills: Vec::new(),
|
||||
icon: None,
|
||||
skills: pc.skills.clone(),
|
||||
};
|
||||
let session = app.save_session(session)?;
|
||||
let run_id = crate::types::new_id();
|
||||
@@ -1553,19 +1558,44 @@ fn is_planning_path(factory: &std::path::Path, cwd: &std::path::Path) -> bool {
|
||||
cwd.strip_prefix(factory).map(|rel| rel.components().any(|c| c.as_os_str() == "_drafts" || c.as_os_str() == "_issues")).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Instructions of a "recreate" draft: analyse existing software in depth, then write a clean-room spec.
|
||||
pub const RECREATE_INSTRUCTIONS: &str = r#"You are the analyst of a software factory working in RECREATE / clean-room mode. The user wants an existing program rebuilt as a new, independent implementation. You analyse the original down to the last detail and write the specification; later, other agents build the new software from that specification alone – they never see the original, your notes or any decompiled code. Answer in the user's language.
|
||||
|
||||
Your working directory is private and never published. It holds `original/` (the program: files the user uploaded and/or what you download), `analysis/` (tool output, notes, scripts), `docs/` (documentation of the original) and the two deliverables `spec.md` and `setup.json`.
|
||||
|
||||
Load the skill "recreate" and follow its phases – but go deeper than its minimum and work through them on your own, without waiting for the user between phases (ask_user only when something essential cannot be found out otherwise):
|
||||
1. Acquire and inventory: fetch the source named in `recreate.txt` (git clone / curl into `original/`, never run installers or the program unsandboxed), unpack archives recursively, identify every file, write `docs/01-inventory.md`.
|
||||
2. Analyse exhaustively: read the source code if it is available, otherwise use binary_info and decompile on EVERY executable and library. Cover entry points and main loop, every screen/dialog/command/option, all rules and algorithms with their exact constants, tables and string/message texts, data and file formats (byte layouts), configuration, persistence, error handling, timing, network protocols, third-party libraries. Keep `analysis/coverage.md`: a list of every file, function group and resource with its status (understood, partly, unknown) – and keep working until nothing important stays open or unknown.
|
||||
3. Document in your own words in `docs/` (templates of the skill).
|
||||
4. Write `spec.md`: the only input for the builders. Structure: Goal · Users · Behaviour per area (numbered features, each with acceptance criteria that can be checked in the running app) · Data and file formats (byte layouts are facts and may be exact) · Texts and constants that must match · Non-functional requirements · Tech stack with reasons · Out of scope · Open questions · **Milestones** (M0 project setup and test harness; then M1…Mn in build order, the smallest useful first version first; each milestone names its features; the last one is wrap-up/performance/docs).
|
||||
Clean-room rules for spec.md: behaviour and facts only – no source or decompiled code, no decompiler-generated names or addresses, no pasted code snippets; describe algorithms in prose or pseudocode of your own.
|
||||
5. Audit: re-read spec.md against `analysis/coverage.md` and the originals, close gaps, and check that nothing in it is copied code. Write the result to `analysis/audit.md`.
|
||||
6. Keep `setup.json` like the spec writers do (install/start/url of the NEW software). Ask the user for the technology only if the recreation plan leaves it open.
|
||||
7. Finish with a short summary and tell the user to review `spec.md` (and `docs/`), correct things together with you, and then say when it is done. Only then propose name and slug and end your message with exactly one fenced json block and nothing after it:
|
||||
```json
|
||||
{"decision": "ready", "name": "Project name", "slug": "project-name", "description": "one sentence"}
|
||||
```
|
||||
The repository is then created with spec.md only; the milestones are cut into issues afterwards."#;
|
||||
|
||||
/// Start a spec chat with the given model.
|
||||
pub fn start_spec_chat(app: &Arc<App>, user: &User, model: &str) -> Result<crate::types::Session> {
|
||||
pub fn start_spec_chat(app: &Arc<App>, user: &User, model: &str, recreate: Option<(&str, &str)>) -> Result<crate::types::Session> {
|
||||
let id = crate::types::new_id();
|
||||
let dir = draft_dir(app, user, &id)?;
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
if let Some((source, notes)) = recreate {
|
||||
for d in ["original", "analysis", "docs"] {
|
||||
std::fs::create_dir_all(dir.join(d))?;
|
||||
}
|
||||
std::fs::write(dir.join("recreate.txt"), format!("Source: {}\n\nNotes from the user:\n{}\n", Some(source.trim()).filter(|s| !s.is_empty()).unwrap_or("(none given – the files are in original/)"), notes.trim()))?;
|
||||
}
|
||||
let model = Some(model.to_string()).filter(|m| !m.is_empty()).or_else(|| Some(app.config().server.default_model.clone()).filter(|m| !m.is_empty())).or_else(|| app.registry().first_model()).context("no model configured")?;
|
||||
let now = crate::types::now_ms();
|
||||
let session = crate::types::Session {
|
||||
id,
|
||||
title: "Factory – new project".into(),
|
||||
title: if recreate.is_some() { "Factory – recreate" } else { "Factory – new project" }.into(),
|
||||
cwd: dir.display().to_string(),
|
||||
model,
|
||||
agent: "build".into(),
|
||||
agent: if recreate.is_some() { "craft" } else { "build" }.into(),
|
||||
permission_mode: "auto".into(),
|
||||
parent_id: None,
|
||||
owner_id: Some(user.id.clone()),
|
||||
@@ -1573,17 +1603,18 @@ pub fn start_spec_chat(app: &Arc<App>, user: &User, model: &str) -> Result<crate
|
||||
updated_at: now,
|
||||
todos: Value::Null,
|
||||
last_usage: None,
|
||||
clean_room: None,
|
||||
clean_room: recreate.map(|_| false),
|
||||
phase: None,
|
||||
worktree: None,
|
||||
pinned: false,
|
||||
archived: false,
|
||||
folder: Some(FACTORY_FOLDER.to_string()),
|
||||
instructions: SPEC_INSTRUCTIONS.to_string(),
|
||||
instructions: if recreate.is_some() { RECREATE_INSTRUCTIONS } else { SPEC_INSTRUCTIONS }.to_string(),
|
||||
telegram_quiet: true,
|
||||
summary: String::new(),
|
||||
color: None,
|
||||
icon: None, skills: Vec::new(),
|
||||
icon: None,
|
||||
skills: if recreate.is_some() { vec!["recreate".to_string()] } else { Vec::new() },
|
||||
};
|
||||
app.save_session(session)
|
||||
}
|
||||
@@ -1622,7 +1653,7 @@ pub fn valid_setup(text: &str) -> bool {
|
||||
|
||||
/// Create the repository, file README and spec, register the repository and open the issue
|
||||
/// that starts the workflow. Safe to repeat after a failure: an empty repository is reused.
|
||||
pub async fn create_project(app: &Arc<App>, user: &User, settings: &mut FactorySettings, spec: &str, setup: &str, connection: &str, name: &str, slug: &str, description: &str, owner: &str) -> Result<Value> {
|
||||
pub async fn create_project(app: &Arc<App>, user: &User, settings: &mut FactorySettings, spec: &str, setup: &str, connection: &str, name: &str, slug: &str, description: &str, owner: &str, start: bool) -> Result<Value> {
|
||||
let slug = slugify(slug);
|
||||
if slug.len() < 2 {
|
||||
bail!("the repository name is too short");
|
||||
@@ -1673,6 +1704,10 @@ pub async fn create_project(app: &Arc<App>, user: &User, settings: &mut FactoryS
|
||||
// The issue that starts the workflow.
|
||||
let g = Forge::new(&resolved)?;
|
||||
g.ensure_labels().await?;
|
||||
if !start {
|
||||
// Recreate projects: the milestones are cut into issues next (issue chat), nothing is built yet.
|
||||
return Ok(json!({"url": cfg.url, "repo": created["full_name"], "issue": Value::Null, "issue_url": Value::Null, "spec": spec_path, "setup": setup_filed}));
|
||||
}
|
||||
let issue = g.create_issue(name, &format!("{}\n\nSpec: {spec_path}", description.trim()), &[cfg.label.clone()]).await?;
|
||||
let n = issue_no(&issue);
|
||||
app.store.factory_issue_add(&cfg.url, n, &user.id, name, &login)?;
|
||||
@@ -1803,6 +1838,7 @@ mod tests {
|
||||
let v = parse_result(t).unwrap();
|
||||
assert_eq!((v["decision"].as_str(), v["slug"].as_str()), (Some("ready"), Some("todo")));
|
||||
assert!(SPEC_INSTRUCTIONS.contains("\"decision\": \"ready\""));
|
||||
assert!(RECREATE_INSTRUCTIONS.contains("\"decision\": \"ready\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -36,6 +36,23 @@ export function App() {
|
||||
const [info, setInfo] = useState<Info>();
|
||||
const [error, setError] = useState<string>();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
// Wide screens: the chat list can be folded away (remembered); narrow screens use the slide-in drawer.
|
||||
const [folded, setFolded] = useState(() => {
|
||||
try {
|
||||
return localStorage.getItem("codecraft.sidebarFolded") === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
const openMenu = () => {
|
||||
if (window.matchMedia("(max-width: 800px)").matches) return setMenuOpen(true);
|
||||
setFolded((f) => {
|
||||
try {
|
||||
localStorage.setItem("codecraft.sidebarFolded", f ? "0" : "1");
|
||||
} catch {}
|
||||
return !f;
|
||||
});
|
||||
};
|
||||
const [shared, setShared] = useState(pendingShare);
|
||||
const offline = useStore((s) => s.offline);
|
||||
useTitleActivity();
|
||||
@@ -98,40 +115,40 @@ export function App() {
|
||||
const [section, arg] = route;
|
||||
let content;
|
||||
const chatIds = section === "s" && arg ? arg.split("+").filter(Boolean).slice(0, MAX_PANES) : [];
|
||||
if (chatIds.length === 1) content = <ChatView key={chatIds[0]} sessionId={chatIds[0]} onMenu={() => setMenuOpen(true)} />;
|
||||
if (chatIds.length === 1) content = <ChatView key={chatIds[0]} sessionId={chatIds[0]} onMenu={openMenu} />;
|
||||
else if (chatIds.length > 1)
|
||||
content = (
|
||||
<div className="split-view">
|
||||
{chatIds.map((id) => (
|
||||
<div key={id} className="split-pane">
|
||||
<ChatView sessionId={id} onMenu={() => setMenuOpen(true)} onClosePane={() => closePane(id)} />
|
||||
<ChatView sessionId={id} onMenu={openMenu} onClosePane={() => closePane(id)} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
else if (section === "settings") content = <Settings tab={arg} onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "p" && arg) content = <ProjectPage key={arg} cwd={decodeURIComponent(arg)} onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "factory") content = <Factory onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "stats") content = <Stats onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "images") content = <Images onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "jobs" && arg) content = <JobEditor key={arg} id={arg} onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "jobs") content = <Jobs onMenu={() => setMenuOpen(true)} />;
|
||||
else if (section === "settings") content = <Settings tab={arg} onMenu={openMenu} />;
|
||||
else if (section === "p" && arg) content = <ProjectPage key={arg} cwd={decodeURIComponent(arg)} onMenu={openMenu} />;
|
||||
else if (section === "factory") content = <Factory onMenu={openMenu} />;
|
||||
else if (section === "stats") content = <Stats onMenu={openMenu} />;
|
||||
else if (section === "images") content = <Images onMenu={openMenu} />;
|
||||
else if (section === "jobs" && arg) content = <JobEditor key={arg} id={arg} onMenu={openMenu} />;
|
||||
else if (section === "jobs") content = <Jobs onMenu={openMenu} />;
|
||||
else if (section === "terminal")
|
||||
content = (
|
||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||
<TerminalPage id={arg} onMenu={() => setMenuOpen(true)} />
|
||||
<TerminalPage id={arg} onMenu={openMenu} />
|
||||
</Suspense>
|
||||
);
|
||||
else if (section === "files")
|
||||
content = (
|
||||
<Suspense fallback={<div className="empty"><Spinner /></div>}>
|
||||
<Files onMenu={() => setMenuOpen(true)} />
|
||||
<Files onMenu={openMenu} />
|
||||
</Suspense>
|
||||
);
|
||||
else content = <NewSession onMenu={() => setMenuOpen(true)} onCreated={(id) => navigate(`/s/${id}`)} />;
|
||||
else content = <NewSession onMenu={openMenu} onCreated={(id) => navigate(`/s/${id}`)} />;
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<div className={`app ${folded ? "side-folded" : ""}`}>
|
||||
{menuOpen && <div className="backdrop" onClick={() => setMenuOpen(false)} />}
|
||||
<Sidebar open={menuOpen} activeIds={chatIds} section={section ?? ""} />
|
||||
<main className="main">
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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 {
|
||||
@@ -30,6 +31,7 @@ interface PhaseCfg {
|
||||
timeout_minutes: number;
|
||||
max_attempts: number;
|
||||
extra_prompt: string;
|
||||
skills: string[];
|
||||
}
|
||||
interface RepoCfg {
|
||||
url: string;
|
||||
@@ -168,10 +170,23 @@ export function Factory({ onMenu }: { onMenu: () => void }) {
|
||||
function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
const t = useT();
|
||||
const [data, setData] = useState<Overview>();
|
||||
const [repo, setRepo] = useState<string>("");
|
||||
const [repo, setRepoState] = useState<string>(() => {
|
||||
try {
|
||||
return localStorage.getItem("codecraft.factoryRepo") ?? "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
});
|
||||
const setRepo = (r: string) => {
|
||||
setRepoState(r);
|
||||
try {
|
||||
localStorage.setItem("codecraft.factoryRepo", r);
|
||||
} catch {}
|
||||
};
|
||||
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")
|
||||
@@ -186,6 +201,11 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
return () => clearInterval(h);
|
||||
}, []);
|
||||
|
||||
// A remembered project that no longer exists falls back to "all".
|
||||
useEffect(() => {
|
||||
if (data && repo && !data.repos.some((r) => r.url === repo)) setRepo("");
|
||||
}, [data, repo]);
|
||||
|
||||
const newProject = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
@@ -266,11 +286,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>
|
||||
@@ -376,29 +400,39 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
</div>
|
||||
|
||||
<div className="factory-repos">
|
||||
<button className={`factory-repo ${repo === "" ? "active" : ""}`} onClick={() => setRepo("")}>
|
||||
<b>{t("factory.allRepos")}</b>
|
||||
<span className="hint">{t("factory.kpi.issues", { n: data.issues.length })}</span>
|
||||
</button>
|
||||
{data.repos.map((r) => {
|
||||
const mine = data.issues.filter((i) => i.repo === r.url);
|
||||
<select className="factory-repo-select" value={repo} onChange={(e) => setRepo(e.target.value)} aria-label={t("factory.project")}>
|
||||
<option value="">
|
||||
{t("factory.allRepos")} ({data.issues.length})
|
||||
</option>
|
||||
{data.repos.map((r) => (
|
||||
<option key={r.url} value={r.url}>
|
||||
{repoName(r.url)}
|
||||
{r.version ? ` · v${r.version}` : ""} ({data.issues.filter((i) => i.repo === r.url).length}){r.enabled ? "" : " – off"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{(() => {
|
||||
const r = data.repos.find((x) => x.url === repo);
|
||||
if (!r) return null;
|
||||
return (
|
||||
<button key={r.url} className={`factory-repo ${repo === r.url ? "active" : ""} ${r.enabled ? "" : "off"}`} onClick={() => setRepo(r.url)}>
|
||||
<b>{repoName(r.url)}</b>
|
||||
<span className="factory-repo-info">
|
||||
<span className="chip">{KIND_NAME[r.kind] ?? r.kind}</span>
|
||||
{r.version && <span className="chip ok mono">v{r.version}</span>}
|
||||
<span className="hint">
|
||||
{r.running > 0 && <span className="factory-pulse" />}
|
||||
{t("factory.repoLine", { n: mine.length, run: r.running })}
|
||||
{t("factory.repoLine", { n: data.issues.filter((i) => i.repo === r.url).length, run: r.running })}
|
||||
</span>
|
||||
<span className="hint mono">{PHASES.map((p) => r.models[p] || "·").map((m) => m.split("/").pop()).join(" → ")}</span>
|
||||
{!r.has_token && <span className="chip warn">{t("factory.noToken")}</span>}
|
||||
</button>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
})()}
|
||||
<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>
|
||||
@@ -448,6 +482,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 }}>
|
||||
@@ -575,11 +610,46 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, max_attempts: 2, extra_prompt: "" });
|
||||
const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, max_attempts: 2, extra_prompt: "", skills: [] });
|
||||
const blankRepo = (connection = "", kind = "gitea"): RepoCfg => ({ url: "", kind, connection, token: "", label: "factory", max_parallel: 1, max_rework: 2, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() });
|
||||
const blankConn = (): Connection => ({ id: "", name: "", kind: "gitea", url: "", token: "", owner: "" });
|
||||
const MODES = ["default", "auto", "accept_edits", "bypass"];
|
||||
|
||||
/** Skills switched on for the chat of one phase (the agent follows them in every turn). */
|
||||
function PhaseSkills({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) {
|
||||
const t = useT();
|
||||
const [all, setAll] = useState<{ name: string; description: string }[]>([]);
|
||||
useEffect(() => {
|
||||
get<{ skills: { name: string; description: string }[] }>("/commands")
|
||||
.then((d) => setAll(d.skills))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
const rest = all.filter((s) => !value.includes(s.name));
|
||||
return (
|
||||
<div className="factory-skills">
|
||||
<span>{t("factory.skills")}</span>
|
||||
<div className="row" style={{ gap: 4, flexWrap: "wrap" }}>
|
||||
{value.map((n) => (
|
||||
<button key={n} type="button" className="chip" style={{ border: "none" }} title={t("factory.skillRemove")} onClick={() => onChange(value.filter((x) => x !== n))}>
|
||||
{n} ×
|
||||
</button>
|
||||
))}
|
||||
{rest.length > 0 && value.length < 10 && (
|
||||
<select value="" onChange={(e) => e.target.value && onChange([...value, e.target.value])}>
|
||||
<option value="">{t("factory.skillAdd")}</option>
|
||||
{rest.map((s) => (
|
||||
<option key={s.name} value={s.name} title={s.description}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<div className="hint">{t("factory.skillsHint")}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg; onChange: (patch: Partial<PhaseCfg>) => void }) {
|
||||
const t = useT();
|
||||
return (
|
||||
@@ -614,6 +684,7 @@ function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg;
|
||||
<span>{t("factory.attempts")}</span>
|
||||
<input type="number" min={1} max={10} value={value.max_attempts} title={t("factory.attemptsHint")} onChange={(e) => onChange({ max_attempts: Math.max(1, Number(e.target.value) || 1) })} />
|
||||
</label>
|
||||
<PhaseSkills value={value.skills ?? []} onChange={(skills) => onChange({ skills })} />
|
||||
<label>
|
||||
<span>{t("factory.extraPrompt")}</span>
|
||||
<textarea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
};
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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())}>
|
||||
|
||||
@@ -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",
|
||||
@@ -790,7 +793,7 @@ export const de: Messages = {
|
||||
"skills.skipped": "übersprungen",
|
||||
"skills.filter": "Filtern…",
|
||||
"skills.empty": "Noch keine Skills.",
|
||||
"skills.files": "{n} Dateien",
|
||||
"skills.files": "Dateien: {n}",
|
||||
"skills.name": "Name (Ordner, Kleinbuchstaben)",
|
||||
"skills.file": "Datei",
|
||||
"skills.addFile": "Pfad der neuen Datei",
|
||||
@@ -799,7 +802,7 @@ export const de: Messages = {
|
||||
"skills.chatTitle": "Skills für diesen Chat",
|
||||
"skills.chatHint": "Eingeschaltete Skills gelten für jede Nachricht dieses Chats. Schalte nur ein, was du brauchst – jeder belegt Kontext.",
|
||||
"skills.manyActive": "Viele aktive Skills belegen viel Kontext.",
|
||||
"skills.chip": "{n} Skills",
|
||||
"skills.chip": "Skills: {n}",
|
||||
"instructions.chip": "Anweisungen",
|
||||
"chat.compacted": "Unterhaltung komprimiert – Zusammenfassung",
|
||||
"chat.context": "Kontext",
|
||||
@@ -1292,6 +1295,10 @@ export const de: Messages = {
|
||||
"factory.closeMsg": "Kommentar zum Schließen von Issue #{n}. Er wird im Issue veröffentlicht, danach wird das Issue geschlossen.",
|
||||
"factory.closeDefault": "Erledigt und abgenommen.",
|
||||
"factory.closed": "Issue geschlossen",
|
||||
"factory.skills": "Skills",
|
||||
"factory.skillAdd": "Skill hinzufügen…",
|
||||
"factory.skillRemove": "Entfernen",
|
||||
"factory.skillsHint": "Für jeden Chat dieser Phase eingeschaltet (CodeCraft-Agent). Jeder belegt Kontext – wenige wählen.",
|
||||
"factory.pr": "Pull Request",
|
||||
"factory.round": "Runde {n}",
|
||||
"factory.openChat": "Chat öffnen",
|
||||
@@ -1317,6 +1324,7 @@ export const de: Messages = {
|
||||
"factory.test": "Verbindung testen",
|
||||
"factory.testOk": "Verbunden als {login} mit {repo}; {n} Labels angelegt, Repository geklont.",
|
||||
"factory.deleteConfirm": "{name} aus der Factory entfernen? Issues und Chats bleiben.",
|
||||
"factory.project": "Projekt",
|
||||
"factory.newProject": "Neues Projekt",
|
||||
"factory.connections": "Verbindungen",
|
||||
"factory.connectionsHint": "Deine Konten bei Gitea, GitHub oder GitLab. Jeder Nutzer richtet seine eigenen ein; Repositories nutzen den Token ihrer Verbindung, sofern sie keinen eigenen haben.",
|
||||
@@ -1340,6 +1348,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",
|
||||
|
||||
@@ -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",
|
||||
@@ -789,7 +792,7 @@ export const en = {
|
||||
"skills.skipped": "skipped",
|
||||
"skills.filter": "Filter…",
|
||||
"skills.empty": "No skills yet.",
|
||||
"skills.files": "{n} files",
|
||||
"skills.files": "Files: {n}",
|
||||
"skills.name": "Name (folder, lowercase)",
|
||||
"skills.file": "File",
|
||||
"skills.addFile": "Path of the new file",
|
||||
@@ -798,7 +801,7 @@ export const en = {
|
||||
"skills.chatTitle": "Skills for this chat",
|
||||
"skills.chatHint": "Switched-on skills are part of every message of this chat. Switch on only what you need – each one uses context.",
|
||||
"skills.manyActive": "Many active skills use a lot of context.",
|
||||
"skills.chip": "{n} skills",
|
||||
"skills.chip": "Skills: {n}",
|
||||
"instructions.chip": "Instructions",
|
||||
"chat.compacted": "Conversation compacted – summary",
|
||||
"chat.context": "Context",
|
||||
@@ -1291,6 +1294,10 @@ export const en = {
|
||||
"factory.closeMsg": "Comment for closing issue #{n}. It is posted on the issue, then the issue is closed.",
|
||||
"factory.closeDefault": "Done and accepted.",
|
||||
"factory.closed": "Issue closed",
|
||||
"factory.skills": "Skills",
|
||||
"factory.skillAdd": "Add skill…",
|
||||
"factory.skillRemove": "Remove",
|
||||
"factory.skillsHint": "Switched on for every chat of this phase (CodeCraft agent). Each one uses context – choose few.",
|
||||
"factory.pr": "Pull request",
|
||||
"factory.round": "round {n}",
|
||||
"factory.openChat": "Open chat",
|
||||
@@ -1316,6 +1323,7 @@ export const en = {
|
||||
"factory.test": "Test connection",
|
||||
"factory.testOk": "Connected as {login} to {repo}; {n} labels created, repository cloned.",
|
||||
"factory.deleteConfirm": "Remove {name} from the factory? Issues and chats stay.",
|
||||
"factory.project": "Project",
|
||||
"factory.newProject": "New project",
|
||||
"factory.connections": "Connections",
|
||||
"factory.connectionsHint": "Your accounts at Gitea, GitHub or GitLab. Each user sets up their own; repositories use the token of their connection unless they have a token of their own.",
|
||||
@@ -1339,6 +1347,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",
|
||||
|
||||
@@ -477,8 +477,10 @@ button.session-group:hover {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.menu-btn {
|
||||
display: none;
|
||||
@media (min-width: 801px) {
|
||||
.app.side-folded .sidebar {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.chip {
|
||||
@@ -5042,6 +5044,16 @@ td.fold-indent {
|
||||
margin-bottom: 14px;
|
||||
align-items: stretch;
|
||||
}
|
||||
.factory-repo-select {
|
||||
min-width: 220px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.factory-repo-info {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.factory-repo {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -5200,3 +5212,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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -3,6 +3,26 @@
|
||||
* under "unreleased"; scripts/release.sh renames the key to the release version.
|
||||
*/
|
||||
export const WHATS_NEW: Record<string, { en: string[]; de: string[] }> = {
|
||||
"202611-00061": {
|
||||
en: ["Factory: projects are chosen from a dropdown (all projects or a single one)"],
|
||||
de: ["Factory: Projekte werden per Dropdown gewählt (alle oder nur eins)"],
|
||||
},
|
||||
"202611-00060": {
|
||||
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)"],
|
||||
},
|
||||
"202611-00058": {
|
||||
en: ["README and screenshots updated"],
|
||||
de: ["README und Screenshots aktualisiert"],
|
||||
},
|
||||
"202611-00057": {
|
||||
en: ["Factory: choose skills for each phase (review, build, acceptance)"],
|
||||
de: ["Factory: Skills für jede Phase wählbar (Review, Build, Abnahme)"],
|
||||
},
|
||||
"202611-00056": {
|
||||
en: ["Skills: create or import them from GitHub (Settings → Skills) and switch them on per chat; large libraries do not fill the context"],
|
||||
de: ["Skills: selbst anlegen oder von GitHub importieren (Einstellungen → Skills) und pro Chat einschalten; große Bibliotheken füllen den Kontext nicht"],
|
||||
|
||||