feat(studio): integrate project MCP setup and lifecycle
This commit is contained in:
@@ -23,8 +23,15 @@ public final class ProjectCatalogService implements ProjectCatalog {
|
||||
private final Path projectsRoot;
|
||||
private final ObjectMapper mapper;
|
||||
private final ProjectLocalStudioSetupStore setupStore;
|
||||
private final p.studio.api.automation.AgentIntegrationPreparation integration;
|
||||
|
||||
public ProjectCatalogService(Path projectsRoot, ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore) {
|
||||
this(projectsRoot, mapper, setupStore, p.studio.api.automation.AgentIntegrationPreparation.unavailable());
|
||||
}
|
||||
|
||||
public ProjectCatalogService(Path projectsRoot, ObjectMapper mapper, ProjectLocalStudioSetupStore setupStore,
|
||||
p.studio.api.automation.AgentIntegrationPreparation integration) {
|
||||
this.integration = Objects.requireNonNull(integration);
|
||||
this.projectsRoot = Objects.requireNonNull(projectsRoot, "projectsRoot").toAbsolutePath().normalize();
|
||||
this.mapper = Objects.requireNonNull(mapper, "mapper").copy()
|
||||
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
@@ -103,6 +110,7 @@ public final class ProjectCatalogService implements ProjectCatalog {
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException(exception);
|
||||
}
|
||||
integration.prepare(root); // Readiness is queried by DEV; project creation remains usable on setup failure.
|
||||
return openProject(root);
|
||||
}
|
||||
|
||||
|
||||
+54
-15
@@ -11,6 +11,9 @@ import java.util.function.Consumer;
|
||||
public final class DefaultAutomationSession implements AutomationSession {
|
||||
private final Path root;
|
||||
private final OperationExecutor executor;
|
||||
private final AutomationConnectionLifecycle connections;
|
||||
private AutomationConnectionLifecycle.Publication connection;
|
||||
private CompletableFuture<Void> publicationIdle = CompletableFuture.completedFuture(null);
|
||||
private final List<Consumer<AutomationSnapshot>> listeners = new CopyOnWriteArrayList<>();
|
||||
private final List<DocumentHandoff> documents = new CopyOnWriteArrayList<>();
|
||||
private final Deque<String> calls = new ArrayDeque<>();
|
||||
@@ -34,8 +37,13 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
private CompletableFuture<Void> manualIdle = CompletableFuture.completedFuture(null);
|
||||
|
||||
public DefaultAutomationSession(Path root, OperationExecutor executor) {
|
||||
this(root, executor, AutomationConnectionLifecycle.none());
|
||||
}
|
||||
|
||||
public DefaultAutomationSession(Path root, OperationExecutor executor, AutomationConnectionLifecycle connections) {
|
||||
this.root = root.toAbsolutePath().normalize();
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
this.connections = Objects.requireNonNull(connections);
|
||||
}
|
||||
|
||||
public synchronized ManualLease enterManual() {
|
||||
@@ -101,15 +109,7 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
if (found && !save) return result(ControlResult.Status.DIRTY_DOCUMENTS, "Save all and grant, or cancel");
|
||||
CompletionStage<Void> saved = CompletableFuture.completedFuture(null);
|
||||
if (found) for (var participant : participants) saved = saved.thenCompose(v -> participant.saveAll());
|
||||
return saved.thenCompose(v -> verifySaved(participants)).thenApply(v -> {
|
||||
synchronized (this) {
|
||||
if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated");
|
||||
if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active");
|
||||
state = ControlState.WAITING_FOR_AGENT;
|
||||
record("grant");
|
||||
return ControlResult.of(ControlResult.Status.GRANTED, "");
|
||||
}
|
||||
});
|
||||
return saved.thenCompose(v -> verifySaved(participants)).thenApplyAsync(v -> publishGrant(attempt));
|
||||
}).exceptionally(f -> ControlResult.of(ControlResult.Status.SAVE_FAILED, message(f)))
|
||||
.thenApply(outcome -> {
|
||||
synchronized (this) {
|
||||
@@ -121,6 +121,39 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
});
|
||||
}
|
||||
|
||||
private ControlResult publishGrant(long attempt) {
|
||||
AutomationConnectionLifecycle.Publication prepared = null;
|
||||
boolean committed = false;
|
||||
CompletableFuture<Void> publishing = null;
|
||||
try {
|
||||
synchronized (this) {
|
||||
if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated");
|
||||
publishing = publicationIdle = new CompletableFuture<>();
|
||||
}
|
||||
prepared = connections.prepare(root);
|
||||
prepared.publish();
|
||||
synchronized (this) {
|
||||
if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated");
|
||||
if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active");
|
||||
prepared.activate();
|
||||
connection = prepared; committed = true;
|
||||
state = ControlState.WAITING_FOR_AGENT;
|
||||
record("grant");
|
||||
return ControlResult.of(ControlResult.Status.GRANTED, "");
|
||||
}
|
||||
} catch (AutomationConnectionLifecycle.OwnershipConflict conflict) {
|
||||
return ControlResult.of(ControlResult.Status.CONNECTION_CONFLICT, conflict.getMessage());
|
||||
} catch (Exception failure) {
|
||||
return ControlResult.of(ControlResult.Status.CONNECTION_FAILED, "Assistant connection could not be published: check project access, installation and publication conflicts.");
|
||||
} finally {
|
||||
if (!committed && prepared != null) {
|
||||
prepared.invalidate();
|
||||
try { prepared.close(); } catch (Exception ignored) { /* Credential is already invalid. */ }
|
||||
}
|
||||
if (publishing != null) publishing.complete(null);
|
||||
}
|
||||
}
|
||||
|
||||
private CompletionStage<Void> verifySaved(List<DocumentHandoff> participants) {
|
||||
CompletionStage<Void> check = CompletableFuture.completedFuture(null);
|
||||
for (var p : participants) check = check.thenCompose(v -> p.hasUnsavedChanges().thenAccept(dirty -> {
|
||||
@@ -131,7 +164,7 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
|
||||
@Override public synchronized ControlResult acquire() {
|
||||
if (closed) return ControlResult.of(ControlResult.Status.CLOSED, "Project closed");
|
||||
if (state != ControlState.WAITING_FOR_AGENT) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required");
|
||||
if (state != ControlState.WAITING_FOR_AGENT || handoffPending) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required");
|
||||
task = new TaskIdentity(root, UUID.randomUUID().toString());
|
||||
state = ControlState.AGENT_WORKING; record("acquire"); publish();
|
||||
return new ControlResult(ControlResult.Status.ACQUIRED, task, "");
|
||||
@@ -155,23 +188,29 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
final ManagedHeadlessSession ownedRuntime;
|
||||
final List<Runnable> cancellations;
|
||||
final List<DocumentHandoff> participants;
|
||||
final CompletableFuture<Void> idle;
|
||||
final CompletableFuture<Void> idle, publisherIdle;
|
||||
final List<Runnable> cleanups;
|
||||
final AutomationConnectionLifecycle.Publication publication;
|
||||
synchronized (this) {
|
||||
if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current");
|
||||
if (closing) closed = true;
|
||||
if (returning != null && !returning.isDone()) return returning;
|
||||
if (!closing && state == ControlState.MANUAL) return result(ControlResult.Status.RETURNED, "");
|
||||
if (!closing && state == ControlState.MANUAL && !handoffPending) return result(ControlResult.Status.RETURNED, "");
|
||||
state = ControlState.RETURNING_CONTROL; task = null; generation++; handoffPending = false;
|
||||
record(closing ? "close" : "reclaim"); stale = capture != null;
|
||||
result = returning = new CompletableFuture<>();
|
||||
operation = active; ownedRuntime = runtime; idle = manualIdle;
|
||||
operation = active; ownedRuntime = runtime; idle = manualIdle; publisherIdle = publicationIdle;
|
||||
cancellations = closing ? List.copyOf(manualCancellation) : List.of();
|
||||
participants = closing ? List.of() : List.copyOf(documents);
|
||||
cleanups = List.copyOf(taskCleanup); taskCleanup.clear();
|
||||
publication = connection; connection = null;
|
||||
if (publication != null) publication.invalidate();
|
||||
publish();
|
||||
}
|
||||
// Never call another service while holding the authority monitor: Debug owns its own lock.
|
||||
CompletionStage<Void> publicationCleanup;
|
||||
try { if (publication != null) publication.close(); publicationCleanup = CompletableFuture.completedFuture(null); }
|
||||
catch (Exception failure) { publicationCleanup = CompletableFuture.failedFuture(new IllegalStateException("Connection cleanup failed; access is revoked")); }
|
||||
CompletionStage<Void> cleanup;
|
||||
try {
|
||||
for (var cancellation : cancellations) cancellation.run();
|
||||
@@ -179,14 +218,14 @@ public final class DefaultAutomationSession implements AutomationSession {
|
||||
CompletionStage<Void> stopped = operation == null ? CompletableFuture.completedFuture(null) : operation.termination();
|
||||
CompletionStage<Void> shutdown = CompletableFuture.completedFuture(null);
|
||||
if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(); }
|
||||
cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle);
|
||||
cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle, publisherIdle, publicationCleanup.toCompletableFuture());
|
||||
cleanup = cleanup.whenComplete((v, failure) -> cleanups.forEach(Runnable::run));
|
||||
// Closing disposes documents; an explicit return must refresh them before unlocking.
|
||||
for (var p : participants) cleanup = cleanup.thenCompose(v -> {
|
||||
synchronized (this) { if (closed) return CompletableFuture.completedFuture(null); }
|
||||
return p.refreshFromDisk();
|
||||
});
|
||||
} catch (RuntimeException failure) { cleanup = CompletableFuture.failedFuture(failure); }
|
||||
} catch (Exception failure) { cleanup = CompletableFuture.failedFuture(failure); }
|
||||
cleanup.whenComplete((v, failure) -> {
|
||||
synchronized (this) {
|
||||
if (failure == null) {
|
||||
|
||||
+23
-1
@@ -17,15 +17,35 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
private final LspLifecyclePort lsp;
|
||||
private final p.studio.core.project.ProjectAccessRegistry access;
|
||||
private final p.studio.api.operation.OperationExecutor operations;
|
||||
private final p.studio.api.automation.AutomationConnectionLifecycle connections;
|
||||
private final p.studio.api.automation.AgentIntegrationPreparation preparation;
|
||||
|
||||
public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations) {
|
||||
this(stateStore, setupStore, lsp, access, operations, p.studio.api.automation.AutomationConnectionLifecycle.none());
|
||||
}
|
||||
|
||||
public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations,
|
||||
p.studio.api.automation.AutomationConnectionLifecycle connections) {
|
||||
this(stateStore, setupStore, lsp, access, operations, connections,
|
||||
p.studio.api.automation.AgentIntegrationPreparation.unavailable());
|
||||
}
|
||||
|
||||
public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations,
|
||||
p.studio.api.automation.AutomationConnectionLifecycle connections,
|
||||
p.studio.api.automation.AgentIntegrationPreparation preparation) {
|
||||
this.preparation = Objects.requireNonNull(preparation);
|
||||
this.stateStore = Objects.requireNonNull(stateStore, "stateStore");
|
||||
this.setupStore = Objects.requireNonNull(setupStore, "setupStore");
|
||||
this.lsp = Objects.requireNonNull(lsp, "lsp");
|
||||
this.access = Objects.requireNonNull(access);
|
||||
this.operations = Objects.requireNonNull(operations);
|
||||
this.connections = Objects.requireNonNull(connections);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -33,8 +53,10 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
if (closed) throw new IllegalStateException("Project sessions are closing");
|
||||
final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference");
|
||||
final var setup = setupStore.load(project);
|
||||
// Preparation reports readiness independently; opening never grants agent authority.
|
||||
if (setup.agentIntegration().enabled()) preparation.prepare(project.rootPath());
|
||||
final var state = stateStore.load(project);
|
||||
var automation = new DefaultAutomationSession(project.rootPath(), operations);
|
||||
var automation = new DefaultAutomationSession(project.rootPath(), operations, connections);
|
||||
var ready = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var registration = access.register(project.rootPath(), automation::enterManual,
|
||||
() -> ready.get() && !automation.snapshot().closed(), automation);
|
||||
|
||||
+40
@@ -18,6 +18,46 @@ class DefaultAutomationSessionTest {
|
||||
ControlResult await(CompletionStage<ControlResult> result) { return result.toCompletableFuture().join(); }
|
||||
TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); }
|
||||
|
||||
@Test void publicationIsRequiredAndCloseWaitsForAbortedPublicationWithoutHoldingMonitor() throws Exception {
|
||||
var entered = new CountDownLatch(1); var proceed = new CountDownLatch(1);
|
||||
var active = new java.util.concurrent.atomic.AtomicBoolean(); var cleaned = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var s = new DefaultAutomationSession(root, operations, ignored -> new AutomationConnectionLifecycle.Publication() {
|
||||
public void publish() throws Exception { entered.countDown(); assertTrue(proceed.await(5, TimeUnit.SECONDS)); }
|
||||
public void activate() { active.set(true); }
|
||||
public void invalidate() { active.set(false); }
|
||||
public void close() { cleaned.set(true); }
|
||||
});
|
||||
var grant = s.grant(false).toCompletableFuture();
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
assertEquals(NOT_GRANTED, s.acquire().status());
|
||||
var closing = s.closeAsync().toCompletableFuture();
|
||||
assertFalse(closing.isDone()); assertTrue(s.snapshot().closed());
|
||||
proceed.countDown();
|
||||
assertEquals(CLOSED, grant.get(5, TimeUnit.SECONDS).status());
|
||||
assertEquals(RETURNED, closing.get(5, TimeUnit.SECONDS).status());
|
||||
assertTrue(cleaned.get()); assertFalse(active.get());
|
||||
}
|
||||
@Test void failedPublicationCannotGrantAndCleanupFailureStillCancelsWork() {
|
||||
var s = new DefaultAutomationSession(root, operations, ignored -> { throw new java.io.IOException("private details"); });
|
||||
assertEquals(CONNECTION_FAILED, await(s.grant(false)).status());
|
||||
assertTrue(s.snapshot().manualAllowed()); assertEquals(NOT_GRANTED, s.acquire().status());
|
||||
assertFalse(s.snapshot().diagnostics().toString().contains("private details"));
|
||||
var active = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var next = new DefaultAutomationSession(root, operations, ignored -> new AutomationConnectionLifecycle.Publication() {
|
||||
public void publish() { }
|
||||
public void activate() { active.set(true); }
|
||||
public void invalidate() { active.set(false); }
|
||||
public void close() throws Exception { throw new java.io.IOException("file failure"); }
|
||||
});
|
||||
var task = start(next);
|
||||
next.submit(task, "running", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null));
|
||||
var returned = next.reclaim().toCompletableFuture();
|
||||
assertFalse(active.get()); assertTrue(operations.last.cancelled); assertFalse(returned.isDone());
|
||||
operations.last.finish();
|
||||
assertEquals(CLEANUP_FAILED, returned.join().status());
|
||||
assertTrue(await(next.reclaim()).success());
|
||||
}
|
||||
|
||||
@Test void terminationObserversCanSubmitTheNextOperation() {
|
||||
var s = session(); var task = start(s);
|
||||
var first = s.submit(task, "first", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(), null));
|
||||
|
||||
+34
@@ -107,6 +107,40 @@ final class DefaultProjectSessionTest {
|
||||
registration.unsubscribe();
|
||||
}
|
||||
|
||||
@Test void openingPreparesIntegrationAndRemainsManualEvenWhenPreparationIsIncomplete() {
|
||||
var mapper = new ObjectMapper(); var calls = new java.util.ArrayList<Path>();
|
||||
var published = new java.util.concurrent.atomic.AtomicInteger();
|
||||
try (var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper),
|
||||
new ProjectLocalStudioSetupStore(mapper), new RecordingLsp(), new p.studio.core.project.ProjectAccessRegistry(),
|
||||
new p.studio.core.support.ControlledOperations(), root -> {
|
||||
published.incrementAndGet(); throw new AssertionError("Opening must not publish credentials");
|
||||
}, root -> {
|
||||
calls.add(root); return new p.studio.api.automation.AgentIntegrationPreparation.Result(false, "Installation missing");
|
||||
})) {
|
||||
var first = factory.open(project());
|
||||
assertEquals(java.util.List.of(project().rootPath()), calls);
|
||||
assertTrue(first.automation().snapshot().manualAllowed());
|
||||
assertNull(first.automation().snapshot().task()); assertEquals(0, published.get());
|
||||
first.close();
|
||||
var reopened = factory.open(project());
|
||||
assertEquals(2, calls.size()); assertTrue(reopened.automation().snapshot().manualAllowed());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void explicitDisabledIntegrationIsPreservedOnOpen() {
|
||||
var mapper = new ObjectMapper(); var setup = new ProjectLocalStudioSetupStore(mapper);
|
||||
setup.save(project(), new p.studio.api.project.ProjectLocalStudioSetup(null, null,
|
||||
new p.studio.api.project.ProjectLocalStudioSetup.AgentIntegrationSetup(1, false, "codex")));
|
||||
try (var factory = new DefaultProjectSessionFactory(new ProjectLocalStudioStateStore(mapper), setup,
|
||||
new RecordingLsp(), new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations(),
|
||||
p.studio.api.automation.AutomationConnectionLifecycle.none(), root -> {
|
||||
throw new AssertionError("Disabled integration must not be prepared automatically");
|
||||
})) {
|
||||
assertTrue(factory.open(project()).automation().snapshot().manualAllowed());
|
||||
assertFalse(setup.load(project()).agentIntegration().enabled());
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RecordingLsp implements LspLifecyclePort {
|
||||
int boots;
|
||||
int shutdowns;
|
||||
|
||||
Reference in New Issue
Block a user