feat(studio): deliver asset authoring and automation workflows
Add shared human/task asset batches with reviewed atomic publication, explicit reference rebinds, ownership inspection and qualified glyph/scene budgets. Expose the same authoring and capacity results through Assets and MCP. Deliver isolated guest test targets, retained visual evidence and immutable runtime lifecycle/control observations. Preserve provider qualification and installed authoring examples alongside the completed discussion lessons. Close AGD-106 coordination and the delivered discussion workflows through housekeeping, updating lesson references and preserving qualification limits. Sound remains outside the asset delivery wave. Validation: 579 module tests and 31 additional desktop, process and installed checks passed; native glyph/scene 16/17 boundaries qualified. Discussion validation passed after housekeeping.
This commit is contained in:
-40
@@ -1,40 +0,0 @@
|
||||
package p.studio.ui.javafx.diagnostics;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.net.URI;
|
||||
import java.util.*;
|
||||
|
||||
/** Read-only navigation: admission and revision checks precede any range selection. */
|
||||
public final class DiagnosticNavigation {
|
||||
private DiagnosticNavigation() {}
|
||||
public record Source(String status, Path path, String text, int start, int end) {}
|
||||
public static Source read(Path root, Map<String, Object> origin) {
|
||||
try {
|
||||
if (!(origin.get("uri") instanceof String uri) || !uri.startsWith("file:"))
|
||||
return new Source("Source unavailable; no admitted physical URI", null, "", 0, 0);
|
||||
var path = Path.of(URI.create(uri)).toRealPath();
|
||||
if (!path.startsWith(root.toRealPath()) || !Files.isRegularFile(path))
|
||||
return new Source("Source unavailable outside project admission", null, "", 0, 0);
|
||||
byte[] bytes;
|
||||
try (var input = Files.newInputStream(path)) { bytes = input.readNBytes(4 * 1024 * 1024 + 1); }
|
||||
if (bytes.length > 4 * 1024 * 1024) return new Source("Source exceeds navigation limit", null, "", 0, 0);
|
||||
var text = java.nio.charset.StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString();
|
||||
var digest = HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
if (origin.get("source") instanceof Map<?, ?> identity && "mixed".equals(identity.get("revisionAvailability")))
|
||||
return new Source("Mixed analysis revisions; showing current source read-only", path, text, 0, 0);
|
||||
if (!digest.equals(origin.get("revision")))
|
||||
return new Source(origin.get("revision") == null ? "Revision unavailable; showing current source read-only" : "Stale diagnostic; showing changed source read-only", path, text, 0, 0);
|
||||
if (!(origin.get("range") instanceof Map<?, ?> range)) return new Source("Current source; diagnostic has no range", path, text, 0, 0);
|
||||
int start = offset(text, (Map<?, ?>) range.get("start")), end = offset(text, (Map<?, ?>) range.get("end"));
|
||||
if (start < 0 || end < start) return new Source("Current source; range unavailable", path, text, 0, 0);
|
||||
return new Source("Current source · read-only", path, text, start, end);
|
||||
} catch (Exception unavailable) { return new Source("Source unavailable", null, "", 0, 0); }
|
||||
}
|
||||
private static int offset(String text, Map<?, ?> position) {
|
||||
if (position == null || !(position.get("line") instanceof Number line) || !(position.get("character") instanceof Number character)) return -1;
|
||||
int start = 0;
|
||||
for (int i = 0; i < line.intValue(); i++) { start = text.indexOf('\n', start); if (start < 0) return -1; start++; }
|
||||
int end = text.indexOf('\n', start); if (end < 0) end = text.length();
|
||||
return character.intValue() < 0 || start + character.intValue() > end ? -1 : start + character.intValue();
|
||||
}
|
||||
}
|
||||
+21
-7
@@ -8,14 +8,17 @@ import javafx.scene.Scene;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import p.studio.api.diagnostic.DiagnosticSources;
|
||||
|
||||
/** UI of the canonical bounded public view, shared by DEV and build. */
|
||||
public final class DiagnosticResultsPane extends VBox {
|
||||
private final Path root;
|
||||
private final DiagnosticSources sources;
|
||||
private Map<String, Object> displayed = Map.of();
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
public DiagnosticResultsPane(Path root) { super(8); this.root = root; setId("diagnostic-results"); setFillWidth(true); setMaxWidth(Double.MAX_VALUE); }
|
||||
public DiagnosticResultsPane(Path root) { this(root, DiagnosticSources.unavailable()); }
|
||||
public DiagnosticResultsPane(Path root, DiagnosticSources sources) {
|
||||
super(8); this.sources = Objects.requireNonNull(sources);
|
||||
setId("diagnostic-results"); setFillWidth(true); setMaxWidth(Double.MAX_VALUE);
|
||||
}
|
||||
public void show(Map<String, Object> view) {
|
||||
if (displayed.equals(view)) return;
|
||||
displayed = view; getChildren().clear();
|
||||
@@ -63,7 +66,7 @@ public final class DiagnosticResultsPane extends VBox {
|
||||
var button = new Button(label); button.setDisable(origin.get("uri") == null);
|
||||
button.setOnAction(event -> {
|
||||
button.setDisable(true);
|
||||
CompletableFuture.supplyAsync(() -> DiagnosticNavigation.read(root, origin)).thenAccept(source -> Platform.runLater(() -> {
|
||||
CompletableFuture.supplyAsync(() -> sources.read(origin)).thenAccept(source -> Platform.runLater(() -> {
|
||||
button.setDisable(false);
|
||||
var text = new TextArea(source.text()); text.setEditable(false); text.selectRange(source.start(), source.end());
|
||||
var window = new Stage(); window.setTitle(source.status());
|
||||
@@ -74,7 +77,18 @@ public final class DiagnosticResultsPane extends VBox {
|
||||
}
|
||||
private static String count(Map<?, ?> counts, String key) { return Objects.toString(counts.get(key), "unknown"); }
|
||||
private static String pretty(Object value) {
|
||||
try { return JSON.writerWithDefaultPrettyPrinter().writeValueAsString(value); }
|
||||
catch (Exception impossible) { throw new IllegalArgumentException("Invalid diagnostic JSON", impossible); }
|
||||
var text = new StringBuilder(); appendValue(text, value, ""); return text.toString();
|
||||
}
|
||||
private static void appendValue(StringBuilder text, Object value, String indent) {
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
map.forEach((key, child) -> {
|
||||
text.append(indent).append(key).append(": ");
|
||||
if (child instanceof Map<?, ?> || child instanceof List<?>) {
|
||||
text.append('\n'); appendValue(text, child, indent + " ");
|
||||
} else text.append(Objects.toString(child, "null")).append('\n');
|
||||
});
|
||||
} else if (value instanceof List<?> list) {
|
||||
for (var child : list) { text.append(indent).append("• "); appendValue(text, child, indent + " "); }
|
||||
} else text.append(Objects.toString(value, "null")).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import lombok.Getter;
|
||||
|
||||
public enum I18n {
|
||||
WORKSPACE_DEV("workspace.dev"),
|
||||
WORKSPACE_TESTS("workspace.tests"),
|
||||
DEV_MCP_WAITING("dev.mcpWaiting"), DEV_MCP_CONNECTED("dev.mcpConnected"), DEV_MCP_RECONNECTING("dev.mcpReconnecting"),
|
||||
DEV_GRANT("dev.grant"), DEV_RECLAIM("dev.reclaim"), DEV_COPY_CONFIG("dev.copyConfig"),
|
||||
DEV_DISCARD_GAME_DATA("dev.discardGameData"), DEV_DISCARD_GAME_DATA_CONFIRM("dev.discardGameDataConfirm"),
|
||||
@@ -376,6 +377,10 @@ public enum I18n {
|
||||
ASSETS_PACK_WIZARD_ERROR_VALIDATION("assets.packWizard.error.validation"),
|
||||
ASSETS_PACK_WIZARD_ERROR_PACK("assets.packWizard.error.pack"),
|
||||
WORKSPACE_DEBUG("workspace.debug"),
|
||||
DEV_OBSERVATIONS("dev.observations"),
|
||||
DEV_CONTROL_OBSERVATION("dev.controlObservation"),
|
||||
DEV_RUNTIME_CURRENT("dev.runtimeCurrent"),
|
||||
DEV_RUNTIME_FINAL("dev.runtimeFinal"),
|
||||
|
||||
|
||||
;
|
||||
|
||||
@@ -95,6 +95,7 @@ public final class MainView extends BorderPane {
|
||||
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
|
||||
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
|
||||
tiledAssetService, sceneBankWorkflow);
|
||||
projectSession.assetAuthoring().ifPresent(assetWorkspace::setAssetAuthoring);
|
||||
animationOrigins=eventBus.subscribe(p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent.class,event->{
|
||||
if(!event.projectRoot().toAbsolutePath().normalize().equals(projectReference.rootPath()))return;
|
||||
javafx.application.Platform.runLater(()->{if(!closed){selectWorkspace(WorkspaceId.ASSETS);assetWorkspace.openAnimationOrigin(event.assetUuid(),event.jsonPointer());}});
|
||||
@@ -103,9 +104,12 @@ public final class MainView extends BorderPane {
|
||||
assetWorkspace.restoreProjectLocalState(persistedState);
|
||||
assetWorkspace.setStateChangedAction(this::persistProjectLocalState);
|
||||
host.register(new DebugWorkspace(projectReference, projectSession.executionSession(), i18n, eventBus));
|
||||
final var shipperWorkspace = new ShipperWorkspace(projectReference, shipper, i18n, eventBus);
|
||||
final var shipperWorkspace = new ShipperWorkspace(projectReference, shipper, i18n, eventBus, projectSession.diagnosticSources());
|
||||
host.register(shipperWorkspace);
|
||||
host.register(new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus, connectionGuide));
|
||||
var devWorkspace = new p.studio.ui.javafx.workspaces.dev.DevWorkspace(projectReference, projectSession.automation(), i18n, eventBus, connectionGuide, projectSession.diagnosticSources());
|
||||
projectSession.evidenceTools().ifPresent(devWorkspace::setEvidenceTools);
|
||||
host.register(devWorkspace);
|
||||
projectSession.guestTestTools().ifPresent(tests->host.register(new p.studio.ui.javafx.workspaces.tests.TestsWorkspace(projectSession,tests,executor,eventBus)));
|
||||
documentRegistration = projectSession.automation().registerDocuments(assetWorkspace.documentHandoff());
|
||||
p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.install(assetWorkspace.rootNode(),
|
||||
() -> projectSession.automation().snapshot().manualAllowed());
|
||||
@@ -114,7 +118,8 @@ public final class MainView extends BorderPane {
|
||||
controlSubscription = projectSession.automation().subscribe(snapshot -> {
|
||||
Runnable update = () -> {
|
||||
if (closed) return;
|
||||
runSurface.setDisable(!snapshot.manualAllowed());
|
||||
assetWorkspace.manualAllowed(snapshot.manualAllowed());
|
||||
runSurface.setDisable(!snapshot.manualAllowed() || snapshot.manualOperations()>0 || projectSession.automation().runtimeAttached());
|
||||
p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.project(assetWorkspace.rootNode(), snapshot.manualAllowed());
|
||||
p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.project(shipperWorkspace.rootNode(), snapshot.manualAllowed());
|
||||
};
|
||||
@@ -126,8 +131,9 @@ public final class MainView extends BorderPane {
|
||||
new StudioWorkspaceRailItem<>(WorkspaceId.ASSETS, "📦", i18n.bind(I18n.WORKSPACE_ASSETS)),
|
||||
new StudioWorkspaceRailItem<>(WorkspaceId.DEBUG, "🎮", i18n.bind(I18n.WORKSPACE_DEBUG)),
|
||||
new StudioWorkspaceRailItem<>(WorkspaceId.DEV, "◇", i18n.bind(I18n.WORKSPACE_DEV)),
|
||||
new StudioWorkspaceRailItem<>(WorkspaceId.TESTS, "✓", i18n.bind(I18n.WORKSPACE_TESTS)),
|
||||
new StudioWorkspaceRailItem<>(WorkspaceId.SHIPPER, "⚙️", i18n.bind(I18n.WORKSPACE_SHIPPER))
|
||||
),
|
||||
).stream().filter(item->item.id()!=WorkspaceId.TESTS||projectSession.guestTestTools().isPresent()).toList(),
|
||||
this::loadWorkspace);
|
||||
setLeft(workspaceRail);
|
||||
setCenter(host);
|
||||
@@ -197,7 +203,8 @@ public final class MainView extends BorderPane {
|
||||
return WorkspaceId.ASSETS;
|
||||
}
|
||||
try {
|
||||
return WorkspaceId.valueOf(openShellState.selectedWorkspaceId());
|
||||
var selected=WorkspaceId.valueOf(openShellState.selectedWorkspaceId());
|
||||
return selected==WorkspaceId.TESTS&&projectSession.guestTestTools().isEmpty()?WorkspaceId.ASSETS:selected;
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return WorkspaceId.ASSETS;
|
||||
}
|
||||
|
||||
+2
-1
@@ -4,5 +4,6 @@ public enum WorkspaceId {
|
||||
ASSETS,
|
||||
SHIPPER,
|
||||
DEBUG,
|
||||
DEV
|
||||
DEV,
|
||||
TESTS
|
||||
}
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package p.studio.ui.javafx.workspaces.assets;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.FileChooser;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/** Shared budget/ownership inspection and source selection inside the existing Assets workspace. */
|
||||
final class AssetAuthoringPane extends VBox {
|
||||
private final ProjectReference project;private final AssetAuthoringService service;private final Executor executor;private final Runnable changed;
|
||||
private final Label summary=new Label("Loading asset budget…");private final TextArea facts=new TextArea();private final ComboBox<AssetSummary> bank=new ComboBox<>();
|
||||
private final Button importPng=new Button("Import PNG"),ownership=new Button("Declare output"),refresh=new Button("Refresh budget");
|
||||
AssetAuthoringPane(ProjectReference project,AssetAuthoringService service,Executor executor,Runnable changed){
|
||||
super(6);this.project=project;this.service=service;this.executor=executor;this.changed=changed;setId("assets-shared-authoring");
|
||||
importPng.setId("assets-import-png");ownership.setId("assets-declare-output");refresh.setId("assets-refresh-budget");for(var button:List.of(importPng,ownership,refresh))button.getStyleClass().addAll("studio-button","studio-button-secondary");summary.setMinHeight(javafx.scene.layout.Region.USE_PREF_SIZE);summary.setMaxWidth(Double.MAX_VALUE);facts.setEditable(false);facts.setWrapText(true);facts.setPrefRowCount(7);facts.setId("assets-budget-facts");summary.setWrapText(true);summary.setId("assets-budget-summary");
|
||||
bank.setPrefWidth(220);bank.setConverter(new javafx.util.StringConverter<>(){public String toString(AssetSummary a){return a==null?"Select bank":a.name()+" ("+a.family()+")";}public AssetSummary fromString(String s){throw new UnsupportedOperationException();}});
|
||||
ManualProjectUiGuard.allowReadOnly(refresh);ManualProjectUiGuard.allowReadOnly(bank);ManualProjectUiGuard.allowReadOnly(facts);
|
||||
refresh.setOnAction(e->refresh());bank.valueProperty().addListener((o,a,b)->refreshFacts());
|
||||
importPng.setOnAction(e->importPng());ownership.setOnAction(e->declareOutput());
|
||||
var details=new TitledPane("Capacity, dependencies and diagnostics",facts);details.setExpanded(false);ManualProjectUiGuard.allowReadOnly(details);
|
||||
getChildren().addAll(summary,new HBox(8,bank,importPng,ownership,refresh),details);refresh();
|
||||
}
|
||||
void manualAllowed(boolean allowed){importPng.setDisable(!allowed);ownership.setDisable(!allowed);}
|
||||
void refresh(){var selected=bank.getValue();executor.execute(()->{try{var catalog=service.catalog(project.rootPath(),null);var budget=service.budget(project.rootPath(),null);Platform.runLater(()->{bank.getItems().setAll(catalog);if(selected!=null)bank.getItems().stream().filter(a->a.reference().equals(selected.reference())).findFirst().ifPresent(bank::setValue);summary.setText(budgetText(budget));refreshFacts();});}catch(Exception e){Platform.runLater(()->summary.setText(e.getMessage()));}});}
|
||||
static String budgetText(AssetBudgets.Snapshot value){
|
||||
var out=new StringBuilder("Capacity: "+value.qualification().state()+" — "+(value.qualification().profile()==null?value.qualification().reason():value.qualification().profile().profileId()));
|
||||
value.pools().stream().filter(pool->pool.bankType()!=AssetBudgets.BankType.sound||!pool.existing().isEmpty()).forEach(pool->out.append("\n").append(pool.bankType()).append(": existing ").append(pool.existing().size()).append(", build ").append(pool.buildIncluded().size()).append(", preload ").append(pool.requiredSlots()).append(" / ").append(pool.limit()==null?"unknown":pool.limit()).append(", potential dynamic ").append(pool.potentialDynamic().size()));return out.toString();
|
||||
}
|
||||
private void refreshFacts(){var selected=bank.getValue();executor.execute(()->{try{var budget=service.budget(project.rootPath(),null);var text=new StringBuilder("Input revision: "+budget.revision().sha256()+"\n");budget.content().forEach(c->text.append(c.asset().value()).append(": ").append(c.used()).append(" / ").append(c.limit()==null?"unknown":c.limit()).append(' ').append(c.unit()).append('\n'));budget.pools().forEach(pool->pool.effectivePreload().forEach(p->text.append(pool.bankType()).append(" slot ").append(p.slot()).append(" = ").append(p.bank().asset().value()).append(" dependencies=").append(p.dependencies()).append('\n')));budget.diagnostics().forEach(d->text.append(d.producer()).append('/').append(d.code()).append(' ').append(d.message()).append(" path=").append(d.path()).append(" missing=").append(d.missingIndices()).append(" duplicate=").append(d.duplicateIndices()).append(" required=").append(d.required()).append(" limit=").append(d.limit()).append(" ").append(d.context()).append('\n'));if(selected!=null)service.dependencies(project.rootPath(),null,selected.reference()).forEach(o->text.append("Output ").append(o.outputPath()).append(" producer=").append(o.producer()).append(" dependencies=").append(o.dependencies()).append(" stale=").append(o.stale()).append('\n'));Platform.runLater(()->facts.setText(text.toString()));}catch(Exception e){Platform.runLater(()->facts.setText(e.getMessage()));}});}
|
||||
private void importPng(){var selected=bank.getValue();if(selected==null||selected.family()!=AssetFamily.GLYPH_BANK){error("Select a glyph bank first");return;}
|
||||
var chooser=new FileChooser();chooser.setTitle("Select PNG source");chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("PNG image","*.png"));var source=chooser.showOpenDialog(getScene().getWindow());if(source==null)return;
|
||||
var destination=new TextInputDialog(source.getName());destination.setTitle("PNG destination");destination.setHeaderText("Path inside "+selected.name());var path=destination.showAndWait().orElse(null);if(path==null)return;
|
||||
executor.execute(()->{try{var grant=service.authorizePng(project.rootPath(),source.toPath());var mutation=new ImportPng(UUID.randomUUID().toString(),new PngInput(null,grant.grantId(),grant.sha256()),selected.reference(),path);var result=new AssetBatchReview(service,project.rootPath(),()->getScene().getWindow()).apply(List.of(mutation));if(result.applied())Platform.runLater(()->{changed.run();});}catch(Exception e){Platform.runLater(()->error(e.getMessage()));}});
|
||||
}
|
||||
private void declareOutput(){var selected=bank.getValue();if(selected==null){error("Select the output owner first");return;}
|
||||
var path=new TextField();path.setPromptText("Project-relative output path");var producer=new TextField();producer.setPromptText("Producer name (descriptive)");var dependencies=new ListView<AssetSummary>();dependencies.getItems().setAll(bank.getItems());dependencies.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);dependencies.setPrefHeight(150);dependencies.setCellFactory(v->new ListCell<>(){protected void updateItem(AssetSummary a,boolean empty){super.updateItem(a,empty);setText(empty||a==null?null:a.name());}});
|
||||
var dialog=new Dialog<Boolean>();dialog.setTitle("Declare generated output");dialog.initOwner(getScene().getWindow());dialog.getDialogPane().setContent(new VBox(8,new Label("Output path"),path,new Label("Producer"),producer,new Label("Input banks"),dependencies));dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK,ButtonType.CANCEL);dialog.setResultConverter(b->b==ButtonType.OK);if(!dialog.showAndWait().orElse(false))return;
|
||||
try{var value=new Ownership(selected.reference(),path.getText(),producer.getText(),dependencies.getSelectionModel().getSelectedItems().stream().map(AssetSummary::reference).toList(),false);executor.execute(()->{try{new AssetBatchReview(service,project.rootPath(),()->getScene().getWindow()).apply(List.of(),List.of(value));Platform.runLater(this::refresh);}catch(Exception e){Platform.runLater(()->error(e.getMessage()));}});}catch(Exception e){error(e.getMessage());}
|
||||
}
|
||||
private void error(String message){var alert=new Alert(Alert.AlertType.ERROR,message==null?"Asset operation failed":message,ButtonType.OK);if(getScene()!=null)alert.initOwner(getScene().getWindow());alert.showAndWait();}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package p.studio.ui.javafx.workspaces.assets;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.stage.Window;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Worker-side review shared by existing human asset controls. Publication always needs a final click. */
|
||||
final class AssetBatchReview {
|
||||
private final AssetAuthoringService service; private final Path root; private final Supplier<Window> owner;
|
||||
AssetBatchReview(AssetAuthoringService service,Path root,Supplier<Window> owner){this.service=service;this.root=root;this.owner=owner;}
|
||||
Result apply(List<Mutation> mutations){return apply(mutations,List.of());}
|
||||
Result apply(List<Mutation> mutations,List<Ownership> ownership) {
|
||||
if(Platform.isFxApplicationThread())throw new IllegalStateException("Asset review must run on the workspace worker");
|
||||
var revision=service.revision(root,null);var rebinds=List.<Rebind>of();
|
||||
while(true) {
|
||||
var preview=service.preview(root,null,UUID.randomUUID().toString(),new Request(revision,mutations,rebinds,ownership));
|
||||
var next=fx(()->review(preview));
|
||||
if(next==null)return new Result(preview.batchId(),preview.requestId(),CommitState.cancelled,revision,revision,List.of(),preview.assets(),List.of(),List.of());
|
||||
if(next.rebinds()!=null){rebinds=next.rebinds();continue;}
|
||||
return service.commit(root,null,UUID.randomUUID().toString(),preview.batchId(),preview.revision());
|
||||
}
|
||||
}
|
||||
private record Choice(List<Rebind> rebinds){}
|
||||
private Choice review(Preview preview) {
|
||||
var dialog=new Dialog<Choice>();dialog.setTitle("Review asset changes");if(owner.get()!=null)dialog.initOwner(owner.get());
|
||||
var text=new TextArea(describe(preview));text.setEditable(false);text.setWrapText(true);text.setPrefSize(760,420);text.setId("asset-batch-preview");
|
||||
var box=new VBox(10,new Label("Revision: "+preview.revision().sha256()),text);
|
||||
var publish=new ButtonType("Publish changes",ButtonBar.ButtonData.OK_DONE);
|
||||
var rebind=new ButtonType("Review rebindings",ButtonBar.ButtonData.OTHER);
|
||||
dialog.getDialogPane().getButtonTypes().addAll(publish,ButtonType.CANCEL);
|
||||
if(!preview.affectedReferences().isEmpty()){dialog.getDialogPane().getButtonTypes().add(rebind);dialog.getDialogPane().lookupButton(rebind).setId("asset-batch-rebind");}
|
||||
dialog.getDialogPane().lookupButton(publish).setDisable(!preview.canCommit());
|
||||
dialog.getDialogPane().lookupButton(publish).setId("asset-batch-publish");
|
||||
dialog.getDialogPane().setContent(box);
|
||||
dialog.setResultConverter(button->button==publish?new Choice(null):button==rebind?new Choice(rebind(preview)):null);
|
||||
var choice=dialog.showAndWait().orElse(null);
|
||||
// Closing the rebind dialog cancels this review, without applying anything.
|
||||
return choice!=null&&choice.rebinds()!=null&&choice.rebinds().isEmpty()?null:choice;
|
||||
}
|
||||
private List<Rebind> rebind(Preview preview) {
|
||||
var targets=new ArrayList<ArtifactInfo>();
|
||||
for(var bank:service.catalog(root,null))if(bank.family()==AssetFamily.GLYPH_BANK)targets.addAll(service.previewArtifacts(root,null,preview.batchId(),bank.reference()));
|
||||
var grouped=new LinkedHashMap<Artifact,List<ReferenceUse>>();preview.affectedReferences().forEach(use->grouped.computeIfAbsent(use.target(),ignored->new ArrayList<>()).add(use));
|
||||
var dialog=new Dialog<List<Rebind>>();dialog.setTitle("Choose replacement artifacts");if(owner.get()!=null)dialog.initOwner(owner.get());
|
||||
var body=new VBox(10);var pickers=new LinkedHashMap<Artifact,ComboBox<ArtifactInfo>>();
|
||||
grouped.forEach((from,uses)->{
|
||||
var picker=new ComboBox<ArtifactInfo>();picker.getItems().setAll(targets);picker.setMaxWidth(Double.MAX_VALUE);
|
||||
picker.setConverter(new javafx.util.StringConverter<>(){public String toString(ArtifactInfo v){return v==null?"Choose replacement":v.identity().bank().value()+" / "+v.sourcePath()+" / "+v.identity().artifactId();}public ArtifactInfo fromString(String s){throw new UnsupportedOperationException();}});
|
||||
picker.setUserData(from);pickers.put(from,picker);body.getChildren().addAll(new Label(from.bank().value()+" / "+from.artifactId()+"\n"+uses.stream().map(ReferenceUse::location).collect(java.util.stream.Collectors.joining("\n"))),picker);
|
||||
});
|
||||
var confirm=new ButtonType("Preview these rebindings",ButtonBar.ButtonData.OK_DONE);dialog.getDialogPane().getButtonTypes().addAll(confirm,ButtonType.CANCEL);
|
||||
var confirmNode=dialog.getDialogPane().lookupButton(confirm);confirmNode.setId("asset-rebind-preview");confirmNode.setDisable(true);
|
||||
pickers.values().forEach(picker->picker.valueProperty().addListener((o,a,b)->confirmNode.setDisable(pickers.values().stream().anyMatch(p->p.getValue()==null))));
|
||||
var scroll=new ScrollPane(body);scroll.setFitToWidth(true);scroll.setPrefViewportWidth(720);scroll.setPrefViewportHeight(360);dialog.getDialogPane().setContent(scroll);
|
||||
dialog.setResultConverter(button->button==confirm?grouped.entrySet().stream().map(e->new Rebind(e.getKey(),pickers.get(e.getKey()).getValue().identity(),e.getValue())).toList():List.of());
|
||||
return dialog.showAndWait().orElse(List.of());
|
||||
}
|
||||
static String describe(Preview preview) {
|
||||
var out=new StringBuilder("State: "+preview.state()+"\n\nFiles:\n");
|
||||
preview.files().forEach(f->out.append(f.action()).append(" ").append(f.path()).append("\n ").append(f.beforeSha256()).append(" -> ").append(f.afterSha256()).append('\n'));
|
||||
out.append("\nAssets: ").append(preview.assets()).append("\n\nAffected references:\n");preview.affectedReferences().forEach(r->out.append(r.kind()).append(" ").append(r.location()).append(" -> ").append(r.target()).append('\n'));
|
||||
preview.conflicts().forEach(c->out.append("CONFLICT ").append(c.path()).append(": ").append(c.reason()).append('\n'));
|
||||
preview.diagnostics().forEach(d->out.append(d.producer()).append(" / ").append(d.code()).append(" / ").append(d.severity()).append(" blocking=").append(d.blocking()).append("\n").append(d.message()).append("\npath=").append(d.path()).append(" root=").append(d.assetRoot()).append(" family=").append(d.family()).append(" missing=").append(d.missingIndices()).append(" duplicate=").append(d.duplicateIndices()).append(" used=").append(d.used()).append(" required=").append(d.required()).append(" limit=").append(d.limit()).append("\n").append(d.context()).append('\n'));
|
||||
preview.ownership().forEach(o->out.append("Output: ").append(o.outputPath()).append(" producer=").append(o.producer()).append(" dependencies=").append(o.dependencies()).append(" stale=").append(o.stale()).append('\n'));return out.toString();
|
||||
}
|
||||
static <T>T fx(Callable<T> work){try{if(Platform.isFxApplicationThread())return work.call();var task=new FutureTask<>(work);Platform.runLater(task);return task.get();}catch(Exception failure){throw new IllegalStateException(failure);}}
|
||||
}
|
||||
+19
-5
@@ -47,7 +47,10 @@ public final class AssetWorkspace extends Workspace {
|
||||
private final java.util.concurrent.Executor executor;
|
||||
private final p.studio.ui.javafx.utilities.i18n.I18nService i18n;
|
||||
private final p.studio.ui.javafx.utilities.ThemeService theme;
|
||||
private final AssetCommands assetCommands;
|
||||
private final SharedAssetCommands assetCommands;
|
||||
private final SharedSceneWorkflow sharedSceneWorkflow;
|
||||
private VBox topProgress;
|
||||
private AssetAuthoringPane authoringPane;
|
||||
private final AssetPacking assetPacking;
|
||||
private final AssetCreationCatalog assetCreationCatalog;
|
||||
private final AssetMetadataService assetMetadataService;
|
||||
@@ -74,7 +77,8 @@ public final class AssetWorkspace extends Workspace {
|
||||
this.executor = executor;
|
||||
this.i18n = i18n;
|
||||
this.theme = theme;
|
||||
this.assetCommands = java.util.Objects.requireNonNull(assetCommands, "assetCommands");
|
||||
this.assetCommands = new SharedAssetCommands(java.util.Objects.requireNonNull(assetCommands, "assetCommands"), () -> root.getScene() == null ? null : root.getScene().getWindow());
|
||||
this.sharedSceneWorkflow = new SharedSceneWorkflow(sceneBankWorkflow, () -> root.getScene() == null ? null : root.getScene().getWindow());
|
||||
this.assetPacking = java.util.Objects.requireNonNull(assetPacking, "assetPacking");
|
||||
this.assetCreationCatalog = java.util.Objects.requireNonNull(assetCreationCatalog, "assetCreationCatalog");
|
||||
this.assetMetadataService = java.util.Objects.requireNonNull(assetMetadataService, "assetMetadataService");
|
||||
@@ -82,9 +86,9 @@ public final class AssetWorkspace extends Workspace {
|
||||
this.assetCapacityPolicy = java.util.Objects.requireNonNull(assetCapacityPolicy, "assetCapacityPolicy");
|
||||
this.assetListControl = new AssetListControl(this.projectReference, this.workspaceEventBus, i18n, executor, assetCatalog);
|
||||
this.detailsControl = new AssetDetailsControl(this.projectReference, this.workspaceEventBus, i18n, executor, theme,
|
||||
assetCatalog, assetCommands, assetDetails, assetMetadataService, assetCapacityPolicy,
|
||||
assetCatalog, this.assetCommands, assetDetails, assetMetadataService, assetCapacityPolicy,
|
||||
bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService,
|
||||
sceneBankWorkflow);
|
||||
this.sharedSceneWorkflow);
|
||||
this.logsPane = new AssetLogsPane(this.workspaceEventBus, eventBus, i18n);
|
||||
root.getStyleClass().add("assets-workspace");
|
||||
root.setCenter(buildLayout());
|
||||
@@ -127,6 +131,12 @@ public final class AssetWorkspace extends Workspace {
|
||||
}
|
||||
|
||||
public void openAnimationOrigin(java.util.UUID bank,String pointer){detailsControl.openAnimationOrigin(bank,pointer);}
|
||||
public void setAssetAuthoring(p.studio.api.assets.AssetAuthoringService service) {
|
||||
assetCommands.service(service);sharedSceneWorkflow.service(service);
|
||||
authoringPane=new AssetAuthoringPane(projectReference,service,executor,this::refreshAssets);
|
||||
topProgress.getChildren().setAll(authoringPane);
|
||||
}
|
||||
public void manualAllowed(boolean allowed){if(authoringPane!=null)authoringPane.manualAllowed(allowed);}
|
||||
public void setAnimationService(p.studio.api.assets.animation.AnimationService service){detailsControl.setAnimationService(service);}
|
||||
|
||||
public p.studio.api.automation.DocumentHandoff documentHandoff() { return detailsControl.documentHandoff(); }
|
||||
@@ -166,8 +176,9 @@ public final class AssetWorkspace extends Workspace {
|
||||
}
|
||||
|
||||
private VBox createTopProgressBox() {
|
||||
final var topProgress = new VBox(6);
|
||||
topProgress = new VBox(6);
|
||||
topProgress.getStyleClass().add("assets-workspace-inline-progress");
|
||||
topProgress.setMinHeight(javafx.scene.layout.Region.USE_PREF_SIZE);
|
||||
return topProgress;
|
||||
}
|
||||
|
||||
@@ -186,11 +197,13 @@ public final class AssetWorkspace extends Workspace {
|
||||
refreshButton.textProperty().bind(i18n.bind(I18n.ASSETS_NAVIGATOR_ACTION_REFRESH));
|
||||
refreshButton.getStyleClass().addAll("studio-button", "studio-button-primary", "assets-workspace-action-button");
|
||||
refreshButton.setMaxWidth(Double.MAX_VALUE);
|
||||
p.studio.ui.javafx.workspaces.dev.ManualProjectUiGuard.allowReadOnly(refreshButton);
|
||||
refreshButton.setOnAction(event -> refreshAssets());
|
||||
return refreshButton;
|
||||
}
|
||||
|
||||
private void refreshAssets() {
|
||||
if(authoringPane!=null)authoringPane.refresh();
|
||||
workspaceEventBus.publish(new StudioAssetsRefreshRequestedEvent(null, true));
|
||||
}
|
||||
|
||||
@@ -238,6 +251,7 @@ public final class AssetWorkspace extends Workspace {
|
||||
private SplitPane createAssetSplitPane() {
|
||||
splitPane = new SplitPane(assetListControl, detailsControl);
|
||||
splitPane.setDividerPositions(0.34);
|
||||
splitPane.setMinHeight(0);
|
||||
splitPane.getStyleClass().add("assets-workspace-split");
|
||||
splitPane.getDividers().forEach(divider ->
|
||||
divider.positionProperty().addListener((ignored, previous, current) -> {
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package p.studio.ui.javafx.workspaces.assets;
|
||||
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import javafx.stage.Window;
|
||||
|
||||
/** Keeps existing editors; their Apply actions use the same preview/publication service as task calls. */
|
||||
final class SharedAssetCommands implements AssetCommands {
|
||||
private final AssetCommands delegate;private final Supplier<Window> owner;
|
||||
private volatile AssetAuthoringService service;
|
||||
SharedAssetCommands(AssetCommands delegate,Supplier<Window> owner){this.delegate=delegate;this.owner=owner;}
|
||||
void service(AssetAuthoringService value){service=value;}
|
||||
private Result apply(ProjectReference p,Mutation mutation){return new AssetBatchReview(service,p.rootPath(),owner).apply(List.of(mutation));}
|
||||
private static String id(){return UUID.randomUUID().toString();}
|
||||
private static String message(Result r){return r.state()+": "+r.diagnostics().stream().map(d->d.code()+": "+d.message()).collect(java.util.stream.Collectors.joining("; "))+r.conflicts();}
|
||||
private AssetUpdateResult update(ProjectReference p,Mutation mutation){try{var r=apply(p,mutation);return new AssetUpdateResult(r.applied(),message(r));}catch(Exception error){return new AssetUpdateResult(false,error.getMessage());}}
|
||||
private AssetMutationResult mutate(ProjectReference p,Mutation mutation,AssetReference ref){
|
||||
try{var r=apply(p,mutation);var asset=service.catalog(p.rootPath(),null).stream().filter(a->a.reference().equals(ref)||ref.isAssetRootReference()&&p.rootPath().resolve("assets").resolve(ref.rawValue()).normalize().equals(a.root())).findFirst().orElse(null);
|
||||
return new AssetMutationResult(r.applied()?AssetOperationStatus.SUCCESS:AssetOperationStatus.FAILED,message(r),asset==null?ref:asset.reference(),asset==null?null:asset.root(),asset==null?null:asset.root().resolve("asset.json"));
|
||||
}catch(Exception e){return new AssetMutationResult(AssetOperationStatus.FAILED,e.getMessage(),ref,null,null);}
|
||||
}
|
||||
public AssetMutationResult create(ProjectReference p,String root,String name,AssetFamily family,String format,String codec,boolean preload){return service==null?delegate.create(p,root,name,family,format,codec,preload):mutate(p,new CreateBank(id(),root,name,family,format,codec,preload),AssetReference.forRelativeAssetRoot(root));}
|
||||
public AssetMutationResult register(ProjectReference p,AssetReference bank){return service==null?delegate.register(p,bank):mutate(p,new RegisterBank(id(),bank),bank);}
|
||||
public AssetMutationResult updateBuildParticipation(ProjectReference p,AssetReference bank,boolean included){return service==null?delegate.updateBuildParticipation(p,bank,included):mutate(p,new BuildParticipation(id(),bank,included),bank);}
|
||||
public AssetUpdateResult updateContract(ProjectReference p,AssetReference bank,boolean preload,String codec,Map<String,String> fields,Map<String,String> metadata){return service==null?delegate.updateContract(p,bank,preload,codec,fields,metadata):update(p,new UpdateContract(id(),bank,preload,codec,fields,metadata));}
|
||||
public AssetUpdateResult applyBankComposition(ProjectReference p,AssetReference bank,List<String> selected){return service==null?delegate.applyBankComposition(p,bank,selected):update(p,new ComposeBank(id(),bank,selected));}
|
||||
public AssetUpdateResult applyPaletteOverhauling(ProjectReference p,AssetReference bank,List<Map<String,Object>> palettes){
|
||||
if(service==null)return delegate.applyPaletteOverhauling(p,bank,palettes);
|
||||
var values=palettes.stream().map(palette->new Palette(((Number)palette.get("index")).intValue(),((List<?>)palette.get("rgba8888")).stream().map(color->((Number)color).longValue()&0xffff_ffffL).toList())).toList();
|
||||
return update(p,new ComposePalettes(id(),bank,values));
|
||||
}
|
||||
public AssetMutationResult move(ProjectReference p,AssetReference bank,String root){return delegate.move(p,bank,root);}
|
||||
public AssetMutationResult delete(ProjectReference p,AssetReference bank){return delegate.delete(p,bank);}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package p.studio.ui.javafx.workspaces.assets;
|
||||
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.AssetBatches.*;
|
||||
import p.studio.api.assets.scene.*;
|
||||
import p.studio.api.assets.workspace.*;
|
||||
import p.studio.api.project.ProjectReference;
|
||||
import java.util.*;
|
||||
import java.util.function.Supplier;
|
||||
import javafx.stage.Window;
|
||||
|
||||
/** Existing scene editor and canonical service share stable-artifact batch publication. */
|
||||
final class SharedSceneWorkflow implements SceneBankWorkflow {
|
||||
private final SceneBankWorkflow delegate;private final Supplier<Window> owner;private volatile AssetAuthoringService service;
|
||||
SharedSceneWorkflow(SceneBankWorkflow delegate,Supplier<Window> owner){this.delegate=delegate;this.owner=owner;}
|
||||
void service(AssetAuthoringService value){service=value;}
|
||||
public SceneBankWorkflowResult inspect(ProjectReference p,AssetWorkspaceAssetDetails d){return delegate.inspect(p,d);}
|
||||
public SceneBankWorkflowResult validate(ProjectReference p,AssetWorkspaceAssetDetails d){return delegate.validate(p,d);}
|
||||
public SceneBankWorkflowResult inspectLayer(ProjectReference p,AssetWorkspaceAssetDetails d,int layer){return delegate.inspectLayer(p,d,layer);}
|
||||
public SceneBankWorkflowResult validateLayer(ProjectReference p,AssetWorkspaceAssetDetails d,int layer){return delegate.validateLayer(p,d,layer);}
|
||||
public SceneBankWorkflowResult accept(ProjectReference p,AssetWorkspaceAssetDetails d){return service==null?delegate.accept(p,d):publish(p,d);}
|
||||
public SceneBankWorkflowResult acceptLayer(ProjectReference p,AssetWorkspaceAssetDetails d,int layer){return service==null?delegate.acceptLayer(p,d,layer):publish(p,d);}
|
||||
private SceneBankWorkflowResult publish(ProjectReference p,AssetWorkspaceAssetDetails d){
|
||||
try{var layers=new ArrayList<SceneLayer>();
|
||||
for(var layer:d.sceneBankMetadata().layerBindings()) {
|
||||
AssetReference bank=layer.tilesetAssetRoot().isBlank()?null:AssetReference.forRelativeAssetRoot(layer.tilesetAssetRoot());
|
||||
var artifacts=bank==null?List.<ArtifactInfo>of():service.artifacts(p.rootPath(),null,bank);
|
||||
var tiles=new ArrayList<SceneTile>();int tileSize=0;
|
||||
for(var tile:layer.tiles()) {
|
||||
if(!tile.active()){tiles.add(new SceneTile(false,null,tile.paletteId(),tile.flipX(),tile.flipY()));continue;}
|
||||
var glyph=artifacts.stream().filter(a->a.glyphIndex()==tile.glyphId()).findFirst().orElseThrow(()->new IllegalArgumentException("Scene tile no longer names an existing glyph"));tileSize=glyph.width();
|
||||
tiles.add(new SceneTile(true,glyph.identity(),tile.paletteId(),tile.flipX(),tile.flipY()));
|
||||
}
|
||||
layers.add(new SceneLayer(layer.enabled(),bank,tileSize,layer.parallaxFactorX(),layer.parallaxFactorY(),layer.width(),layer.height(),tiles));
|
||||
}
|
||||
var result=new AssetBatchReview(service,p.rootPath(),owner).apply(List.of(new ComposeScene(UUID.randomUUID().toString(),d.summary().assetReference(),layers)));
|
||||
if(result.applied())return delegate.inspect(p,d);
|
||||
return new SceneBankWorkflowResult(false,"Scene publication "+result.state()+": "+result.diagnostics(),d.sceneBankValidation(),List.of());
|
||||
}catch(Exception e){return new SceneBankWorkflowResult(false,e.getMessage(),d.sceneBankValidation(),List.of());}
|
||||
}
|
||||
}
|
||||
+2
@@ -418,6 +418,8 @@ public final class PackWorkspaceWizard {
|
||||
formatElapsed(packResult.elapsedMillis())),
|
||||
AssetDetailsUiSupport.createSectionMessage(packResult.summary()));
|
||||
|
||||
packResult.diagnostics().forEach(diagnostic->content.getChildren().add(AssetDetailsUiSupport.createSectionMessage(
|
||||
diagnostic.producer()+" / "+diagnostic.code()+" / "+diagnostic.severity()+": "+diagnostic.message()+"\n"+diagnostic.evidencePath()+"\n"+diagnostic.context())));
|
||||
if (packResult.emittedArtifacts().isEmpty()) {
|
||||
content.getChildren().add(AssetDetailsUiSupport.createSectionMessage(
|
||||
i18n.text(I18n.ASSETS_PACK_WIZARD_RESULT_NO_ARTIFACTS)));
|
||||
|
||||
+5
-1
@@ -28,10 +28,14 @@ public class ShipperWorkspace extends Workspace {
|
||||
|
||||
public ShipperWorkspace(ProjectReference projectReference, Shipper shipperService, I18nService i18n,
|
||||
StudioEventBus eventBus) {
|
||||
this(projectReference, shipperService, i18n, eventBus, p.studio.api.diagnostic.DiagnosticSources.unavailable());
|
||||
}
|
||||
public ShipperWorkspace(ProjectReference projectReference, Shipper shipperService, I18nService i18n,
|
||||
StudioEventBus eventBus, p.studio.api.diagnostic.DiagnosticSources diagnosticSources) {
|
||||
super(projectReference, eventBus);
|
||||
this.shipperService = java.util.Objects.requireNonNull(shipperService, "shipperService");
|
||||
this.i18n = java.util.Objects.requireNonNull(i18n, "i18n");
|
||||
diagnosticResults = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane(projectReference.rootPath());
|
||||
diagnosticResults = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane(projectReference.rootPath(), diagnosticSources);
|
||||
final var toolbar = buildToolBar();
|
||||
root.setTop(toolbar);
|
||||
|
||||
|
||||
+17
-3
@@ -24,6 +24,7 @@ public final class DevWorkspace extends Workspace {
|
||||
private final Label state = new Label(), identity = new Label(), operation = new Label(), imageStatus = new Label();
|
||||
private final TextArea diagnostics = new TextArea(), history = new TextArea();
|
||||
private final p.studio.ui.javafx.diagnostics.DiagnosticResultsPane diagnosticResults;
|
||||
private final RuntimeObservationPane observations;
|
||||
private final ImageView canvas = new ImageView();
|
||||
private final Button grant = new Button(), reclaim = new Button();
|
||||
private final Button configuration = new Button();
|
||||
@@ -36,6 +37,11 @@ public final class DevWorkspace extends Workspace {
|
||||
private long generation;
|
||||
private CanonicalCapture rendered;
|
||||
private boolean preparing;
|
||||
private EvidenceInspector evidence;
|
||||
public void setEvidenceTools(EvidenceTools tools) {
|
||||
evidence = new EvidenceInspector(projectRoot, automation, tools);
|
||||
root.getChildren().add(new TitledPane("Visual evidence", evidence));
|
||||
}
|
||||
private final javafx.beans.value.ChangeListener<java.util.Locale> localeListener;
|
||||
|
||||
public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events) {
|
||||
@@ -43,9 +49,14 @@ public final class DevWorkspace extends Workspace {
|
||||
}
|
||||
public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events,
|
||||
AgentConnectionGuide connectionGuide) {
|
||||
this(project, automation, i18n, events, connectionGuide, p.studio.api.diagnostic.DiagnosticSources.unavailable());
|
||||
}
|
||||
public DevWorkspace(ProjectReference project, AutomationSession automation, I18nService i18n, StudioEventBus events,
|
||||
AgentConnectionGuide connectionGuide, p.studio.api.diagnostic.DiagnosticSources diagnosticSources) {
|
||||
super(project, events); this.automation = automation; this.i18n = i18n;
|
||||
this.connectionGuide = java.util.Objects.requireNonNull(connectionGuide); projectRoot = project.rootPath();
|
||||
diagnosticResults = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane(projectRoot);
|
||||
diagnosticResults = new p.studio.ui.javafx.diagnostics.DiagnosticResultsPane(projectRoot, diagnosticSources);
|
||||
observations = new RuntimeObservationPane(i18n);
|
||||
localeListener = (o, before, after) -> apply(this.automation.snapshot());
|
||||
scroll.setFitToWidth(true);
|
||||
root.setPadding(new Insets(16)); root.getStyleClass().add("dev-workspace");
|
||||
@@ -79,7 +90,7 @@ public final class DevWorkspace extends Workspace {
|
||||
root.getChildren().addAll(new Label(project.name() + " — " + project.rootPath()),
|
||||
state, new HBox(10, grant, reclaim, configuration), discardGameData, availability, copyStatus, instructions, warning,
|
||||
operation, imageStatus, imagePane, identity,
|
||||
pane(I18n.DEV_DIAGNOSTICS, diagnostics), diagnosticResults, pane(I18n.DEV_HISTORY, history));
|
||||
observations, pane(I18n.DEV_DIAGNOSTICS, diagnostics), diagnosticResults, pane(I18n.DEV_HISTORY, history));
|
||||
apply(automation.snapshot());
|
||||
}
|
||||
|
||||
@@ -92,6 +103,7 @@ public final class DevWorkspace extends Workspace {
|
||||
@Override public Node rootNode() { return scroll; }
|
||||
@Override public void load() {
|
||||
if (subscription != null) return;
|
||||
if (evidence != null) evidence.refresh();
|
||||
i18n.localeProperty().addListener(localeListener);
|
||||
long subscribed = ++generation;
|
||||
java.util.concurrent.CompletableFuture.supplyAsync(() -> connectionGuide.preparationStatus(projectRoot))
|
||||
@@ -126,15 +138,17 @@ public final class DevWorkspace extends Workspace {
|
||||
}));
|
||||
}
|
||||
private void apply(AutomationSnapshot snapshot) {
|
||||
if (evidence != null) evidence.setManual(snapshot.manualAllowed());
|
||||
updateConnection();
|
||||
var view = DevWorkspaceProjection.from(snapshot);
|
||||
observations.show(view);
|
||||
state.setText(i18n.text(switch (view.state()) {
|
||||
case MANUAL -> I18n.DEV_MANUAL;
|
||||
case WAITING_FOR_AGENT -> I18n.DEV_WAITING;
|
||||
case AGENT_WORKING -> I18n.DEV_WORKING;
|
||||
case RETURNING_CONTROL -> I18n.DEV_RETURNING;
|
||||
}));
|
||||
grant.setDisable(!view.grantEnabled()); reclaim.setDisable(!view.reclaimEnabled());
|
||||
grant.setDisable(!view.grantEnabled() || automation.runtimeAttached()); reclaim.setDisable(!view.reclaimEnabled());
|
||||
boolean blockedReturn = snapshot.state() == ControlState.RETURNING_CONTROL && !snapshot.diagnostics().isEmpty();
|
||||
discardGameData.setVisible(blockedReturn); discardGameData.setManaged(blockedReturn);
|
||||
identity.setText(view.identity()); operation.setText(view.operation());
|
||||
|
||||
+4
-2
@@ -3,7 +3,8 @@ package p.studio.ui.javafx.workspaces.dev;
|
||||
import p.studio.api.automation.*;
|
||||
|
||||
public record DevWorkspaceProjection(ControlState state, boolean grantEnabled, boolean reclaimEnabled,
|
||||
boolean stale, CanonicalCapture capture, String identity, String operation, String diagnostics, String calls, java.util.Map<String, Object> diagnosticResult) {
|
||||
boolean stale, CanonicalCapture capture, String identity, String operation, String diagnostics, String calls, java.util.Map<String, Object> diagnosticResult,
|
||||
RuntimeObservation runtimeObservation, ControlObservation controlObservation, RuntimeObservation operationObservation) {
|
||||
public static DevWorkspaceProjection from(AutomationSnapshot s) {
|
||||
var frame = s.capture();
|
||||
String identity = frame == null ? "" : "session=" + frame.sessionId() + " | build=" + frame.buildId()
|
||||
@@ -11,6 +12,7 @@ public record DevWorkspaceProjection(ControlState state, boolean grantEnabled, b
|
||||
+ " | " + frame.width() + "×" + frame.height() + " | stride=" + frame.stridePixels();
|
||||
return new DevWorkspaceProjection(s.state(), s.canGrant(), s.canReclaim(), s.stale(), frame, identity,
|
||||
s.operation() == null ? "" : s.operation().id().value() + " | " + s.operation().state() + " | " + s.operation().summary(),
|
||||
String.join("\n", s.diagnostics()), String.join("\n", s.calls()), s.diagnosticResult());
|
||||
String.join("\n", s.diagnostics()), String.join("\n", s.calls()), s.diagnosticResult(),
|
||||
s.runtimeObservation(), s.controlObservation(), s.operationObservation());
|
||||
}
|
||||
}
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package p.studio.ui.javafx.workspaces.dev;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.stage.FileChooser;
|
||||
import javafx.util.StringConverter;
|
||||
import p.studio.api.automation.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Read-only images and explicit human reference review; no guest execution controls. */
|
||||
public final class EvidenceInspector extends VBox {
|
||||
private final EvidenceTools tools;private final Path root;private final AutomationSession automation;
|
||||
private final ComboBox<Evidence.Publication> publications=new ComboBox<>();
|
||||
private final ComboBox<Evidence.Artifact> references=new ComboBox<>();
|
||||
private final TextArea facts=new TextArea();private final Label pixel=new Label(),status=new Label();
|
||||
private final HBox images=new HBox(12);
|
||||
private final Button approve=new Button("Approve baseline revision…"),importReference=new Button("Import reference…");
|
||||
private String previousRevision;private boolean busy;private long generation;
|
||||
public EvidenceInspector(Path root,AutomationSession automation,EvidenceTools tools) {
|
||||
super(8);this.root=root;this.automation=automation;this.tools=tools;setId("evidence-inspector");
|
||||
var refresh=new Button("Refresh evidence");refresh.setOnAction(e->refresh());
|
||||
publications.setId("evidence-publications");publications.setMaxWidth(Double.MAX_VALUE);
|
||||
publications.setConverter(new StringConverter<>() {
|
||||
public String toString(Evidence.Publication p){return p==null?"":p.createdAt()+" — "+(p.report()==null?p.baseline()==null?"image": "baseline revision":p.report().verdict())+" — "+p.requestId();}
|
||||
public Evidence.Publication fromString(String s){throw new UnsupportedOperationException();}
|
||||
});
|
||||
references.setConverter(new StringConverter<>() {
|
||||
public String toString(Evidence.Artifact a){return a==null?"":a.id()+" — "+a.provenance().get("origin");}
|
||||
public Evidence.Artifact fromString(String s){throw new UnsupportedOperationException();}
|
||||
});
|
||||
references.setMaxWidth(Double.MAX_VALUE);references.setId("evidence-reference");
|
||||
approve.setId("evidence-approve-baseline");approve.setOnAction(e->approve());
|
||||
importReference.setOnAction(e->importReference());
|
||||
publications.valueProperty().addListener((o,b,a)->{if(a!=null)show(a);});
|
||||
facts.setEditable(false);facts.setPrefRowCount(9);facts.setWrapText(true);facts.setId("evidence-facts");
|
||||
pixel.setId("evidence-pixel");status.setWrapText(true);
|
||||
getChildren().addAll(new Label("Project visual evidence"),new HBox(8,refresh,importReference),status,publications,
|
||||
new ScrollPane(images),pixel,facts,new Label("Reference for explicit human review"),references,approve);
|
||||
setManual(automation.snapshot().manualAllowed());
|
||||
}
|
||||
public void setManual(boolean manual) {approve.setDisable(!manual||busy);importReference.setDisable(!manual||busy);}
|
||||
public void refresh() {
|
||||
async(()->tools.list(root,null),all->{
|
||||
String selected=publications.getValue()==null?null:publications.getValue().id();
|
||||
publications.getItems().setAll(all);references.getItems().setAll(all.stream().flatMap(p->p.artifacts().stream()).toList());
|
||||
previousRevision=all.stream().filter(p->p.baseline()!=null).max(Comparator.comparing(Evidence.Publication::createdAt)).map(p->p.baseline().id()).orElse(null);
|
||||
status.setText("Publications: "+all.size()+" · Current baseline revision: "+previousRevision);
|
||||
all.stream().filter(p->p.id().equals(selected)).findFirst().or(()->all.stream().reduce((a,b)->b)).ifPresent(p->publications.setValue(p));
|
||||
});
|
||||
}
|
||||
private record ImageData(String label,Evidence.View view,Evidence.Pixels pixels){}
|
||||
private void show(Evidence.Publication p) {
|
||||
async(()->{
|
||||
var ids=p.report()==null?p.artifacts().stream().map(Evidence.Artifact::id).toList():List.of(p.report().expectedId(),p.report().actualId(),p.report().diffId());
|
||||
var data=new ArrayList<ImageData>();int i=0;
|
||||
for(var id:ids)data.add(new ImageData(p.report()==null?"Artifact":List.of("Expected","Actual","Diff").get(i++),tools.metadata(root,null,id),tools.pixels(root,null,id)));
|
||||
return data;
|
||||
},data->{
|
||||
if(publications.getValue()==null||!publications.getValue().id().equals(p.id()))return;
|
||||
images.getChildren().clear();var text=new StringBuilder("Publication: ").append(p.id()).append("\nRequest: ").append(p.requestId());
|
||||
if(p.report()!=null) {
|
||||
var report=p.report();
|
||||
text.append("\nReport: ").append(report.id()).append("\nVerdict: ").append(report.verdict())
|
||||
.append("\nCompared pixels: ").append(report.comparedPixels()).append("\nDifferent pixels: ").append(report.differentPixels())
|
||||
.append("\nMaximum channel error: ").append(report.maximumChannelError()).append("\nDifference bounds: ").append(report.boundingBox())
|
||||
.append("\nParameters: ").append(report.parameters()).append("\nExpected SHA-256: ").append(report.expectedSha256())
|
||||
.append("\nActual SHA-256: ").append(report.actualSha256()).append("\nExpected / actual / diff IDs: ")
|
||||
.append(report.expectedId()).append(" / ").append(report.actualId()).append(" / ").append(report.diffId());
|
||||
}
|
||||
if(p.baseline()!=null)text.append("\nReviewed baseline: ").append(p.baseline());
|
||||
for(var item:data) {images.getChildren().add(preview(item));text.append("\n\n").append(item.label()).append(": ").append(item.view());}
|
||||
facts.setText(text.toString());
|
||||
if(p.report()!=null)references.getItems().stream().filter(a->a.id().equals(p.report().expectedId())).findFirst().ifPresent(references::setValue);
|
||||
else if(!p.artifacts().isEmpty())references.setValue(p.artifacts().getFirst());
|
||||
});
|
||||
}
|
||||
private VBox preview(ImageData data) {
|
||||
var p=data.pixels();byte[] rgba=p.rgba();var image=new WritableImage(p.width(),p.height());
|
||||
image.getPixelWriter().setPixels(0,0,p.width(),p.height(),PixelFormat.getByteBgraInstance(),bgra(rgba),0,p.width()*4);
|
||||
var view=new ImageView(image);view.setSmooth(false);view.setId("evidence-"+data.label().toLowerCase(Locale.ROOT));
|
||||
var zoom=new Spinner<Integer>(1,32,p.width()<32?16:1);
|
||||
zoom.setPrefWidth(90);view.setFitWidth(p.width()*zoom.getValue());view.setFitHeight(p.height()*zoom.getValue());
|
||||
zoom.valueProperty().addListener((o,b,a)->{view.setFitWidth(p.width()*a);view.setFitHeight(p.height()*a);});
|
||||
view.setOnMouseMoved(e->{int x=(int)Math.floor(e.getX()/zoom.getValue()),y=(int)Math.floor(e.getY()/zoom.getValue());if(x>=0&&y>=0&&x<p.width()&&y<p.height())pixel.setText(pixelText(data.label(),p,x,y));});
|
||||
var viewport=new ScrollPane(view);viewport.setPrefViewportWidth(320);viewport.setPrefViewportHeight(Math.min(240,Math.max(100,p.height())));
|
||||
return new VBox(4,new Label(data.label()+" · "+p.width()+"×"+p.height()+" · stale="+data.view().stale()),new HBox(6,new Label("Display zoom"),zoom),viewport);
|
||||
}
|
||||
public static String pixelText(String label,Evidence.Pixels p,int x,int y) {
|
||||
if(x<0||y<0||x>=p.width()||y>=p.height())throw new IllegalArgumentException("Pixel outside image");
|
||||
return label+" ("+x+", "+y+") RGBA = "+p.channel(x,y,0)+", "+p.channel(x,y,1)+", "+p.channel(x,y,2)+", "+p.channel(x,y,3);
|
||||
}
|
||||
private static byte[] bgra(byte[] rgba) {var b=rgba.clone();for(int i=0;i<b.length;i+=4){b[i]=rgba[i+2];b[i+2]=rgba[i];}return b;}
|
||||
private void approve() {
|
||||
var reference=references.getValue();if(reference==null)return;
|
||||
var confirmation=new Alert(Alert.AlertType.CONFIRMATION,"Approve reference "+reference.id()+" as a new baseline revision?\nPrevious revision: "+previousRevision+"\nOrigin: "+reference.provenance(),ButtonType.OK,ButtonType.CANCEL);
|
||||
if(getScene()!=null)confirmation.initOwner(getScene().getWindow());
|
||||
if(confirmation.showAndWait().orElse(ButtonType.CANCEL)==ButtonType.OK)
|
||||
async(()->tools.approveBaseline(root,reference.id(),previousRevision),ignored->refresh());
|
||||
}
|
||||
private void importReference() {
|
||||
var chooser=new FileChooser();chooser.setTitle("Select and authorize PNG reference");chooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("PNG reference","*.png"));
|
||||
var file=chooser.showOpenDialog(getScene()==null?null:getScene().getWindow());if(file==null)return;
|
||||
async(()->{String grant=tools.authorizeReference(root,file.toPath());return tools.importReference(root,null,"human-import:"+UUID.randomUUID(),file.toPath(),grant);},ignored->refresh());
|
||||
}
|
||||
private <T>void async(Supplier<T> work,java.util.function.Consumer<T> success) {
|
||||
long request=++generation;busy=true;setManual(automation.snapshot().manualAllowed());
|
||||
CompletableFuture.supplyAsync(work).whenComplete((value,error)->Platform.runLater(()->{
|
||||
if(request!=generation)return;busy=false;setManual(automation.snapshot().manualAllowed());
|
||||
if(error!=null) {Throwable cause=error;while(cause.getCause()!=null)cause=cause.getCause();status.setText(cause.getMessage());}
|
||||
else success.accept(value);
|
||||
}));
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package p.studio.ui.javafx.workspaces.dev;
|
||||
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.VBox;
|
||||
import p.studio.ui.javafx.utilities.i18n.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Read-only inspection of the shared facts; this surface cannot perform recovery. */
|
||||
final class RuntimeObservationPane extends VBox {
|
||||
private final TreeView<String> tree = new TreeView<>();
|
||||
private final I18nService i18n;
|
||||
RuntimeObservationPane(I18nService i18n) {
|
||||
super(6); this.i18n = i18n;
|
||||
var heading = new Label(); heading.textProperty().bind(i18n.bind(I18n.DEV_OBSERVATIONS));
|
||||
tree.setId("dev-runtime-observation"); tree.setShowRoot(false); tree.setPrefHeight(260);
|
||||
getChildren().addAll(heading, tree);
|
||||
}
|
||||
void show(DevWorkspaceProjection view) {
|
||||
var root = new TreeItem<String>("");
|
||||
root.getChildren().add(node(i18n.text(I18n.DEV_CONTROL_OBSERVATION), view.controlObservation() == null ? null : view.controlObservation().toMap()));
|
||||
root.getChildren().add(node(i18n.text(I18n.DEV_RUNTIME_CURRENT), view.runtimeObservation() == null ? null : view.runtimeObservation().toMap()));
|
||||
root.getChildren().add(node(i18n.text(I18n.DEV_RUNTIME_FINAL), view.operationObservation() == null ? null : view.operationObservation().toMap()));
|
||||
root.getChildren().forEach(item -> item.setExpanded(true));
|
||||
tree.setRoot(root);
|
||||
}
|
||||
private static TreeItem<String> node(String name, Object value) {
|
||||
var item = new TreeItem<String>(name);
|
||||
if (value instanceof Map<?, ?> map) map.forEach((key, child) -> item.getChildren().add(node(String.valueOf(key), child)));
|
||||
else if (value instanceof List<?> list) {
|
||||
for (int at = 0; at < list.size(); at++) item.getChildren().add(node(Integer.toString(at), list.get(at)));
|
||||
} else item.setValue(name + ": " + Objects.toString(value, "null"));
|
||||
return item;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package p.studio.ui.javafx.workspaces.tests;
|
||||
|
||||
import javafx.animation.*;
|
||||
import javafx.application.Platform;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.Node;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.layout.*;
|
||||
import javafx.util.Duration;
|
||||
import javafx.util.StringConverter;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.operation.OperationSubscription;
|
||||
import p.studio.api.session.ProjectSession;
|
||||
import p.studio.ui.javafx.events.StudioEventBus;
|
||||
import p.studio.ui.javafx.utilities.i18n.I18n;
|
||||
import p.studio.ui.javafx.workspaces.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/** Project test surface; all execution and result semantics belong to the shared service. */
|
||||
public final class TestsWorkspace extends Workspace {
|
||||
private final ProjectSession project;
|
||||
private final GuestTestTools tools;
|
||||
private final Executor executor;
|
||||
private final VBox body=new VBox(10);
|
||||
private final ScrollPane root=new ScrollPane(body);
|
||||
private final ComboBox<String> target=new ComboBox<>();
|
||||
private final ComboBox<GuestTestTools.Media> media=new ComboBox<>();
|
||||
private final ComboBox<GuestTestTools.View> imageOwner=new ComboBox<>();
|
||||
private final Spinner<Integer> frames=new Spinner<>(1,1_000_000,120),block=new Spinner<>(1,60,1),seconds=new Spinner<>(1,3600,30);
|
||||
private final CheckBox discard=new CheckBox("Discard unsaved RAM when closing this test");
|
||||
private final Button run=new Button("Run tests"),cancel=new Button("Cancel"),close=new Button("Close retained runtime");
|
||||
private final ListView<GuestTestTools.View> history=new ListView<>();
|
||||
private final TreeView<String> cases=new TreeView<>();
|
||||
private final Label status=new Label("Select a declared test target"),identity=new Label(),transcriptStatus=new Label();
|
||||
private final TextArea transcript=new TextArea(),details=new TextArea();
|
||||
private final ProgressBar progress=new ProgressBar(0);
|
||||
private OperationSubscription authority;
|
||||
private final Timeline polling;
|
||||
private boolean loading,active;
|
||||
private long generation;
|
||||
private p.studio.ui.javafx.workspaces.dev.EvidenceInspector evidence;
|
||||
private String shownCapture;
|
||||
public TestsWorkspace(ProjectSession project,GuestTestTools tools,Executor executor,StudioEventBus events) {
|
||||
super(project.projectReference(),events);this.project=project;this.tools=tools;this.executor=executor;
|
||||
body.setPadding(new Insets(16));root.setFitToWidth(true);
|
||||
target.setId("tests-target");media.setId("tests-media");run.setId("tests-run");cancel.setId("tests-cancel");close.setId("tests-close-runtime");
|
||||
history.setId("tests-history");cases.setId("tests-cases");status.setId("tests-status");details.setId("tests-details");transcript.setId("tests-transcript");discard.setId("tests-discard-unsaved");
|
||||
media.getItems().setAll(GuestTestTools.Media.values());media.setValue(GuestTestTools.Media.memory_fresh);
|
||||
media.setConverter(new StringConverter<>() {
|
||||
public String toString(GuestTestTools.Media value){return value==null?"":switch(value){case memory_fresh->"Fresh RAM";case disposable_create->"Create disposable card";case disposable_reopen->"Reopen test card";};}
|
||||
public GuestTestTools.Media fromString(String value){throw new UnsupportedOperationException();}
|
||||
});
|
||||
var names=new StringConverter<GuestTestTools.View>() {
|
||||
public String toString(GuestTestTools.View value){return value==null?"":(value.result()==null?value.operation().state():value.result().targetId()+" — "+value.result().completion()+" / "+value.result().verdict())+" — "+value.runId();}
|
||||
public GuestTestTools.View fromString(String value){throw new UnsupportedOperationException();}
|
||||
};
|
||||
imageOwner.setConverter(names);
|
||||
history.setCellFactory(ignored->new ListCell<>(){@Override protected void updateItem(GuestTestTools.View value,boolean empty){super.updateItem(value,empty);setText(empty?null:names.toString(value));}});
|
||||
history.setPrefHeight(120);cases.setPrefHeight(260);cases.setShowRoot(true);
|
||||
history.getSelectionModel().selectedItemProperty().addListener((observable,before,after)->show(after));
|
||||
transcript.setEditable(false);transcript.setPrefRowCount(8);details.setEditable(false);details.setPrefRowCount(5);
|
||||
identity.setWrapText(true);status.setWrapText(true);progress.setMaxWidth(Double.MAX_VALUE);
|
||||
run.setOnAction(event->start());
|
||||
cancel.setOnAction(event->{var selected=history.getSelectionModel().getSelectedItem();if(selected!=null)background(()->{tools.cancel(projectReference.rootPath(),null,selected.operation().id().value());return null;});});
|
||||
close.setOnAction(event->{var selected=history.getSelectionModel().getSelectedItem();boolean discardRam=discard.isSelected();if(selected!=null)background(()->{tools.shutdown(projectReference.rootPath(),null,selected.operation().id().value(),discardRam);return null;});});
|
||||
media.valueProperty().addListener((observable,before,after)->imageOwner.setDisable(after!=GuestTestTools.Media.disposable_reopen));imageOwner.setDisable(true);
|
||||
var bounds=new FlowPane(10,8,new Label("Maximum frames"),frames,new Label("Frames per block"),block,new Label("Timeout (seconds)"),seconds);
|
||||
body.getChildren().addAll(new Label("Project tests"),new FlowPane(10,8,new Label("Target"),target,new Label("Media"),media,imageOwner),bounds,
|
||||
discard,new HBox(10,run,cancel,close),status,progress,identity,history,cases,new TitledPane("Failure and provenance",details),transcriptStatus,transcript);
|
||||
project.evidenceTools().ifPresent(toolsPort->{evidence=new p.studio.ui.javafx.workspaces.dev.EvidenceInspector(projectReference.rootPath(),project.automation(),toolsPort);var pane=new TitledPane("Original checkpoint evidence",evidence);pane.setExpanded(false);body.getChildren().add(pane);});
|
||||
polling=new Timeline(new KeyFrame(Duration.millis(300),event->refresh()));polling.setCycleCount(Animation.INDEFINITE);controls();
|
||||
}
|
||||
private void start() {
|
||||
if(target.getValue()==null)return;
|
||||
String selected=target.getValue();var selectedMedia=media.getValue();var prior=imageOwner.getValue();
|
||||
if(selectedMedia==GuestTestTools.Media.disposable_reopen&&prior==null){status.setText("Select the earlier run that created the disposable card");return;}
|
||||
var request=new GuestTestTools.Request(selected,frames.getValue(),block.getValue(),seconds.getValue()*1000L,selectedMedia,
|
||||
selectedMedia==GuestTestTools.Media.disposable_reopen&&prior!=null?prior.runId():null,discard.isSelected());
|
||||
background(()->tools.start(projectReference.rootPath(),null,"human-test:"+UUID.randomUUID(),request));
|
||||
}
|
||||
private <T> void background(Callable<T> work) {
|
||||
if(loading)return;loading=true;controls();long epoch=generation;
|
||||
CompletableFuture.supplyAsync(()->{try{return work.call();}catch(Exception error){throw new CompletionException(error);}},executor)
|
||||
.whenComplete((value,error)->Platform.runLater(()->{if(epoch!=generation)return;loading=false;if(error!=null)status.setText(message(error));controls();refresh();}));
|
||||
}
|
||||
private static String message(Throwable error){while(error instanceof CompletionException&&error.getCause()!=null)error=error.getCause();return Objects.requireNonNullElse(error.getMessage(),error.getClass().getSimpleName());}
|
||||
private void refresh() {
|
||||
if(!active||loading)return;loading=true;long epoch=generation;
|
||||
CompletableFuture.supplyAsync(()->Map.entry(tools.targets(projectReference.rootPath(),null),tools.list(projectReference.rootPath(),null)),executor)
|
||||
.whenComplete((value,error)->Platform.runLater(()->{
|
||||
if(epoch!=generation)return;loading=false;
|
||||
if(error!=null){status.setText(message(error));controls();return;}
|
||||
String selectedTarget=target.getValue();target.getItems().setAll(value.getKey().targets().stream().map(GuestTests.Target::id).toList());
|
||||
if(selectedTarget!=null&&target.getItems().contains(selectedTarget))target.setValue(selectedTarget);else if(!target.getItems().isEmpty())target.setValue(target.getItems().getFirst());
|
||||
var before=history.getSelectionModel().getSelectedItem();String selected=before==null?null:before.runId();
|
||||
var owner=imageOwner.getValue();String ownerId=owner==null?null:owner.runId();
|
||||
history.getItems().setAll(value.getValue());imageOwner.getItems().setAll(value.getValue().stream().filter(v->v.result()!=null&&"disposable_create".equals(v.result().context().get("media"))).toList());
|
||||
imageOwner.getItems().stream().filter(v->v.runId().equals(ownerId)).findFirst().ifPresent(imageOwner::setValue);
|
||||
var choose=value.getValue().stream().filter(v->v.runId().equals(selected)).findFirst().orElse(value.getValue().isEmpty()?null:value.getValue().getLast());
|
||||
history.getSelectionModel().select(choose);show(choose);controls();
|
||||
}));
|
||||
}
|
||||
private void show(GuestTestTools.View value) {
|
||||
if(value==null){controls();return;}
|
||||
var result=value.result();var known=value.progress().completedFrames();
|
||||
progress.setProgress(known==null?-1:(double)known/value.progress().requestedFrames());
|
||||
identity.setText("Run "+value.runId()+" · operation "+value.operation().id().value()+" · "+value.operation().state()+" · worker terminated: "+value.workerTerminated());
|
||||
if(result!=null) {
|
||||
status.setText(result.targetId()+" — "+result.completion()+" / "+result.verdict());
|
||||
var tree=new TreeItem<String>("Cases — "+result.verdict());tree.setExpanded(true);
|
||||
for(var c:result.cases()) {
|
||||
var row=new TreeItem<String>(c.id()+" — "+(c.state()==null?"running":c.state()));row.setExpanded(true);
|
||||
for(var a:c.assertions())row.getChildren().add(new TreeItem<>((a.passed()?"PASS ":"FAIL ")+a.name()+": "+a.message()+
|
||||
(a.expectedAvailable()?" · expected="+a.expected():"")+(a.actualAvailable()?" · actual="+a.actual():"")));
|
||||
for(var id:c.checkpointIds())row.getChildren().add(new TreeItem<>("Original checkpoint: "+id));tree.getChildren().add(row);
|
||||
}
|
||||
cases.setRoot(tree);var entries=result.transcript();int start=Math.max(0,entries.size()-200);
|
||||
transcriptStatus.setText("Transcript: showing "+(entries.size()-start)+" of "+entries.size()+" retained entries");
|
||||
var text=new StringBuilder();for(var entry:entries.subList(start,entries.size()))text.append(entry.nativeEvent().sequence()).append(" · frame ").append(entry.nativeEvent().frame()).append(" · ").append(entry.nativeEvent().message()).append('\n');
|
||||
transcript.setText(text.toString());
|
||||
details.setText("Build: "+result.buildId()+"\nSession: "+result.sessionId()+"\n"+(result.failure()==null?"":result.failure().code()+": "+result.failure().message()+"\n"+result.failure().runtimeError()+"\n")+result.context());
|
||||
var capture=result.context().get("captureArtifactId");
|
||||
if(evidence!=null&&capture instanceof String id&&!id.equals(shownCapture)){shownCapture=id;evidence.refresh();}
|
||||
}
|
||||
controls();
|
||||
}
|
||||
private void controls() {
|
||||
boolean manual=project.automation().snapshot().manualAllowed();var selected=history.getSelectionModel().getSelectedItem();
|
||||
run.setDisable(!manual||loading||target.getValue()==null);cancel.setDisable(!manual||loading||selected==null||selected.workerTerminated());
|
||||
close.setDisable(!manual||loading||selected==null||!selected.workerTerminated()||!selected.runtimeRetained());
|
||||
discard.setDisable(!manual);
|
||||
if(evidence!=null)evidence.setManual(manual);
|
||||
}
|
||||
@Override public WorkspaceId workspaceId(){return WorkspaceId.TESTS;}
|
||||
@Override public I18n title(){return I18n.WORKSPACE_TESTS;}
|
||||
@Override public Node rootNode(){return root;}
|
||||
@Override public void load(){if(active)return;active=true;generation++;authority=project.automation().subscribe(snapshot->Platform.runLater(()->{if(active)controls();}));polling.play();refresh();}
|
||||
@Override public void unLoad(){active=false;generation++;loading=false;polling.stop();if(authority!=null){authority.unsubscribe();authority=null;}}
|
||||
}
|
||||
@@ -383,3 +383,9 @@ dev.mcpReconnecting=Assistant reconnecting
|
||||
|
||||
dev.discardGameData=Discard unsaved game data and return control
|
||||
dev.discardGameDataConfirm=Cancel pending writes and discard any game data that remains unsaved? A write already published may persist.
|
||||
dev.observations=Runtime and recovery observations
|
||||
dev.controlObservation=Current authority and cleanup
|
||||
dev.runtimeCurrent=Current session (last known facts)
|
||||
dev.runtimeFinal=Last operation conclusion (historical facts)
|
||||
|
||||
workspace.tests=Tests
|
||||
|
||||
@@ -54,3 +54,9 @@ dev.mcpReconnecting=Assistente reconectando
|
||||
|
||||
dev.discardGameData=Descartar dados não gravados do jogo e retomar controle
|
||||
dev.discardGameDataConfirm=Cancelar gravações pendentes e descartar os dados do jogo que ainda não foram gravados? Uma gravação já publicada pode persistir.
|
||||
dev.observations=Observações de execução e recuperação
|
||||
dev.controlObservation=Autoridade e limpeza atuais
|
||||
dev.runtimeCurrent=Sessão atual (últimos fatos conhecidos)
|
||||
dev.runtimeFinal=Conclusão da última operação (fatos históricos)
|
||||
|
||||
workspace.tests=Testes
|
||||
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package p.studio.ui.javafx.diagnostics;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DiagnosticNavigationTest {
|
||||
@TempDir Path root;
|
||||
@Test void unicodeRangeIsSelectedOnlyForMatchingAdmittedRevision() throws Exception {
|
||||
Path file = root.resolve("main.pbs"); byte[] bytes = "// á 😀\r\nfn x() {}\n".getBytes(java.nio.charset.StandardCharsets.UTF_8); Files.write(file, bytes);
|
||||
String sha = HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
var origin = Map.<String, Object>of("uri", file.toUri().toString(), "revision", sha, "range", Map.of("start", Map.of("line", 1, "character", 3), "end", Map.of("line", 1, "character", 4)));
|
||||
var current = DiagnosticNavigation.read(root, origin); assertEquals("x", current.text().substring(current.start(), current.end()));
|
||||
Files.writeString(file, "changed"); var stale = DiagnosticNavigation.read(root, origin);
|
||||
assertTrue(stale.status().startsWith("Stale")); assertEquals(0, stale.start()); assertEquals(0, stale.end());
|
||||
assertNull(DiagnosticNavigation.read(root.resolve("other"), origin).path());
|
||||
assertNull(DiagnosticNavigation.read(root, Map.of("uri", "prometeu-source:unowned")).path());
|
||||
assertNull(DiagnosticNavigation.read(root, Map.of()).path());
|
||||
}
|
||||
}
|
||||
+11
@@ -7,6 +7,17 @@ import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DevWorkspaceProjectionTest {
|
||||
@Test void projectionKeepsHistoricalOperationAndCurrentSessionSeparate() {
|
||||
var finished = RuntimeObservation.unknown("session", "build").withProgress(new TrackedOperation.Progress(3L, 3L));
|
||||
var reset = finished.transition(RuntimeObservation.Lifecycle.UNBOOTED, "reset", java.util.Map.of());
|
||||
var control = new ControlObservation(ControlState.RETURNING_CONTROL, ControlObservation.Cleanup.FAILED, true, false,
|
||||
new AutomationFailure(AutomationFailure.Code.CLEANUP_FAILED, "refused"));
|
||||
var snapshot = new AutomationSnapshot(Path.of("."), ControlState.RETURNING_CONTROL, false, false, 0, null, null,
|
||||
null, true, List.of(), List.of(), java.util.Map.of(), reset, control, finished);
|
||||
var view = DevWorkspaceProjection.from(snapshot);
|
||||
assertSame(finished, view.operationObservation()); assertSame(reset, view.runtimeObservation());
|
||||
assertSame(control, view.controlObservation()); assertFalse(view.grantEnabled()); assertTrue(view.reclaimEnabled());
|
||||
}
|
||||
@Test void actionMappingUsesAuthorityAndNeverInventsAnEndpointOrFrame() {
|
||||
for (var state : ControlState.values()) {
|
||||
var view = DevWorkspaceProjection.from(snapshot(state, null, false, false));
|
||||
|
||||
Reference in New Issue
Block a user