feat(xiaoyi): wire 1.2612.109 cross-track storage, multi-project UI and concurrency seams
This commit is contained in:
parent
b6a08be74a
commit
a52287d650
@ -550,6 +550,47 @@ fn project_slot_key(backend: &Backend, input: &Value, doc: Option<u64>) -> Proje
|
||||
(backend.scope(), project)
|
||||
}
|
||||
|
||||
fn storage_node_path() -> Result<PathBuf, String> {
|
||||
pi_runtime::runtime().map(|(node, _)| node)
|
||||
}
|
||||
|
||||
fn dispatch_storage_action(
|
||||
method: String,
|
||||
input: Value,
|
||||
project_slots: Arc<Mutex<ProjectSlots>>,
|
||||
project_busy: Arc<std::sync::atomic::AtomicBool>,
|
||||
events: mpsc::Sender<Event>,
|
||||
ctx: egui::Context,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
let guard = || {
|
||||
let slots = project_slots.lock().map_err(|_| "后台任务锁暂不可用".to_owned())?;
|
||||
if !slots.active.is_empty()
|
||||
|| !slots.restoring.is_empty()
|
||||
|| !slots.queued.is_empty()
|
||||
|| project_busy.load(std::sync::atomic::Ordering::Acquire)
|
||||
{
|
||||
return Err("仍有项目正在运行、排队或保存,请等待完成或暂停后再操作".into());
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let emit_events = events.clone();
|
||||
let emit_ctx = ctx.clone();
|
||||
let host = crate::jiansun_storage::Host {
|
||||
guard: &guard,
|
||||
rebase: project_file::rebase_storage_json,
|
||||
node: storage_node_path,
|
||||
emit: Box::new(move |event| {
|
||||
let _ = emit_events.send(event);
|
||||
emit_ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}),
|
||||
};
|
||||
let result = crate::jiansun_storage::handle_action(&method, &input, host);
|
||||
let _ = events.send(Event::Json(method, result));
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
});
|
||||
}
|
||||
|
||||
fn enqueue_open<T: Send + 'static>(requests: mpsc::Sender<T>, open: impl FnOnce() -> T + Send + 'static) {
|
||||
static OPEN_WORKERS: std::sync::OnceLock<reads::QueuedReads> = std::sync::OnceLock::new();
|
||||
if let Err(error) = OPEN_WORKERS.get_or_init(reads::QueuedReads::detail_review).submit(move || {
|
||||
@ -2349,10 +2390,19 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
let ctx = ctx.clone();
|
||||
std::thread::spawn(move || b.scan_recovery(&tx, &ctx));
|
||||
}
|
||||
dispatch_storage_action(
|
||||
"storage-status".into(),
|
||||
json!({"op": "status"}),
|
||||
project_slots.clone(),
|
||||
project_busy.clone(),
|
||||
events.clone(),
|
||||
ctx.clone(),
|
||||
);
|
||||
for request in rx {
|
||||
if backend.exiting() && !matches!(&request, Request::Save(..) | Request::DeliverProductionBundle(..))
|
||||
&& !matches!(&request, Request::Action(method, _) if matches!(method.as_str(),
|
||||
"product-run-checkpoint" | "product-exit-checkpoint" | "product-end-checkpoint" | "slot-adopted"))
|
||||
&& !matches!(&request, Request::Action(method, input) if matches!(method.as_str(),
|
||||
"product-run-checkpoint" | "product-exit-checkpoint" | "product-end-checkpoint" | "slot-adopted")
|
||||
|| (method == "storage-migrate" && input["op"] == "cancel_switch"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@ -2577,6 +2627,17 @@ pub fn start(root: PathBuf, ctx: egui::Context) -> Workspace {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if matches!(method.as_str(), "storage-status" | "storage-scan" | "storage-cleanup" | "storage-migrate") {
|
||||
dispatch_storage_action(
|
||||
method,
|
||||
input,
|
||||
project_slots.clone(),
|
||||
project_busy.clone(),
|
||||
events.clone(),
|
||||
ctx.clone(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let skip_post_request = (|| {
|
||||
if method == "project-operation" {
|
||||
backend.project_operation(input, project_busy.clone(), &events, &ctx);
|
||||
|
||||
@ -39,6 +39,8 @@ struct Location {
|
||||
cleanup: bool,
|
||||
#[serde(default)]
|
||||
cleanup_started: bool,
|
||||
#[serde(default)]
|
||||
prompt_deferred: bool,
|
||||
manifest_sha256: Option<String>,
|
||||
}
|
||||
|
||||
@ -75,19 +77,38 @@ impl Migration {
|
||||
|
||||
fn progress(&self) -> Value {
|
||||
let switching = self.phase == Phase::Switching;
|
||||
let restarting = self.phase == Phase::Restarting;
|
||||
let target_free = existing_ancestor(&self.to_path).ok().and_then(|path| free_bytes(path).ok());
|
||||
let switch_steps = if switching || restarting {
|
||||
Some([
|
||||
json!({"id":"freeze","label":"停写冻结核对(刷新会话与任务日志)","status":"completed","state":"done"}),
|
||||
json!({"id":"verify","label":"路径改写与完整性校验","status":if restarting { "completed" } else { "running" },"state":if restarting { "done" } else { "active" }}),
|
||||
json!({"id":"publish","label":"原子写入新目录指针(保留旧目录)","status":if restarting { "running" } else { "pending" },"state":if restarting { "active" } else { "pending" }}),
|
||||
json!({"id":"restart","label":"重启应用并完成启动自检","status":"pending","state":"pending"}),
|
||||
])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
json!({
|
||||
"phase":self.phase, "copiedBytes":self.copied_bytes, "totalBytes":self.total_bytes,
|
||||
"phase":self.phase,
|
||||
"targetRoot":self.to_path,
|
||||
"targetFreeBytes":target_free,
|
||||
"requiredBytes":self.total_bytes,
|
||||
"copiedBytes":self.copied_bytes,
|
||||
"totalBytes":self.total_bytes,
|
||||
"percent":(self.phase == Phase::Copying).then(|| {
|
||||
(self.copied_bytes.saturating_mul(100) / self.total_bytes.max(1)).min(100)
|
||||
}),
|
||||
"currentStep":self.message, "error":(self.phase == Phase::Failed).then_some(&self.message),
|
||||
"canRetry":self.phase == Phase::Failed,
|
||||
"currentStep":self.message,
|
||||
"validationError":Value::Null,
|
||||
"validationWarnings":json!([]),
|
||||
"blockingProjects":json!([]),
|
||||
"error":(self.phase == Phase::Failed).then_some(&self.message),
|
||||
"rollbackNote":(self.phase == Phase::RolledBack).then_some(&self.message),
|
||||
"canRetry":matches!(self.phase, Phase::Failed | Phase::RolledBack),
|
||||
"oldPathToRelease":(self.phase == Phase::Completed).then_some(&self.from_path),
|
||||
"steps":switching.then(|| [
|
||||
json!({"id":"freeze","label":"停止写入","status":"completed"}),
|
||||
json!({"id":"verify","label":"同步与校验","status":"running"}),
|
||||
json!({"id":"publish","label":"切换存储目录","status":"pending"}),
|
||||
])
|
||||
"steps":switch_steps,
|
||||
"switchSteps":switch_steps,
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -618,7 +639,7 @@ fn current_location(migration: &Migration, manifest_hash: String) -> Location {
|
||||
version: 1, root: migration.to_path.clone(), previous_root: Some(migration.from_path.clone()),
|
||||
migration_id: migration.id, migrated_at: chrono::Utc::now().to_rfc3339(),
|
||||
app_version: photocraft_engine::build_info::long_version(), cleanup: false, cleanup_started: false,
|
||||
manifest_sha256: Some(manifest_hash),
|
||||
prompt_deferred: false, manifest_sha256: Some(manifest_hash),
|
||||
}
|
||||
}
|
||||
|
||||
@ -744,7 +765,7 @@ fn restore_previous(platform: &Path, entry: &Location, migration: &mut Migration
|
||||
write(&platform.join(POINTER), &Location {
|
||||
version: 1, root: previous.clone(), previous_root: None, migration_id: previous_id,
|
||||
migrated_at: chrono::Utc::now().to_rfc3339(), app_version: entry.app_version.clone(),
|
||||
cleanup: true, cleanup_started: true, manifest_sha256: None,
|
||||
cleanup: true, cleanup_started: true, prompt_deferred: false, manifest_sha256: None,
|
||||
})?;
|
||||
}
|
||||
migration.phase = Phase::RolledBack;
|
||||
@ -887,13 +908,24 @@ impl Plan {
|
||||
fn summary(&self) -> Value {
|
||||
let totals = self.totals();
|
||||
json!({
|
||||
"scanning": false,
|
||||
"cleanupRunning": false,
|
||||
"totalBytes": unique_bytes(&self.files),
|
||||
"reclaimableLosslessBytes": totals[..5].iter().sum::<u64>(),
|
||||
"reclaimablePolicyBytes": totals[5],
|
||||
"categories": CATEGORIES.iter().zip(totals).enumerate().map(|(index, (&(id, label, lossless, risk_note), bytes))| {
|
||||
"categories": CATEGORIES.iter().zip(totals).enumerate().map(|(index, (&(id, label, lossless, note), bytes))| {
|
||||
let error = self.unavailable[index].as_deref();
|
||||
json!({"id":id,"label":label,"bytes":bytes,"lossless":lossless,
|
||||
"riskNote":error.unwrap_or(risk_note),"selectedByDefault":lossless && error.is_none()})
|
||||
let description = if lossless {
|
||||
note
|
||||
} else {
|
||||
"清理超出最近两代的旧成品导出目录,当前版与上一版始终保留"
|
||||
};
|
||||
let risk_note = error.or_else(|| (!lossless).then_some(note));
|
||||
let default_selected = lossless && error.is_none();
|
||||
json!({
|
||||
"id":id,"label":label,"description":description,"bytes":bytes,"lossless":lossless,
|
||||
"riskNote":risk_note,"selectedByDefault":default_selected,"defaultSelected":default_selected
|
||||
})
|
||||
}).collect::<Vec<_>>()
|
||||
})
|
||||
}
|
||||
@ -1330,20 +1362,54 @@ fn update_stats(root: &Path, files: &[DiskFile]) {
|
||||
Stats { root: root.to_owned(), bytes: unique_bytes(files), projects: project_count(files) });
|
||||
}
|
||||
|
||||
fn status(platform: &Path, emit: Sink) -> R<Value> {
|
||||
let data = app_dirs::current();
|
||||
fn human_bytes(bytes: u64) -> String {
|
||||
const KB: f64 = 1024.0;
|
||||
const MB: f64 = 1024.0 * 1024.0;
|
||||
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
|
||||
let b = bytes as f64;
|
||||
if b >= GB {
|
||||
let gb = b / GB;
|
||||
if gb >= 100.0 { format!("{gb:.0} GB") } else { format!("{gb:.1} GB") }
|
||||
} else if b >= MB {
|
||||
let mb = b / MB;
|
||||
if mb >= 100.0 { format!("{mb:.0} MB") } else { format!("{mb:.1} MB") }
|
||||
} else if b >= KB {
|
||||
format!("{:.0} KB", b / KB)
|
||||
} else {
|
||||
format!("{bytes} B")
|
||||
}
|
||||
}
|
||||
|
||||
fn old_root_reclaimable_bytes(old_root: &Path, entry: &Location, migration: &Migration, fallback: u64) -> u64 {
|
||||
let Ok(manifest) = verified_manifest(entry, migration) else {
|
||||
return fallback;
|
||||
};
|
||||
manifest.source_files.keys().filter_map(|rel| {
|
||||
if !rel.components().all(|part| matches!(part, Component::Normal(_))) || skip_migration(rel) {
|
||||
return None;
|
||||
}
|
||||
fs::symlink_metadata(old_root.join(rel)).ok().filter(|meta| meta.is_file() && !is_link(meta)).map(|meta| meta.len())
|
||||
}).sum()
|
||||
}
|
||||
|
||||
fn status_payload(platform: &Path, data: &app_dirs::DataDir, spawn_scan: bool, emit: Option<Sink>) -> R<Value> {
|
||||
let pointer = location(platform).ok().flatten();
|
||||
let migration = journal(platform)?;
|
||||
let stats = STATS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
|
||||
.filter(|stats| data.dir.as_ref() == Some(&stats.root));
|
||||
if let Some(root) = data.dir.clone()
|
||||
if spawn_scan && let Some(emit) = emit && let Some(root) = data.dir.clone()
|
||||
&& stats.is_none() && SCANNING.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_ok()
|
||||
{
|
||||
let platform_for_scan = platform.to_owned();
|
||||
let data_for_scan = data.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Ok(files) = walk(&root, |path| path == Path::new("Recovery"), |_| Ok(())) {
|
||||
update_stats(&root, &files);
|
||||
}
|
||||
SCANNING.store(false, Ordering::Release);
|
||||
if let Ok(refreshed) = status_payload(&platform_for_scan, &data_for_scan, false, None) {
|
||||
emit(Event::Json("storage-status".into(), Ok(refreshed)));
|
||||
}
|
||||
emit(Event::Json("storage-status-refresh".into(), Ok(json!({}))));
|
||||
});
|
||||
}
|
||||
@ -1354,34 +1420,123 @@ fn status(platform: &Path, emit: Sink) -> R<Value> {
|
||||
Mode::Portable => "portable",
|
||||
Mode::Unavailable => "unavailable",
|
||||
};
|
||||
let current_path = data.dir.as_ref().or_else(|| pointer.as_ref().map(|entry| &entry.root));
|
||||
let current_root = current_path.map(|path| path.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let free = current_path.and_then(|path| existing_ancestor(path).ok()).and_then(|path| free_bytes(path).ok());
|
||||
let pending_entry = pointer.as_ref().filter(|entry| !entry.cleanup
|
||||
&& migration.as_ref().is_some_and(|log| log.id == entry.migration_id && log.phase == Phase::Completed));
|
||||
let pending_old = pending_entry.and_then(|entry| entry.previous_root.clone());
|
||||
let project_total = stats.as_ref().map_or(0, |stats| stats.projects);
|
||||
let total_bytes = stats.as_ref().map_or(0, |stats| stats.bytes);
|
||||
let old_cleanup_info = pending_entry.zip(pending_old.as_ref()).zip(migration.as_ref()).map(|((entry, old), log)| {
|
||||
let reclaimable = old_root_reclaimable_bytes(old, entry, log, total_bytes);
|
||||
json!({
|
||||
"oldRoot": old,
|
||||
"reclaimableBytes": reclaimable,
|
||||
"graceDays": 7,
|
||||
"verifiedProjectCount": project_total
|
||||
})
|
||||
});
|
||||
let auto_open_release = pending_entry.is_some_and(|entry| !entry.prompt_deferred);
|
||||
let block_reason: Option<String> = match data.mode {
|
||||
Mode::Override => Some("当前存储由启动环境指定".into()),
|
||||
Mode::Portable => Some("便携模式的数据目录固定在程序旁".into()),
|
||||
Mode::Unavailable => data.warning.clone(),
|
||||
_ if COPYING.load(Ordering::Acquire) => Some("正在准备存储迁移".into()),
|
||||
_ => None,
|
||||
};
|
||||
let (status_text, status_tone) = if data.mode == Mode::Unavailable {
|
||||
(data.warning.clone(), Some("error"))
|
||||
} else if let Some(log) = migration.as_ref().filter(|log| log.phase == Phase::Failed) {
|
||||
(Some(log.message.clone()), Some("error"))
|
||||
} else if let Some(log) = migration.as_ref().filter(|log| log.phase == Phase::RolledBack) {
|
||||
(Some(log.message.clone()), Some("warning"))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let migration_view = match migration.as_ref() {
|
||||
Some(log) if log.phase == Phase::Completed && pending_old.is_none() => json!({"phase":"idle"}),
|
||||
Some(log) => log.progress(),
|
||||
None => json!({"phase":"idle"}),
|
||||
};
|
||||
let last = migration.as_ref().map(|log| json!({"status":log.phase,"fromPath":log.from_path,"toPath":log.to_path,"message":log.message}));
|
||||
Ok(json!({
|
||||
"mode":mode,"currentPath":data.dir.as_ref().or_else(|| pointer.as_ref().map(|entry| &entry.root)),
|
||||
"defaultPath":platform,"envVarName":(data.mode == Mode::Override).then_some("PHOTOCRAFT_CONFIG_DIR"),
|
||||
"totalBytes":stats.as_ref().map(|stats| stats.bytes),"projectCount":stats.as_ref().map(|stats| stats.projects),
|
||||
"mode":mode,
|
||||
"currentPath":current_path,
|
||||
"currentRoot":current_root,
|
||||
"defaultPath":platform,
|
||||
"envVarName":(data.mode == Mode::Override).then_some("PHOTOCRAFT_CONFIG_DIR"),
|
||||
"statsReady":stats.is_some(),
|
||||
"totalBytes":total_bytes,
|
||||
"projectCount":project_total,
|
||||
"freeBytes":free,
|
||||
"scanning":SCANNING.load(Ordering::Acquire),
|
||||
"activeBlockReason": match data.mode {
|
||||
Mode::Override => Some("当前存储由启动环境指定"),
|
||||
Mode::Portable => Some("便携模式的数据目录固定在程序旁"),
|
||||
Mode::Unavailable => data.warning.as_deref(),
|
||||
_ if COPYING.load(Ordering::Acquire) => Some("正在准备存储迁移"),
|
||||
_ => None,
|
||||
},
|
||||
"pendingCleanupOldPath":pointer.filter(|entry| !entry.cleanup && migration.as_ref().is_some_and(|log|
|
||||
log.id == entry.migration_id && log.phase == Phase::Completed)).and_then(|entry| entry.previous_root),
|
||||
"activeBlockReason":block_reason,
|
||||
"readonlyReason":block_reason,
|
||||
"recoveryNote":"异常恢复目录仍保留在本机默认缓存位置,不随迁移移动。",
|
||||
"statusText":status_text,
|
||||
"statusTone":status_tone,
|
||||
"migration":migration_view,
|
||||
"pendingCleanupOldPath":pending_old,
|
||||
"pendingOldRootCleanup":old_cleanup_info,
|
||||
"autoOpenReleaseModal":auto_open_release,
|
||||
"lastMigration":last
|
||||
}))
|
||||
}
|
||||
|
||||
fn status(platform: &Path, data: &app_dirs::DataDir, emit: Sink) -> R<Value> {
|
||||
status_payload(platform, data, true, Some(emit))
|
||||
}
|
||||
|
||||
fn validate_target_view(platform: &Path, root: &Path, proposed: &str) -> Value {
|
||||
let required = STATS.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
|
||||
.filter(|stats| stats.root == root).map_or(0, |stats| stats.bytes);
|
||||
let requested = Path::new(proposed);
|
||||
let target_free = existing_ancestor(requested).ok().and_then(|path| free_bytes(path).ok());
|
||||
let mut warnings = Vec::new();
|
||||
let validation_error = match fs::canonicalize(root).map_err(disk) {
|
||||
Ok(canonical_from) => match validate_destination(&canonical_from, requested, platform, |name| std::env::var_os(name)) {
|
||||
Ok(_) => {
|
||||
if let Some(free) = target_free && required > 0 && let Err(space_err) = check_space(free, required) {
|
||||
Some(space_err)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Err(err) => Some(err),
|
||||
},
|
||||
Err(err) => Some(err),
|
||||
};
|
||||
if validation_error.is_none() && proposed.chars().count() > 40 {
|
||||
warnings.push("目标路径较长,建议控制在 40 个字符以内以免触发深路径问题。");
|
||||
}
|
||||
json!({
|
||||
"targetRoot": proposed,
|
||||
"migration": {
|
||||
"phase": "idle",
|
||||
"targetRoot": proposed,
|
||||
"targetFreeBytes": target_free,
|
||||
"requiredBytes": required,
|
||||
"validationError": validation_error,
|
||||
"validationWarnings": warnings,
|
||||
"blockingProjects": []
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn start_copy(platform: PathBuf, root: &Path, input: &Value, op: &str, emit: Sink) -> R<Value> {
|
||||
let root = fs::canonicalize(root).map_err(disk)?;
|
||||
let current = journal(&platform)?;
|
||||
let mut migration = if op == "retry" {
|
||||
current.filter(|entry| entry.from_path == root && matches!(entry.phase, Phase::Copying | Phase::Failed
|
||||
| Phase::ReadyToSwitch | Phase::Switching | Phase::Restarting | Phase::Validating))
|
||||
| Phase::RolledBack | Phase::ReadyToSwitch | Phase::Switching | Phase::Restarting | Phase::Validating))
|
||||
.ok_or("没有可继续的迁移")?
|
||||
} else {
|
||||
let proposed = input["targetPath"].as_str().ok_or("请选择新的存储目录")?;
|
||||
let proposed = input["targetRoot"].as_str()
|
||||
.or_else(|| input["targetPath"].as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or("请选择新的存储目录")?;
|
||||
let target = validate_destination(&root, Path::new(proposed), &platform, |name| std::env::var_os(name))?;
|
||||
if let Some(entry) = current.filter(|entry| entry.from_path == root && entry.to_path == target
|
||||
&& !matches!(entry.phase, Phase::Completed | Phase::RolledBack)) {
|
||||
@ -1415,6 +1570,22 @@ fn start_copy(platform: PathBuf, root: &Path, input: &Value, op: &str, emit: Sin
|
||||
std::thread::spawn(move || {
|
||||
progress(&*emit, &migration);
|
||||
if let Err(error) = precopy(&platform, &mut migration, &*emit) {
|
||||
if CANCEL.swap(false, Ordering::AcqRel) {
|
||||
let _ = fs::remove_file(platform.join(JOURNAL));
|
||||
if let Ok(stage) = migration.stage() { let _ = fs::remove_dir_all(stage); }
|
||||
COPYING.store(false, Ordering::Release);
|
||||
(*emit)(Event::Json("storage-migrate-progress".into(), Ok(json!({
|
||||
"phase":"idle",
|
||||
"targetRoot":migration.to_path,
|
||||
"currentStep":"预拷贝已取消,原目录已保留",
|
||||
"error":Value::Null,
|
||||
"validationError":Value::Null
|
||||
}))));
|
||||
if let Ok(refreshed) = status_payload(&platform, app_dirs::current(), false, None) {
|
||||
(*emit)(Event::Json("storage-status".into(), Ok(refreshed)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
migration.phase = Phase::Failed;
|
||||
migration.message = error;
|
||||
}
|
||||
@ -1432,11 +1603,48 @@ fn start_copy(platform: PathBuf, root: &Path, input: &Value, op: &str, emit: Sin
|
||||
/// workflow. If that workflow aborts, send cancel_switch to discard the in-memory request.
|
||||
pub(crate) fn handle_action(method: &str, input: &Value, host: Host<'_>) -> R<Value> {
|
||||
let platform = app_dirs::platform_dir(&|name| std::env::var_os(name)).ok_or("无法定位默认配置目录")?;
|
||||
if method == "storage-status" { return status(&platform, host.emit); }
|
||||
let data = app_dirs::current();
|
||||
let root = data.dir.as_deref().ok_or("当前存储目录不可用")?;
|
||||
let _job = JOB.lock().map_err(|_| "存储操作暂不可用")?;
|
||||
handle_action_with(&platform, app_dirs::current(), method, input, host)
|
||||
}
|
||||
|
||||
fn handle_action_with(platform: &Path, data: &app_dirs::DataDir, method: &str, input: &Value, host: Host<'_>) -> R<Value> {
|
||||
let platform = platform.to_path_buf();
|
||||
let op = input["op"].as_str().unwrap_or("start");
|
||||
if method == "storage-status" {
|
||||
if op == "open-folder" {
|
||||
let root = data.dir.as_deref().ok_or("当前存储目录不可用")?;
|
||||
open::that(root).map_err(disk)?;
|
||||
return Ok(json!({"opened":true,"currentRoot":root}));
|
||||
}
|
||||
return status(&platform, data, host.emit);
|
||||
}
|
||||
let root = data.dir.as_deref().ok_or("当前存储目录不可用")?;
|
||||
if method == "storage-migrate" && matches!(op, "pick-folder" | "validate") {
|
||||
if !matches!(data.mode, Mode::Pointer | Mode::Platform) {
|
||||
return Err("当前存储模式无法从小壹切换".into());
|
||||
}
|
||||
if op == "pick-folder" {
|
||||
let start_dir = existing_ancestor(root).unwrap_or(root);
|
||||
let picked = rfd::FileDialog::new()
|
||||
.set_title("选择小壹数据存储目录")
|
||||
.set_directory(start_dir)
|
||||
.pick_folder();
|
||||
let Some(dir) = picked else {
|
||||
return Ok(json!({"cancelled":true}));
|
||||
};
|
||||
let picked_str = dir.to_string_lossy().into_owned();
|
||||
let mut out = validate_target_view(&platform, root, &picked_str);
|
||||
out["pickedRoot"] = json!(picked_str);
|
||||
return Ok(out);
|
||||
}
|
||||
let proposed = input["targetRoot"].as_str()
|
||||
.or_else(|| input["targetPath"].as_str())
|
||||
.unwrap_or("").trim();
|
||||
if proposed.is_empty() {
|
||||
return Ok(json!({"migration":{"phase":"idle","targetRoot":"","validationError":"请选择新的存储目录"}}));
|
||||
}
|
||||
return Ok(validate_target_view(&platform, root, proposed));
|
||||
}
|
||||
let _job = JOB.lock().map_err(|_| "存储操作暂不可用")?;
|
||||
if method == "storage-migrate" && op == "cancel" {
|
||||
if !COPYING.load(Ordering::Acquire) { return Err("当前没有正在运行的预拷贝".into()); }
|
||||
CANCEL.store(true, Ordering::Release);
|
||||
@ -1463,8 +1671,29 @@ pub(crate) fn handle_action(method: &str, input: &Value, host: Host<'_>) -> R<Va
|
||||
.ok_or("清理类别无效")).collect::<Result<_, _>>()?;
|
||||
if selected.is_empty() { return Err("请选择需要清理的类别".into()); }
|
||||
let plan = plan_cleanup(root, host.node)?;
|
||||
let result = apply_cleanup(root, &plan, &selected)?;
|
||||
*STATS.lock().map_err(|_| "存储统计暂不可用")? = None;
|
||||
let mut result = apply_cleanup(root, &plan, &selected)?;
|
||||
let reclaimed = result["reclaimedBytes"].as_u64().unwrap_or(0);
|
||||
let first_error = result["details"].as_array().into_iter().flatten()
|
||||
.flat_map(|row| row["errors"].as_array().into_iter().flatten())
|
||||
.find_map(|err| err["message"].as_str().map(str::to_owned));
|
||||
let refreshed = plan_cleanup(root, host.node).ok();
|
||||
if let Some(plan) = &refreshed {
|
||||
update_stats(root, &plan.files);
|
||||
result["categories"] = plan.summary()["categories"].clone();
|
||||
} else {
|
||||
*STATS.lock().map_err(|_| "存储统计暂不可用")? = None;
|
||||
result["categories"] = json!([]);
|
||||
}
|
||||
result["scanning"] = json!(false);
|
||||
result["cleanupRunning"] = json!(false);
|
||||
result["cleanupResult"] = json!({
|
||||
"freedBytes": reclaimed,
|
||||
"message": format!("已清理释放 {}", human_bytes(reclaimed)),
|
||||
"error": first_error
|
||||
});
|
||||
if let Ok(status_view) = status_payload(&platform, data, false, None) {
|
||||
(host.emit)(Event::Json("storage-status".into(), Ok(status_view)));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
"storage-migrate" => {
|
||||
@ -1472,9 +1701,24 @@ pub(crate) fn handle_action(method: &str, input: &Value, host: Host<'_>) -> R<Va
|
||||
return Err("当前存储模式无法从小壹切换".into());
|
||||
}
|
||||
match op {
|
||||
"start" | "retry" => start_copy(platform, root, input, op, host.emit),
|
||||
"switch_and_restart" | "rollback" => {
|
||||
(host.guard)()?;
|
||||
"start" | "start-copy" | "retry" => {
|
||||
let action_op = if op == "retry" { "retry" } else { "start" };
|
||||
start_copy(platform, root, input, action_op, host.emit)
|
||||
}
|
||||
"switch" | "switch_and_restart" | "rollback" => {
|
||||
if let Err(reason) = (host.guard)() {
|
||||
if op == "switch" {
|
||||
return Ok(json!({
|
||||
"requiresExit": false,
|
||||
"migration": {
|
||||
"phase": "ready_to_switch",
|
||||
"blockingProjects": [reason],
|
||||
"error": reason
|
||||
}
|
||||
}));
|
||||
}
|
||||
return Err(reason);
|
||||
}
|
||||
let rollback = op == "rollback";
|
||||
let migration = journal(&platform)?.ok_or("没有可切换的迁移")?;
|
||||
let expected = if rollback { Phase::Completed } else { Phase::ReadyToSwitch };
|
||||
@ -1485,19 +1729,35 @@ pub(crate) fn handle_action(method: &str, input: &Value, host: Host<'_>) -> R<Va
|
||||
return Err("当前存储迁移状态不允许切换".into());
|
||||
}
|
||||
let step = if rollback { "正在准备切回原目录" } else { "正在停止写入" };
|
||||
let switch_steps = [
|
||||
json!({"id":"freeze","label":"停写冻结核对(刷新会话与任务日志)","status":"running","state":"active"}),
|
||||
json!({"id":"verify","label":"路径改写与完整性校验","status":"pending","state":"pending"}),
|
||||
json!({"id":"publish","label":"原子写入新目录指针(保留旧目录)","status":"pending","state":"pending"}),
|
||||
json!({"id":"restart","label":"重启应用并完成启动自检","status":"pending","state":"pending"}),
|
||||
];
|
||||
(host.emit)(Event::Json("storage-migrate-progress".into(), Ok(json!({
|
||||
"phase":"switching","currentStep":step,"steps":[
|
||||
{"id":"freeze","label":"停止写入","status":"running"},
|
||||
{"id":"verify","label":"同步与校验","status":"pending"},
|
||||
{"id":"publish","label":"切换存储目录","status":"pending"}
|
||||
]
|
||||
"phase":"switching","currentStep":step,"steps":switch_steps,"switchSteps":switch_steps
|
||||
}))));
|
||||
*pending = Some(Switch { platform, migration, rebase: host.rebase, node: host.node, rollback });
|
||||
Ok(json!({"requiresExit":true,"phase":"switching"}))
|
||||
Ok(json!({"requiresExit":true,"phase":"switching","switchSteps":switch_steps}))
|
||||
}
|
||||
"release_old" => {
|
||||
"release_old" | "release-old-root" => {
|
||||
(host.guard)()?;
|
||||
release_old(&platform, root)
|
||||
let released = release_old(&platform, root)?;
|
||||
if let Ok(status_view) = status_payload(&platform, data, false, None) {
|
||||
(host.emit)(Event::Json("storage-status".into(), Ok(status_view)));
|
||||
}
|
||||
Ok(released)
|
||||
}
|
||||
"defer-old-root" => {
|
||||
if let Some(mut entry) = location(&platform)? && !entry.prompt_deferred {
|
||||
entry.prompt_deferred = true;
|
||||
write(&platform.join(POINTER), &entry)?;
|
||||
}
|
||||
if let Ok(status_view) = status_payload(&platform, data, false, None) {
|
||||
(host.emit)(Event::Json("storage-status".into(), Ok(status_view)));
|
||||
}
|
||||
Ok(json!({"deferred":true}))
|
||||
}
|
||||
"confirm" => Ok(journal(&platform)?.map_or_else(|| json!({"phase":"idle"}), |entry| entry.progress())),
|
||||
_ => Err("存储迁移操作无效".into()),
|
||||
@ -1770,6 +2030,104 @@ mod tests {
|
||||
assert!(exports.join("generations/generation-last/detail.jpg").is_file());
|
||||
assert!(!exports.join("generations/generation-old").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_validate_and_cleanup_summary_match_ui_contract() {
|
||||
let (_temp, root, _) = fixture();
|
||||
let platform = root.clone();
|
||||
let data = app_dirs::DataDir { dir: Some(root.clone()), mode: Mode::Platform, warning: None };
|
||||
let status_json = status_payload(&platform, &data, false, None).unwrap();
|
||||
assert_eq!(status_json["mode"], "default");
|
||||
assert_eq!(status_json["currentRoot"], root.to_string_lossy().as_ref());
|
||||
assert!(status_json["freeBytes"].as_u64().unwrap_or(0) > 0);
|
||||
assert!(status_json["recoveryNote"].as_str().is_some_and(|s| !s.is_empty()));
|
||||
assert_eq!(status_json["migration"]["phase"], "idle");
|
||||
|
||||
let valid_target = root.parent().unwrap().join("fresh-target");
|
||||
let valid_view = validate_target_view(&platform, &root, &valid_target.to_string_lossy());
|
||||
assert!(valid_view["migration"]["validationError"].is_null());
|
||||
assert!(valid_view["migration"]["targetFreeBytes"].as_u64().unwrap_or(0) > 0);
|
||||
|
||||
let nested = validate_target_view(&platform, &root, &root.join("nested").to_string_lossy());
|
||||
assert!(nested["migration"]["validationError"].as_str().is_some_and(|s| !s.is_empty()));
|
||||
|
||||
let plan = plan_cleanup(&root, no_node).unwrap();
|
||||
let summary = plan.summary();
|
||||
let cats = summary["categories"].as_array().unwrap();
|
||||
assert_eq!(cats[0]["defaultSelected"], true);
|
||||
assert_eq!(cats[0]["selectedByDefault"], true);
|
||||
assert!(cats[0]["riskNote"].is_null(), "lossless category must not emit warning riskNote");
|
||||
assert!(cats[0]["description"].as_str().is_some_and(|s| !s.is_empty()));
|
||||
assert_eq!(cats[5]["defaultSelected"], false);
|
||||
assert_eq!(cats[5]["selectedByDefault"], false);
|
||||
assert!(cats[5]["riskNote"].as_str().is_some_and(|s| !s.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switch_returns_blocking_projects_on_guard_error_and_defer_marks_pointer() {
|
||||
let (_temp, from, migration) = fixture();
|
||||
let platform = from.clone();
|
||||
let data = app_dirs::DataDir { dir: Some(from.clone()), mode: Mode::Platform, warning: None };
|
||||
record(&platform, &migration).unwrap();
|
||||
|
||||
let guard_err = || Err("项目 A 正在制作中".to_owned());
|
||||
let emit: Sink = Box::new(|_| {});
|
||||
let out = handle_action_with(
|
||||
&platform,
|
||||
&data,
|
||||
"storage-migrate",
|
||||
&json!({"op":"switch"}),
|
||||
Host { guard: &guard_err, rebase: plain_rebase, node: no_node, emit },
|
||||
).unwrap();
|
||||
assert_eq!(out["requiresExit"], false);
|
||||
assert_eq!(out["migration"]["phase"], "ready_to_switch");
|
||||
assert_eq!(out["migration"]["blockingProjects"], json!(["项目 A 正在制作中"]));
|
||||
|
||||
let moved_root = from.parent().unwrap().join("moved-active");
|
||||
fs::create_dir_all(&moved_root).unwrap();
|
||||
let mig_done = Migration {
|
||||
id: Uuid::new_v4(),
|
||||
phase: Phase::Completed,
|
||||
from_path: from.clone(),
|
||||
to_path: moved_root.clone(),
|
||||
copied_bytes: 10,
|
||||
total_bytes: 10,
|
||||
message: "done".into(),
|
||||
};
|
||||
record(&platform, &mig_done).unwrap();
|
||||
write(&moved_root.join(MARKER), &mig_done.id).unwrap();
|
||||
let loc = Location {
|
||||
version: 1,
|
||||
root: moved_root.clone(),
|
||||
previous_root: Some(from.clone()),
|
||||
migration_id: mig_done.id,
|
||||
migrated_at: "2026-12-02T00:00:00Z".into(),
|
||||
app_version: "1.2612.109".into(),
|
||||
cleanup: false,
|
||||
cleanup_started: false,
|
||||
prompt_deferred: false,
|
||||
manifest_sha256: None,
|
||||
};
|
||||
write(&platform.join(POINTER), &loc).unwrap();
|
||||
|
||||
let moved_data = app_dirs::DataDir { dir: Some(moved_root.clone()), mode: Mode::Pointer, warning: None };
|
||||
let initial = status_payload(&platform, &moved_data, false, None).unwrap();
|
||||
assert_eq!(initial["autoOpenReleaseModal"], true);
|
||||
assert_eq!(initial["pendingOldRootCleanup"]["oldRoot"], from.to_string_lossy().as_ref());
|
||||
|
||||
let emit_defer: Sink = Box::new(|_| {});
|
||||
let defer = handle_action_with(
|
||||
&platform,
|
||||
&moved_data,
|
||||
"storage-migrate",
|
||||
&json!({"op":"defer-old-root"}),
|
||||
Host { guard: &|| Ok(()), rebase: plain_rebase, node: no_node, emit: emit_defer },
|
||||
).unwrap();
|
||||
assert_eq!(defer["deferred"], true);
|
||||
let after = status_payload(&platform, &moved_data, false, None).unwrap();
|
||||
assert_eq!(after["autoOpenReleaseModal"], false);
|
||||
assert!(after["pendingOldRootCleanup"].is_object());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -1158,6 +1158,8 @@ pub struct Workspace {
|
||||
template_workflow: Value,
|
||||
client_update: client_update::ClientUpdate,
|
||||
client_update_ui: client_update_ui::UpdateUi,
|
||||
storage_restart_requested: bool,
|
||||
storage_switch_pending: bool,
|
||||
product_production: Option<product_production::Run>,
|
||||
last_production_summary: Option<(u64, multi_project_state::ProjectRunVisualStatus)>,
|
||||
product_views: product_production::Views,
|
||||
@ -1717,6 +1719,8 @@ impl Workspace {
|
||||
template_workflow: Value::Null,
|
||||
client_update: client_update::ClientUpdate::default(),
|
||||
client_update_ui: client_update_ui::UpdateUi::default(),
|
||||
storage_restart_requested: false,
|
||||
storage_switch_pending: false,
|
||||
product_production: None,
|
||||
last_production_summary: None,
|
||||
product_views: product_production::Views::default(),
|
||||
@ -3134,6 +3138,18 @@ impl Workspace {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if matches!(
|
||||
method.as_str(),
|
||||
"storage-status"
|
||||
| "storage-scan"
|
||||
| "storage-cleanup"
|
||||
| "storage-migrate"
|
||||
| "storage-migrate-progress"
|
||||
| "storage-status-refresh"
|
||||
) {
|
||||
self.receive_storage_event(ctx, &method, result);
|
||||
return;
|
||||
}
|
||||
if method == "product-end-checkpoint" {
|
||||
if self.busy.as_deref() == Some("product-end-checkpoint") {
|
||||
self.busy = None;
|
||||
@ -3938,7 +3954,9 @@ impl Workspace {
|
||||
}
|
||||
|
||||
fn tick(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if std::mem::take(&mut self.client_update.restart_requested) {
|
||||
if std::mem::take(&mut self.client_update.restart_requested)
|
||||
|| std::mem::take(&mut self.storage_restart_requested)
|
||||
{
|
||||
app.explicit_exit = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
return;
|
||||
@ -5016,6 +5034,10 @@ pub(crate) fn cancel_exit(app: &mut PhotocraftApp) {
|
||||
let Some(mut workspace) = app.jiansun.take() else { return };
|
||||
if workspace.exit_admission_closed.swap(false, Ordering::AcqRel) {
|
||||
if let Some(cancel) = workspace.cancel_daemon_exit { cancel(); }
|
||||
workspace.storage_restart_requested = false;
|
||||
if std::mem::take(&mut workspace.storage_switch_pending) {
|
||||
let _ = workspace.tx.send(Request::Action("storage-migrate".into(), json!({"op": "cancel_switch"})));
|
||||
}
|
||||
workspace.busy = None;
|
||||
workspace.pi_run = None;
|
||||
workspace.pi_native = false;
|
||||
@ -5075,6 +5097,7 @@ pub fn prepare(app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
}
|
||||
w.header(app, ui);
|
||||
w.artifact_window(ui);
|
||||
w.storage_modals_ui(ui.ctx());
|
||||
workflow_export::show_psd_review(&mut w, app, ui.ctx());
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
project_file::show_project_save(&mut w, app, ui.ctx());
|
||||
@ -5106,6 +5129,32 @@ pub fn center(app: &mut PhotocraftApp, ui: &mut Ui) -> bool {
|
||||
.frame(egui::Frame::NONE.inner_margin(egui::Margin { left: 14, right: 14, top: 5, bottom: 5 }))
|
||||
// This row sits above the native canvas, whatever the host theme.
|
||||
.show(ui, |ui| stitch_ui::host_ground(ui, |ui| w.workspace_toolbar(app, ui)));
|
||||
let multi_vm = w.multi_project_view_model(app, ui.ctx());
|
||||
let dock_open = agent_selected(app) || projects_agent_dock(app);
|
||||
let show_strip = !dock_open && !multi_vm.global_runs.is_empty();
|
||||
let show_banner = multi_vm.viewing_differs_from_producing;
|
||||
if show_strip || show_banner {
|
||||
let reduced = w.reduce_motion;
|
||||
let action = egui::Panel::top("jiansun-multi-project-bar")
|
||||
.frame(egui::Frame::NONE.inner_margin(egui::Margin { left: 14, right: 14, top: 2, bottom: 4 }))
|
||||
.show(ui, |ui| {
|
||||
stitch_ui::host_ground(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
let mut action = None;
|
||||
if show_strip {
|
||||
action = agent_panel::multi_project_ui::global_task_strip(ui, &multi_vm, reduced);
|
||||
}
|
||||
if show_banner {
|
||||
action = action.or_else(|| agent_panel::multi_project_ui::viewing_producing_banner(ui, &multi_vm, reduced));
|
||||
}
|
||||
action
|
||||
})
|
||||
})
|
||||
.inner;
|
||||
if let Some(action) = action {
|
||||
w.handle_multi_project_action(app, ui.ctx(), action);
|
||||
}
|
||||
}
|
||||
}
|
||||
let used = w.material || w.library || (w.creation_open && w.creation_step != 3) || app.session.active().is_none();
|
||||
if w.material {
|
||||
@ -7779,4 +7828,47 @@ mod tests {
|
||||
assert_eq!(state["modelSettingsOpen"], true);
|
||||
assert_eq!(state["imageModel"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_events_update_machine_state_and_cancel_exit_notifies_backend() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":800,"height":800})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
app.sync_views();
|
||||
|
||||
let (tx, requests) = mpsc::channel();
|
||||
let (_events, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
let ctx = egui::Context::default();
|
||||
PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
let _ = requests.try_recv();
|
||||
|
||||
w.receive_json_event(&mut app, &ctx, "storage-status".into(), Ok(json!({
|
||||
"mode": "pointer",
|
||||
"currentRoot": "D:\\XiaoYiData",
|
||||
"statsReady": true,
|
||||
"totalBytes": 2048,
|
||||
"projectCount": 3,
|
||||
"freeBytes": 4096,
|
||||
"migration": {"phase": "ready_to_switch", "targetRoot": "E:\\XiaoYiNew", "totalBytes": 2048}
|
||||
})));
|
||||
let status_view = agent_panel::storage_settings_ui::with_machine_state(&ctx, |st| st.status.clone());
|
||||
assert_eq!(status_view.current_root, "D:\\XiaoYiData");
|
||||
assert_eq!(status_view.project_count, 3);
|
||||
assert_eq!(status_view.migration.phase, agent_panel::storage_settings_ui::MigrationPhase::ReadyToSwitch);
|
||||
|
||||
w.receive_json_event(&mut app, &ctx, "storage-migrate".into(), Ok(json!({
|
||||
"requiresExit": true,
|
||||
"phase": "switching"
|
||||
})));
|
||||
assert!(w.storage_restart_requested);
|
||||
assert!(w.storage_switch_pending);
|
||||
|
||||
w.exit_admission_closed.store(true, std::sync::atomic::Ordering::Release);
|
||||
app.jiansun = Some(w);
|
||||
cancel_exit(&mut app);
|
||||
let cancelled = requests.try_iter().any(|req| matches!(req, Request::Action(m, v) if m == "storage-migrate" && v["op"] == "cancel_switch"));
|
||||
assert!(cancelled);
|
||||
assert!(!app.jiansun.as_ref().unwrap().storage_restart_requested);
|
||||
}
|
||||
}
|
||||
|
||||
@ -4040,73 +4040,69 @@ impl Workspace {
|
||||
if let Some(injected) = multi_project_ui::snapshot(ctx) {
|
||||
return injected;
|
||||
}
|
||||
let section = match self.agent_page(app) {
|
||||
"brief" => multi_project_ui::WorkspaceSection::Brief,
|
||||
"canvas" | "professional" => multi_project_ui::WorkspaceSection::Canvas,
|
||||
_ => multi_project_ui::WorkspaceSection::Projects,
|
||||
let snap = self.multi_project_ui_snapshot(app);
|
||||
let active_section = match snap.active_section {
|
||||
super::multi_project_state::WorkspaceSectionKind::Projects => multi_project_ui::WorkspaceSection::Projects,
|
||||
super::multi_project_state::WorkspaceSectionKind::Brief => multi_project_ui::WorkspaceSection::Brief,
|
||||
super::multi_project_state::WorkspaceSectionKind::Canvas => multi_project_ui::WorkspaceSection::Canvas,
|
||||
};
|
||||
let project_id = self.project_context["localId"]
|
||||
.as_str()
|
||||
.or_else(|| self.project_context["id"].as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
let project_title = self.project_context["name"]
|
||||
.as_str()
|
||||
.or_else(|| self.creation_brief["name"].as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
let viewing_output_id = self.template_workflow["activeOutputId"]
|
||||
.as_str()
|
||||
.or_else(|| self.template_workflow["outputId"].as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
let viewing_output_label = viewing_output_id
|
||||
.as_deref()
|
||||
.map(|id| multi_project_ui::output_display_label(id).to_owned());
|
||||
let producing_output_id = self
|
||||
.product_production
|
||||
.as_ref()
|
||||
.and_then(|run| run.working_output())
|
||||
.and_then(|row| row["outputId"].as_str().map(str::to_owned));
|
||||
let producing_output_label = producing_output_id
|
||||
.as_deref()
|
||||
.map(|id| multi_project_ui::output_display_label(id).to_owned());
|
||||
let viewing_differs_from_producing = matches!(
|
||||
(&viewing_output_id, &producing_output_id),
|
||||
(Some(v), Some(p)) if v != p
|
||||
);
|
||||
let mut global_runs = Vec::new();
|
||||
if let Some(run) = self.product_production.as_ref()
|
||||
&& let Some(pid) = project_id.clone()
|
||||
{
|
||||
let status = if run.clock_paused() {
|
||||
multi_project_ui::MultiRunStatus::Paused
|
||||
let map_status = |status: &super::multi_project_state::ProjectRunVisualStatus| match status {
|
||||
super::multi_project_state::ProjectRunVisualStatus::Running => multi_project_ui::MultiRunStatus::Running,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Queued => multi_project_ui::MultiRunStatus::Queued,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Paused => multi_project_ui::MultiRunStatus::Paused,
|
||||
super::multi_project_state::ProjectRunVisualStatus::PartialDelivered => multi_project_ui::MultiRunStatus::PartialDelivered,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Completed => multi_project_ui::MultiRunStatus::Completed,
|
||||
super::multi_project_state::ProjectRunVisualStatus::Failed => multi_project_ui::MultiRunStatus::Failed,
|
||||
};
|
||||
let global_runs = snap
|
||||
.global_runs
|
||||
.into_iter()
|
||||
.map(|run| {
|
||||
let output_id = run.producing_output_id.unwrap_or_default();
|
||||
let output_label = if run.producing_output_label.is_empty() && !output_id.is_empty() {
|
||||
multi_project_ui::output_display_label(&output_id).to_owned()
|
||||
} else {
|
||||
run.producing_output_label
|
||||
};
|
||||
multi_project_ui::GlobalRunEntry {
|
||||
project_id: run.project_id,
|
||||
project_title: run.project_title,
|
||||
status: map_status(&run.status),
|
||||
producing_output_id: output_id,
|
||||
producing_output_label: output_label,
|
||||
progress_label: run.progress_label,
|
||||
elapsed_secs: run.elapsed_secs,
|
||||
active_slots: run.active_slots,
|
||||
has_attention: run.has_attention,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let active_project_title = (!snap.active_project_title.is_empty()).then_some(snap.active_project_title);
|
||||
let viewing_output_label = snap.viewing_output_id.as_deref().map(|id| {
|
||||
if snap.viewing_output_label.is_empty() {
|
||||
multi_project_ui::output_display_label(id).to_owned()
|
||||
} else {
|
||||
multi_project_ui::MultiRunStatus::Running
|
||||
};
|
||||
global_runs.push(multi_project_ui::GlobalRunEntry {
|
||||
project_id: pid,
|
||||
project_title: project_title.clone().unwrap_or_else(|| "当前项目".into()),
|
||||
status,
|
||||
producing_output_id: producing_output_id.clone().unwrap_or_default(),
|
||||
producing_output_label: producing_output_label.clone().unwrap_or_default(),
|
||||
progress_label: run.progress_label().unwrap_or_default(),
|
||||
elapsed_secs: run.elapsed().as_secs(),
|
||||
active_slots: self.production_workers().iter().filter(|w| w.active).count(),
|
||||
has_attention: self.pi_ui_waiting(),
|
||||
});
|
||||
}
|
||||
snap.viewing_output_label.clone()
|
||||
}
|
||||
});
|
||||
let producing_output_label = snap.producing_output_id.as_deref().map(|id| {
|
||||
if snap.producing_output_label.is_empty() {
|
||||
multi_project_ui::output_display_label(id).to_owned()
|
||||
} else {
|
||||
snap.producing_output_label.clone()
|
||||
}
|
||||
});
|
||||
multi_project_ui::MultiProjectViewModel {
|
||||
global_runs,
|
||||
max_concurrent: 2,
|
||||
active_project_id: project_id,
|
||||
active_project_title: project_title,
|
||||
active_section: section,
|
||||
viewing_output_id,
|
||||
max_concurrent: snap.max_concurrent,
|
||||
active_project_id: snap.active_project_id,
|
||||
active_project_title,
|
||||
active_section,
|
||||
viewing_output_id: snap.viewing_output_id,
|
||||
viewing_output_label,
|
||||
producing_output_id,
|
||||
producing_output_id: snap.producing_output_id,
|
||||
producing_output_label,
|
||||
viewing_differs_from_producing,
|
||||
viewing_differs_from_producing: snap.viewing_differs_from_producing,
|
||||
}
|
||||
}
|
||||
|
||||
@ -4118,29 +4114,43 @@ impl Workspace {
|
||||
) {
|
||||
match &action {
|
||||
multi_project_ui::MultiProjectAction::SwitchToProject(project_id) => {
|
||||
if let Some(item) = self
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.focus_project_by_id(app, project_id);
|
||||
} else if let Some(item) = self
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| p["id"].as_str() == Some(project_id.as_str()))
|
||||
.find(|p| p["localId"].as_str() == Some(project_id.as_str()) || p["id"].as_str() == Some(project_id.as_str()))
|
||||
.cloned()
|
||||
{
|
||||
self.handover();
|
||||
if let Err(error) = self.request_project_open(app, item) {
|
||||
self.error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::PauseProject(_) => {
|
||||
super::production_controls::queue_action(
|
||||
ctx,
|
||||
"production-stop",
|
||||
super::production_controls::stop_input(timeline::StopMode::Pause),
|
||||
);
|
||||
multi_project_ui::MultiProjectAction::PauseProject(project_id) => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.pause_project_run(app, project_id);
|
||||
} else {
|
||||
super::production_controls::queue_action(
|
||||
ctx,
|
||||
"production-stop",
|
||||
super::production_controls::stop_input(timeline::StopMode::Pause),
|
||||
);
|
||||
}
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::ResumeProject(_) => {
|
||||
self.resume_product_production(app);
|
||||
multi_project_ui::MultiProjectAction::ResumeProject(project_id) => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.resume_project_run(app, project_id);
|
||||
} else {
|
||||
self.resume_product_production(app);
|
||||
}
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::JumpToProducingOutput { project_id, .. } => {
|
||||
if self.open_project_index(app, project_id).is_some() {
|
||||
self.focus_project_by_id(app, project_id);
|
||||
}
|
||||
self.jump_to_producing_output(app);
|
||||
}
|
||||
multi_project_ui::MultiProjectAction::JumpToProducingOutput { .. } => {}
|
||||
}
|
||||
multi_project_ui::push_action(ctx, action);
|
||||
}
|
||||
@ -4167,6 +4177,13 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn storage_modals_ui(&mut self, ctx: &egui::Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let pass_id = Id::unique("xiaoyi-storage-modals-pass");
|
||||
let already_rendered = ctx.data(|data| data.get_temp::<u64>(pass_id) == Some(pass));
|
||||
if already_rendered {
|
||||
return;
|
||||
}
|
||||
ctx.data_mut(|data| data.insert_temp(pass_id, pass));
|
||||
let reduced = self.reduce_motion;
|
||||
let action = storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
storage_settings_ui::show_storage_modals(ctx, state, reduced)
|
||||
@ -4176,6 +4193,180 @@ impl Workspace {
|
||||
let _ = self.tx.send(Request::Action(method.into(), payload));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn receive_storage_event(&mut self, ctx: &egui::Context, method: &str, result: Result<Value, String>) {
|
||||
let apply_migration_patch = |mig: &mut storage_settings_ui::MigrationStateView, patch: &Value| {
|
||||
if let Some(phase) = patch["phase"].as_str() {
|
||||
mig.phase = storage_settings_ui::MigrationPhase::parse(phase);
|
||||
}
|
||||
if let Some(target) = patch["targetRoot"].as_str().filter(|s| !s.is_empty()) {
|
||||
mig.target_root = target.to_owned();
|
||||
}
|
||||
if patch.get("targetFreeBytes").is_some() {
|
||||
mig.target_free_bytes = patch["targetFreeBytes"].as_u64();
|
||||
}
|
||||
if let Some(req) = patch["requiredBytes"].as_u64() {
|
||||
mig.required_bytes = req;
|
||||
}
|
||||
if let Some(copied) = patch["copiedBytes"].as_u64() {
|
||||
mig.copied_bytes = copied;
|
||||
}
|
||||
if let Some(total) = patch["totalBytes"].as_u64() {
|
||||
mig.total_bytes = total;
|
||||
}
|
||||
if patch.get("validationError").is_some() {
|
||||
mig.validation_error = patch["validationError"].as_str().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
}
|
||||
if let Some(warnings) = patch["validationWarnings"].as_array() {
|
||||
mig.validation_warnings = warnings.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
|
||||
}
|
||||
if let Some(blocking) = patch["blockingProjects"].as_array() {
|
||||
mig.blocking_projects = blocking.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
|
||||
} else if !matches!(mig.phase, storage_settings_ui::MigrationPhase::ReadyToSwitch | storage_settings_ui::MigrationPhase::Idle) {
|
||||
mig.blocking_projects.clear();
|
||||
}
|
||||
if let Some(steps) = patch.get("switchSteps").or_else(|| patch.get("steps")).and_then(Value::as_array) {
|
||||
mig.switch_steps = steps
|
||||
.iter()
|
||||
.map(|row| storage_settings_ui::SwitchStep {
|
||||
id: row["id"].as_str().unwrap_or_default().to_owned(),
|
||||
label: row["label"].as_str().unwrap_or_default().to_owned(),
|
||||
state: storage_settings_ui::SwitchStepState::parse(
|
||||
row["state"].as_str().or_else(|| row["status"].as_str()).unwrap_or("pending"),
|
||||
),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
if patch.get("error").is_some() {
|
||||
mig.error = patch["error"].as_str().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
}
|
||||
if patch.get("rollbackNote").is_some() {
|
||||
mig.rollback_note = patch["rollbackNote"].as_str().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
}
|
||||
};
|
||||
|
||||
match method {
|
||||
"storage-status" => match result {
|
||||
Ok(val) if val.get("mode").is_some() => {
|
||||
let view = storage_settings_ui::StorageStatusView::from_json(&val);
|
||||
storage_settings_ui::set_status(ctx, view);
|
||||
if val["autoOpenReleaseModal"] == true {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.migrate_modal_open = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.status.status_text = Some(error);
|
||||
state.status.status_is_error = true;
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-status-refresh" => {}
|
||||
"storage-scan" => match result {
|
||||
Ok(val) => storage_settings_ui::set_scan(ctx, storage_settings_ui::StorageScanView::from_json(&val)),
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.scan.scanning = false;
|
||||
state.scan.error = Some(error);
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-cleanup" => match result {
|
||||
Ok(val) => {
|
||||
let mut scan = storage_settings_ui::StorageScanView::from_json(&val);
|
||||
scan.scanning = false;
|
||||
scan.cleanup_running = false;
|
||||
storage_settings_ui::set_scan(ctx, scan);
|
||||
}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.scan.cleanup_running = false;
|
||||
state.scan.cleanup_result = Some(storage_settings_ui::CleanupResultView {
|
||||
freed_bytes: 0,
|
||||
message: String::new(),
|
||||
error: Some(error),
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-migrate" => match result {
|
||||
Ok(val) => {
|
||||
if val["requiresExit"] == true {
|
||||
self.storage_switch_pending = true;
|
||||
self.storage_restart_requested = true;
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val);
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Switching;
|
||||
state.migrate_modal_open = true;
|
||||
});
|
||||
} else if let Some(picked) = val["pickedRoot"].as_str() {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.target_input = picked.to_owned();
|
||||
if val["migration"].is_object() {
|
||||
apply_migration_patch(&mut state.status.migration, &val["migration"]);
|
||||
}
|
||||
});
|
||||
} else if val["migration"].is_object() {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val["migration"]);
|
||||
});
|
||||
} else if val["deferred"] == true {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.migrate_modal_open = false;
|
||||
});
|
||||
} else if val["cancelled"] == true {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
if state.status.migration.phase.is_non_closable() {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::ReadyToSwitch;
|
||||
}
|
||||
});
|
||||
} else if val["phase"].is_string() {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val);
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
if matches!(
|
||||
state.status.migration.phase,
|
||||
storage_settings_ui::MigrationPhase::Idle | storage_settings_ui::MigrationPhase::Validating
|
||||
) {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Idle;
|
||||
state.status.migration.validation_error = Some(error);
|
||||
} else {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed;
|
||||
state.status.migration.error = Some(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
"storage-migrate-progress" => match result {
|
||||
Ok(val) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
apply_migration_patch(&mut state.status.migration, &val);
|
||||
if state.target_input.is_empty() && !state.status.migration.target_root.is_empty() {
|
||||
state.target_input = state.status.migration.target_root.clone();
|
||||
}
|
||||
if state.status.migration.phase.is_non_closable() {
|
||||
state.migrate_modal_open = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
storage_settings_ui::with_machine_state(ctx, |state| {
|
||||
state.status.migration.phase = storage_settings_ui::MigrationPhase::Failed;
|
||||
state.status.migration.error = Some(error);
|
||||
});
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Experimental, local-acceptance-only opt-in. Until device-loss, resource
|
||||
|
||||
@ -355,7 +355,6 @@ impl Workspace {
|
||||
.unwrap_or(project).to_owned()
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // Consumed by the workspace UI in the integration branch.
|
||||
pub(super) fn multi_project_ui_snapshot(&self, app: &PhotocraftApp) -> MultiProjectUiSnapshot {
|
||||
let mut global_runs = Vec::new();
|
||||
let mut add_run = |run: Option<&Run>, context: &Value, busy: Option<&str>, progress: &Value| {
|
||||
@ -403,7 +402,7 @@ impl Workspace {
|
||||
let producing_output_label = producing.map_or_else(String::new, |run| run.producing_output_label.clone());
|
||||
MultiProjectUiSnapshot {
|
||||
global_runs,
|
||||
max_concurrent: 1,
|
||||
max_concurrent: if std::env::var("JIANSUN_PARALLEL_PROJECTS").as_deref() == Ok("3") { 3 } else { 2 },
|
||||
active_project_id,
|
||||
active_project_title,
|
||||
active_section: if self.library || self.material || active.is_none() { WorkspaceSectionKind::Projects }
|
||||
@ -414,7 +413,6 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn focus_project_by_id(&mut self, app: &mut PhotocraftApp, project_id: &str) {
|
||||
if !self.authority_active() { return; }
|
||||
if let Some(index) = self.open_project_index(app, project_id) {
|
||||
@ -422,7 +420,6 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn pause_project_run(&mut self, app: &mut PhotocraftApp, project_id: &str) {
|
||||
if !self.authority_active() { return; }
|
||||
let Some(index) = self.open_project_index(app, project_id) else { return; };
|
||||
@ -437,7 +434,17 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(super) fn resume_project_run(&mut self, app: &mut PhotocraftApp, project_id: &str) {
|
||||
if !self.authority_active() { return; }
|
||||
let Some(index) = self.open_project_index(app, project_id) else { return; };
|
||||
let doc = app.session.documents()[index].doc.id.0;
|
||||
if self.observed_doc == Some(doc) {
|
||||
self.resume_product_production(app);
|
||||
} else {
|
||||
self.with_parked_project(app, doc, |w, app| w.resume_product_production(app));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn jump_to_producing_output(&mut self, app: &mut PhotocraftApp) {
|
||||
let Some(output) = self.product_production.as_ref().and_then(Run::working_output) else { return; };
|
||||
match self.request_product_view(app, &output) {
|
||||
|
||||
@ -2984,6 +2984,65 @@ mod tests {
|
||||
assert_eq!(checkpoints, HashSet::from([first, second]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_project_view_model_reports_parallel_limit_and_routes_switch_without_handover() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width":800,"height":800,"name":"项目甲"})).unwrap();
|
||||
let first = session.active().unwrap().doc.id.0;
|
||||
session.execute("file.new", json!({"width":800,"height":800,"name":"项目乙"})).unwrap();
|
||||
let second = session.active().unwrap().doc.id.0;
|
||||
session.set_active(0);
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
app.sync_views();
|
||||
|
||||
let (tx, _requests) = mpsc::channel();
|
||||
let (_events, rx) = mpsc::channel();
|
||||
let mut w = Workspace::new(tx, rx);
|
||||
w.account = json!({"id":"owner"});
|
||||
w.library = false;
|
||||
w.observed_doc = Some(first);
|
||||
w.loaded_draft = Some(first);
|
||||
w.owner_doc = Some(first);
|
||||
w.open_projects.insert(first, w.local_identity("proj-a"));
|
||||
w.open_projects.insert(second, w.local_identity("proj-b"));
|
||||
let stage = Stage { output: "sku_images".into(), variant: "wood".into() };
|
||||
let mut run_a = Run::new(
|
||||
first,
|
||||
w.local_identity("proj-a"),
|
||||
json!("ws-a"),
|
||||
vec![stage.clone()],
|
||||
None,
|
||||
Phase::Agent,
|
||||
);
|
||||
run_a.bound = Some(stage.clone());
|
||||
w.product_production = Some(run_a);
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
let vm_before = w.multi_project_view_model(&app, &ctx);
|
||||
assert!(vm_before.max_concurrent >= 2);
|
||||
assert_eq!(vm_before.global_runs.len(), 1);
|
||||
assert_eq!(vm_before.active_project_id.as_deref(), Some("proj-a"));
|
||||
|
||||
w.handle_multi_project_action(
|
||||
&mut app,
|
||||
&ctx,
|
||||
crate::jiansun::agent_panel::multi_project_ui::MultiProjectAction::SwitchToProject("proj-b".into()),
|
||||
);
|
||||
assert_eq!(app.session.active().unwrap().doc.id.0, second);
|
||||
w.product_production = Some(Run::new(
|
||||
second,
|
||||
w.local_identity("proj-b"),
|
||||
json!("ws-b"),
|
||||
vec![stage],
|
||||
None,
|
||||
Phase::Agent,
|
||||
));
|
||||
let vm_both = w.multi_project_view_model(&app, &ctx);
|
||||
assert_eq!(vm_both.global_runs.len(), 2);
|
||||
assert_eq!(vm_both.active_project_id.as_deref(), Some("proj-b"));
|
||||
assert!(w.with_parked_project(&mut app, first, |parked, _| parked.product_production.is_some()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_tab_cannot_take_the_hidden_worker() {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
|
||||
@ -151,12 +151,16 @@ impl Workspace {
|
||||
format!("{}|{}|{local}", self.origin, self.account["id"].as_str().unwrap_or("guest"))
|
||||
}
|
||||
pub(super) fn new_project_button(&mut self, app: &mut PhotocraftApp, ui: &mut Ui) {
|
||||
let new = stitch_ui::action_button(ui, "新建项目", stitch_ui::ButtonRole::Primary, self.busy.is_none());
|
||||
let can_create = self.busy.is_none() || self.product_production.is_some();
|
||||
let new = stitch_ui::action_button(ui, "新建项目", stitch_ui::ButtonRole::Primary, can_create);
|
||||
self.project_geometry["new"] = agent_panel::rect_value(new.rect);
|
||||
if new.clicked() {
|
||||
if self.busy.is_some() {
|
||||
if !can_create {
|
||||
self.project_list_error = "请等待当前操作完成".into();
|
||||
} else {
|
||||
if self.product_production.is_some() && self.park_project_projection() {
|
||||
self.project_view_parked = true;
|
||||
}
|
||||
self.begin_staged_new_project(app);
|
||||
}
|
||||
}
|
||||
@ -439,7 +443,7 @@ impl Workspace {
|
||||
ui.spacing_mut().item_spacing.x = 16.0;
|
||||
for (column, item) in items.iter().skip(row * cols).take(cols).enumerate() {
|
||||
let background = backgrounds[row * cols + column - first];
|
||||
ui.push_id((item["source"].as_str(), item["id"].as_str()), |ui| self.project_tile(app, ui, item, tile_width, background));
|
||||
ui.push_id((item["source"].as_str(), item["id"].as_str()), |ui| self.project_tile(app, ui, item, tile_width, background, &multi_vm));
|
||||
}
|
||||
});
|
||||
}
|
||||
@ -453,7 +457,7 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
fn project_tile(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, item: &Value, width: f32, background: egui::layers::ShapeIdx) {
|
||||
fn project_tile(&mut self, app: &mut PhotocraftApp, ui: &mut Ui, item: &Value, width: f32, background: egui::layers::ShapeIdx, multi_vm: &agent_panel::multi_project_ui::MultiProjectViewModel) {
|
||||
let t = Tokens::get(ui.ctx()).agent();
|
||||
let k = key(item);
|
||||
let native = item["source"] == "native";
|
||||
@ -464,7 +468,7 @@ impl Workspace {
|
||||
let (shell, _) = ui.allocate_exact_size(vec2(width, preview_height + 82.0), Sense::hover());
|
||||
let rect = egui::Rect::from_min_size(shell.min, vec2(width, preview_height));
|
||||
let response = ui.interact(shell, ui.scope_id().with("project-open"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
let enabled = self.busy.is_none();
|
||||
let enabled = self.busy.is_none() || self.product_production.is_some();
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button,enabled,"打开项目"));
|
||||
let hover = stitch_ui::morph_value(ui.ctx(),ui.scope_id().with("project-hover"),enabled && (response.hovered() || response.has_focus()),self.reduce_motion);
|
||||
let stroke_width = if cloud { 2.0 / ui.ctx().pixels_per_point() } else { 1.0 / ui.ctx().pixels_per_point() };
|
||||
@ -487,12 +491,11 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
ui.painter().rect_stroke(shell,16.0,Stroke::new(stroke_width,t.card_border.lerp_to_gamma(t.text_dim,hover*0.65)),egui::StrokeKind::Inside);
|
||||
let live_run = item["id"]
|
||||
let live_run = item["localId"]
|
||||
.as_str()
|
||||
.and_then(|id| {
|
||||
agent_panel::multi_project_ui::snapshot(ui.ctx())
|
||||
.and_then(|vm| vm.run_for_project(id).cloned())
|
||||
});
|
||||
.and_then(|id| multi_vm.run_for_project(id))
|
||||
.or_else(|| item["id"].as_str().and_then(|id| multi_vm.run_for_project(id)))
|
||||
.cloned();
|
||||
let (state, badge_rect) = if let Some(run) = &live_run {
|
||||
let rect = agent_panel::multi_project_ui::paint_project_live_badge(ui, rect, run, self.reduce_motion);
|
||||
(run.status.label(), rect)
|
||||
@ -572,7 +575,7 @@ impl Workspace {
|
||||
if let Err(error)=self.request_cloud_update(app,item) {self.project_list_error=error;}
|
||||
} else if opening && enabled && !deleting {
|
||||
egui::Popup::close_id(ui.ctx(),menu.id.with("popup"));
|
||||
self.handover();if let Err(error)=self.request_project_open(app,item.clone()) {self.project_list_error=error;}
|
||||
if let Err(error)=self.request_project_open(app,item.clone()) {self.project_list_error=error;}
|
||||
}
|
||||
if let Some(tiles)=self.project_geometry["tiles"].as_array_mut() {
|
||||
tiles.push(json!({"id":item["id"],"source":item["source"],"open":agent_panel::rect_value(rect),"card":agent_panel::rect_value(shell),"hover":hover,"menu":agent_panel::rect_value(menu.rect),"delete":delete_rect.map(agent_panel::rect_value),"deleteEnabled":delete_enabled,"deleteBlockedReason":blocked,"hasCover":self.project_covers.contains_key(&key(item)),"cloud":cloud,"borderPhysicalPixels":if cloud {2.0} else {1.0},"state":state,"badge":agent_panel::rect_value(badge_rect),"cloudUpdate":update.as_ref().map(|b|agent_panel::rect_value(b.rect)),"cloudUpdateEnabled":update.as_ref().is_some_and(|b|b.enabled())}));
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
//! State lives in a machine-scoped context slot so switching accounts never
|
||||
//! resets storage settings or active migration progress.
|
||||
|
||||
#[cfg_attr(not(test), allow(unused_imports))]
|
||||
use super::super::stitch_ui::{
|
||||
self, ButtonRole, FocusRing, OverlayVisual, StatusTone, SurfaceRole,
|
||||
};
|
||||
@ -207,7 +208,6 @@ impl Default for StorageStatusView {
|
||||
}
|
||||
|
||||
impl StorageStatusView {
|
||||
#[allow(dead_code, reason = "跨轨契约 JSON 解析入口,供集成阶段消费 storage-status 回执")]
|
||||
pub(crate) fn from_json(value: &Value) -> Self {
|
||||
let mig = &value["migration"];
|
||||
let steps = mig["switchSteps"]
|
||||
@ -316,7 +316,6 @@ impl StorageScanView {
|
||||
self.items.iter().filter(|item| !item.lossless).map(|item| item.bytes).sum()
|
||||
}
|
||||
|
||||
#[allow(dead_code, reason = "跨轨契约 JSON 解析入口,供集成阶段消费 storage-scan 回执")]
|
||||
pub(crate) fn from_json(value: &Value) -> Self {
|
||||
let items = value["categories"]
|
||||
.as_array()
|
||||
@ -415,7 +414,6 @@ pub(crate) fn with_machine_state<R>(ctx: &egui::Context, f: impl FnOnce(&mut Sto
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(dead_code, reason = "跨轨契约写入入口,供集成阶段同步 storage-status 状态")]
|
||||
pub(crate) fn set_status(ctx: &egui::Context, status: StorageStatusView) {
|
||||
with_machine_state(ctx, |state| {
|
||||
if state.target_input.is_empty() && !status.migration.target_root.is_empty() {
|
||||
@ -428,7 +426,6 @@ pub(crate) fn set_status(ctx: &egui::Context, status: StorageStatusView) {
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(dead_code, reason = "跨轨契约写入入口,供集成阶段同步 storage-scan 状态")]
|
||||
pub(crate) fn set_scan(ctx: &egui::Context, scan: StorageScanView) {
|
||||
with_machine_state(ctx, |state| {
|
||||
state.scan = scan;
|
||||
@ -778,6 +775,7 @@ fn render_migrate_select_contents(
|
||||
let browse_w = 104.0;
|
||||
let field_w = (ui.available_width() - browse_w - space::SM).max(120.0);
|
||||
let validating = state.status.migration.phase == MigrationPhase::Validating;
|
||||
let prev_target = state.target_input.clone();
|
||||
ui.allocate_ui_with_layout(vec2(field_w, control::DEFAULT), Layout::top_down(Align::Min), |ui| {
|
||||
stitch_ui::halo_field(ui, Id::unique("storage-target-input"), None, reduced, |ui| {
|
||||
let edit = stitch_ui::text_input(&mut state.target_input, "例如 D:\\XiaoYiData", false)
|
||||
@ -789,6 +787,11 @@ fn render_migrate_select_contents(
|
||||
resp
|
||||
});
|
||||
});
|
||||
if state.target_input != prev_target {
|
||||
state.status.migration.validation_error = None;
|
||||
state.status.migration.validation_warnings.clear();
|
||||
state.status.migration.target_free_bytes = None;
|
||||
}
|
||||
if stitch_ui::action_button(ui, "选择目录…", ButtonRole::Secondary, !validating).clicked() {
|
||||
*action = Some(StorageAction::PickMigrationTarget);
|
||||
}
|
||||
|
||||
@ -336,6 +336,14 @@ impl Workspace {
|
||||
ui.set_width(inner_w);
|
||||
ui.spacing_mut().item_spacing.y = space::SM;
|
||||
|
||||
let multi_vm = self.multi_project_view_model(app, ui.ctx());
|
||||
if !multi_vm.global_runs.is_empty() {
|
||||
if let Some(action) = super::agent_panel::multi_project_ui::global_task_strip(ui, &multi_vm, self.reduce_motion) {
|
||||
self.handle_multi_project_action(app, ui.ctx(), action);
|
||||
}
|
||||
stitch_ui::divider(ui);
|
||||
}
|
||||
|
||||
// Header
|
||||
ui.horizontal(|ui| {
|
||||
stitch_kit::label(ui, "建项协作者", Type::Heading, Tone::Active);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user