From 55788e3e6bc8c8fa66e89e55f1bbe77b2b2c9dbb Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:33:51 -0500 Subject: [PATCH 1/4] Reproduce a stopped local launch publishing its late Android asset result --- .../AlphaAgentServiceLocalHandoffTest.java | 52 ++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java b/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java index 6ae1b7bba3..fea17055f6 100644 --- a/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java +++ b/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java @@ -13,9 +13,17 @@ import android.app.Application; import android.app.Service; import android.content.Context; +import android.content.ContextWrapper; +import android.content.res.AssetManager; +import android.content.res.Resources; import android.content.Intent; import android.content.SharedPreferences; import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -25,6 +33,7 @@ import org.robolectric.RuntimeEnvironment; import org.robolectric.android.controller.ServiceController; import org.robolectric.annotation.Config; +import org.robolectric.util.ReflectionHelpers; /** * Verifies zero-cloud local runner handoff in {@link AlphaAgentService} and {@link AlphaLocalAgentRunner}: @@ -98,7 +107,7 @@ public void explicitActionStopInLocalModeStopsLocalRunner() { } @Test - public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() { + public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() throws Exception { AlphaLocalAgentRunner runner = AlphaLocalAgentRunner.shared(app); assertFalse(runner.isActive()); @@ -121,6 +130,47 @@ public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() { runner.stop(); assertFalse(runner.isActive()); assertEquals("stopped", runner.statusJson().optString("state")); + assertObsoletePayloadCannotPublish(false); + assertObsoletePayloadCannotPublish(true); + } + + private void assertObsoletePayloadCannotPublish(boolean startAgain) throws Exception { + CountDownLatch reading = new CountDownLatch(1); + CountDownLatch unavailable = new CountDownLatch(1); + Context packages = new ContextWrapper(app) { + @Override public Context getApplicationContext() { return this; } + @Override public AssetManager getAssets() { + reading.countDown(); + try { + if (!unavailable.await(10, TimeUnit.SECONDS)) throw new AssertionError("The asset read was not released"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return Resources.getSystem().getAssets(); + } + }; + AlphaLocalAgentRunner runner = ReflectionHelpers.callConstructor(AlphaLocalAgentRunner.class, + ReflectionHelpers.ClassParameter.from(Context.class, packages)); + ScheduledThreadPoolExecutor launches = ReflectionHelpers.getField(runner, "serial"); + try { + runner.start(Map.of(), null); + assertTrue("Local launch reached Android assets", reading.await(10, TimeUnit.SECONDS)); + Future afterRead = launches.submit(runner::statusJson); + runner.stop(); + if (startAgain) runner.start(Map.of(), null); + JSONObject afterCommand = runner.statusJson(); + unavailable.countDown(); + JSONObject afterOldLaunch = afterRead.get(10, TimeUnit.SECONDS); + assertEquals(startAgain ? "starting" : "stopped", afterOldLaunch.getString("state")); + assertEquals(afterCommand.getLong("epoch"), afterOldLaunch.getLong("epoch")); + assertFalse(afterOldLaunch.has("failure")); + } finally { + unavailable.countDown(); + runner.stop(); + launches.shutdown(); + assertTrue(launches.awaitTermination(10, TimeUnit.SECONDS)); + } } @Test From 7d6562798acadbb5954594a3d3b85a5892dbf865 Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:33:51 -0500 Subject: [PATCH 2/4] Fence native local agent status and child cleanup to their launch epochs --- .../alphaphone/AlphaLocalAgentRunner.java | 224 ++++++++---------- 1 file changed, 103 insertions(+), 121 deletions(-) diff --git a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java index 1f79ed0dce..1b464ef3ca 100644 --- a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java +++ b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java @@ -97,13 +97,14 @@ private enum Phase { STOPPED, STARTING, RUNNING, FAILED } private final AtomicLong nextEpoch = new AtomicLong(1_000L); private final Object lifecycleLock = new Object(); - private volatile Phase phase = Phase.STOPPED; - private volatile long activeEpoch; - private volatile String failureReason; - private volatile String errorDetail; - private volatile boolean desiredRunning; - private volatile Path activeSocket; - private volatile String activeToken; + private record Status(Phase phase, long epoch, String failure, String detail) { + static Status starting(long epoch) { return new Status(Phase.STARTING, epoch, null, null); } + } + private static final Status STOPPED = new Status(Phase.STOPPED, 0L, null, null); + private volatile Status status = STOPPED; + private long handoffEpoch; + private volatile long childEpoch; + private Path activeSocket; private Process childProcess; private ScheduledFuture watchdogTask; private ScheduledFuture restartTask; @@ -139,7 +140,7 @@ public static AutoCloseable onReady(Runnable observer) { Objects.requireNonNull(observer); READY_OBSERVERS.add(observer); AlphaLocalAgentRunner current = instance; - if (current != null && current.phase == Phase.RUNNING) { + if (current != null && current.status.phase() == Phase.RUNNING) { NOTICES.execute(observer); } return () -> READY_OBSERVERS.remove(observer); @@ -147,21 +148,19 @@ public static AutoCloseable onReady(Runnable observer) { /** True while this runner owns a starting, running, or locally failed agent lifecycle. */ public boolean isActive() { - return desiredRunning; + return status.phase() != Phase.STOPPED; } /** True when the local Node 26 agent is healthy and serving on {@link AgentService#channel()}. */ public boolean isRunning() { - return phase == Phase.RUNNING && AgentService.channel().policy().servingEpoch() == activeEpoch && activeEpoch > 0; + Status current = status; + return current.phase() == Phase.RUNNING && AgentService.channel().policy().servingEpoch() == current.epoch(); } /** Returns the {@code ElizaAgent.getStatus()} JSON snapshot for the local runner. */ public JSONObject statusJson() { - Phase current = phase; - if (current == Phase.STOPPED && desiredRunning) { - current = Phase.STARTING; - } - String state = switch (current) { + Status current = status; + String state = switch (current.phase()) { case STOPPED -> "stopped"; case STARTING -> "starting"; case RUNNING -> "running"; @@ -171,12 +170,12 @@ public JSONObject statusJson() { try { out.put("available", true) .put("state", state) - .put("epoch", current == Phase.STOPPED ? 0L : activeEpoch) + .put("epoch", current.epoch()) .put("requestBodyLimit", AgentService.REQUEST_BODY_LIMIT) .put("mode", "local"); - if (current == Phase.FAILED) { - if (failureReason != null) out.put("failure", failureReason); - if (errorDetail != null) out.put("error", errorDetail); + if (current.phase() == Phase.FAILED) { + out.put("failure", current.failure()); + out.put("error", current.detail()); } } catch (JSONException impossible) { throw new IllegalStateException(impossible); @@ -184,35 +183,31 @@ public JSONObject statusJson() { return out; } - private long reserveEpoch() { - long channelLast = AgentService.channel().policy().lastEpoch(); - return nextEpoch.updateAndGet(current -> Math.max(current, channelLast) + 1L); + private long beginLaunch(boolean handoff) { + var policy = AgentService.channel().policy(); + handoffEpoch = handoff ? policy.servingEpoch() : 0L; + long epoch = nextEpoch.updateAndGet(current -> policy.firstOpenable(current + 1L)); + status = Status.starting(epoch); + notifyObservers(); + return epoch; } /** Starts the local Node 26 agent if not already starting or running. */ public void start(Map environment, AgentConfig.GoogleConsent consent) { Map envCopy = environment == null ? Map.of() : Map.copyOf(environment); synchronized (lifecycleLock) { - desiredRunning = true; - long launchEpoch; - if (phase == Phase.STARTING || phase == Phase.RUNNING) { - launchEpoch = activeEpoch; - } else { - launchEpoch = reserveEpoch(); - activeEpoch = launchEpoch; - phase = Phase.STARTING; - failureReason = null; - errorDetail = null; + if (status.phase() != Phase.STARTING && status.phase() != Phase.RUNNING) { + beginLaunch(true); } - long targetEpoch = launchEpoch; + long targetEpoch = status.epoch(); serial.execute(() -> { - if (!desiredRunning || activeEpoch != targetEpoch) return; + if (status.epoch() != targetEpoch) return; lastEnvironment = envCopy; lastConsent = consent; restartAttempt = 0; cancelRestartLocked(); - if (phase == Phase.RUNNING && childProcess != null) return; - if (phase == Phase.STARTING && childProcess != null) return; + if (childProcess != null && childEpoch == targetEpoch) return; + teardownChildLocked(); launchLocked(targetEpoch, envCopy, consent); }); } @@ -222,14 +217,9 @@ public void start(Map environment, AgentConfig.GoogleConsent con public void restart(Map environment, AgentConfig.GoogleConsent consent) { Map envCopy = environment == null ? Map.of() : Map.copyOf(environment); synchronized (lifecycleLock) { - desiredRunning = true; - long targetEpoch = reserveEpoch(); - activeEpoch = targetEpoch; - phase = Phase.STARTING; - failureReason = null; - errorDetail = null; + long targetEpoch = beginLaunch(true); serial.execute(() -> { - if (!desiredRunning || activeEpoch != targetEpoch) return; + if (status.epoch() != targetEpoch) return; lastEnvironment = envCopy; lastConsent = consent; restartAttempt = 0; @@ -244,21 +234,13 @@ public void restart(Map environment, AgentConfig.GoogleConsent c public void stop() { long serving; synchronized (lifecycleLock) { - desiredRunning = false; - serving = activeEpoch; - phase = Phase.STOPPED; - failureReason = null; - errorDetail = null; + serving = childEpoch; + status = STOPPED; + notifyObservers(); serial.execute(() -> { restartAttempt = 0; cancelRestartLocked(); teardownChildLocked(); - if (!desiredRunning) { - phase = Phase.STOPPED; - failureReason = null; - errorDetail = null; - notifyObservers(); - } }); } if (serving > 0L) AgentService.channel().retire(serving); @@ -284,25 +266,24 @@ public boolean awaitReady(long timeoutMs) { } private void launchLocked(long epoch, Map environment, AgentConfig.GoogleConsent consent) { - activeEpoch = epoch; - phase = Phase.STARTING; - failureReason = null; - errorDetail = null; - notifyObservers(); + if (status.epoch() != epoch) return; AgentConfig config; try { config = AgentService.config(appContext); } catch (AgentConfig.Refused | IOException refused) { - failLocked("config", refused.getMessage()); + failLocked(epoch, "config", refused.getMessage()); return; } AgentChannel channel = AgentService.channel(); - channel.policy().loadRoutes(CallerKind.NATIVE, config.routes(CallerKind.NATIVE)); - if (!channel.policy().loadRoutes(CallerKind.RENDERER, config.routes(CallerKind.RENDERER))) { - failLocked("config", "The agent renderer route list could not be loaded"); - return; + synchronized (lifecycleLock) { + if (status.epoch() != epoch) return; + channel.policy().loadRoutes(CallerKind.NATIVE, config.routes(CallerKind.NATIVE)); + if (!channel.policy().loadRoutes(CallerKind.RENDERER, config.routes(CallerKind.RENDERER))) { + failLocked(epoch, "config", "The agent renderer route list could not be loaded"); + return; + } } AgentDirectories directories = new AgentDirectories(appContext.getFilesDir().toPath(), AndroidRuntimeDirectories::syncRuntimeDirectory); @@ -317,15 +298,16 @@ private void launchLocked(long epoch, Map environment, AgentConf directories.sync() ); if (check instanceof PayloadCheck.Failed failed) { - failLocked("payload", String.join("; ", failed.errors())); + failLocked(epoch, "payload", String.join("; ", failed.errors())); return; } prepared = AlphaDevBuild.agent(appContext, ((PayloadCheck.Ready) check).payload()); } catch (IOException | PackageManager.NameNotFoundException failed) { - failLocked("payload", "The agent runtime could not be verified: " + failed.getMessage()); + failLocked(epoch, "payload", "The agent runtime could not be verified: " + failed.getMessage()); return; } + if (status.epoch() != epoch) return; String token = LaunchFrame.newToken(); try { @@ -372,9 +354,12 @@ private void launchLocked(long epoch, Map environment, AgentConf } childProcess = spawned; - activeEpoch = epoch; + childEpoch = epoch; activeSocket = socketPath; - activeToken = token; + if (status.epoch() != epoch) { + teardownChildLocked(); + return; + } Log.i(TAG, "Spawned zero-cloud local agent epoch=" + epoch + " socket=" + socketPath); Thread exitWatcher = new Thread(() -> watchExit(spawned, epoch), "AlphaLocalAgentExit"); @@ -386,13 +371,13 @@ private void launchLocked(long epoch, Map environment, AgentConf readyWatcher.start(); } catch (IOException | JSONException | RuntimeException failed) { Log.e(TAG, "Failed to spawn zero-cloud local agent", failed); - failLocked("spawn", failed.getMessage() == null ? "Local agent failed to spawn" : failed.getMessage()); + failLocked(epoch, "spawn", failed.getMessage() == null ? "Local agent failed to spawn" : failed.getMessage()); } } private void awaitChildReady(Process process, long epoch, Path socketPath, String token) { long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(READY_TIMEOUT_MS); - while (process.isAlive() && activeEpoch == epoch && desiredRunning) { + while (process.isAlive() && status.epoch() == epoch) { enforceSocketPermissions(socketPath); HealthPolicy.ProbeReply reply = probeHealth(socketPath, token, process::isAlive); if (HealthPolicy.classify(reply, epoch) == HealthPolicy.Probe.OK) { @@ -403,10 +388,10 @@ private void awaitChildReady(Process process, long epoch, Path socketPath, Strin long remaining = deadline - System.nanoTime(); if (remaining <= 0L) { serial.execute(() -> { - if (childProcess == process && activeEpoch == epoch) { + if (childProcess == process && status.epoch() == epoch) { Log.w(TAG, "Local agent readiness timed out for epoch=" + epoch); teardownChildLocked(); - failOrScheduleRestartLocked("timeout", "Local agent did not become healthy in time"); + failOrScheduleRestartLocked(epoch, "timeout", "Local agent did not become healthy in time"); } }); return; @@ -420,22 +405,22 @@ private void awaitChildReady(Process process, long epoch, Path socketPath, Strin } private void markReadyLocked(Process process, long epoch, Path socketPath, String token) { - if (childProcess != process || activeEpoch != epoch || !desiredRunning) return; - if (!AgentService.channel().open(epoch, token, socketPath)) { - long currentServing = AgentService.channel().policy().servingEpoch(); - if (currentServing > 0L && currentServing != epoch) { - AgentService.channel().retire(currentServing); - } - if (!AgentService.channel().open(epoch, token, socketPath)) { - teardownChildLocked(); - failLocked("channel", "Could not open local agent channel for epoch " + epoch); - return; + synchronized (lifecycleLock) { + if (childProcess != process || status.epoch() != epoch) return; + AgentChannel channel = AgentService.channel(); + long serving = channel.policy().servingEpoch(); + if (serving > 0L && serving == handoffEpoch) channel.retire(serving); + if (channel.open(epoch, token, socketPath)) { + status = new Status(Phase.RUNNING, epoch, null, null); + } else { + failLocked(epoch, "channel", "Could not open local agent channel for epoch " + epoch); } } - phase = Phase.RUNNING; + if (status.phase() != Phase.RUNNING || status.epoch() != epoch) { + teardownChildLocked(); + return; + } restartAttempt = 0; - failureReason = null; - errorDetail = null; Log.i(TAG, "Zero-cloud local agent ready epoch=" + epoch); startWatchdogLocked(process, epoch, socketPath); notifyObservers(); @@ -454,71 +439,68 @@ private void watchExit(Process process, long epoch) { } int code = exitCode; serial.execute(() -> { - if (childProcess != process || activeEpoch != epoch) return; + if (childProcess != process) return; Log.i(TAG, "Local agent epoch=" + epoch + " exited code=" + code); cancelWatchdogLocked(); AgentService.channel().retire(epoch); childProcess = null; + childEpoch = 0L; activeSocket = null; - activeToken = null; - if (!desiredRunning) { - phase = Phase.STOPPED; - notifyObservers(); - return; - } - failOrScheduleRestartLocked("exit", "Local agent exited with code " + code); + failOrScheduleRestartLocked(epoch, "exit", "Local agent exited with code " + code); }); } private void startWatchdogLocked(Process process, long epoch, Path socketPath) { cancelWatchdogLocked(); watchdogTask = serial.scheduleWithFixedDelay(() -> { - if (childProcess != process || activeEpoch != epoch || phase != Phase.RUNNING || !desiredRunning) return; + if (childProcess != process || status.epoch() != epoch || status.phase() != Phase.RUNNING) return; if (!process.isAlive() || !socketAccepts(socketPath)) { Log.w(TAG, "Local agent watchdog detected dead process/socket for epoch=" + epoch); teardownChildLocked(); - failOrScheduleRestartLocked("unhealthy", "Local agent stopped accepting connections"); + failOrScheduleRestartLocked(epoch, "unhealthy", "Local agent stopped accepting connections"); } }, WATCHDOG_INTERVAL_MS, WATCHDOG_INTERVAL_MS, TimeUnit.MILLISECONDS); } - private void failOrScheduleRestartLocked(String reason, String detail) { - if (!desiredRunning || restartAttempt >= MAX_RESTART_ATTEMPTS) { - failLocked(reason, detail); - return; - } - long delayMs = HealthPolicy.restartDelay(restartAttempt++); - phase = Phase.STARTING; - failureReason = null; - errorDetail = null; - notifyObservers(); - cancelRestartLocked(); - restartTask = serial.schedule(() -> { - if (desiredRunning && phase != Phase.RUNNING) { - launchLocked(reserveEpoch(), lastEnvironment, lastConsent); + private void failOrScheduleRestartLocked(long epoch, String reason, String detail) { + synchronized (lifecycleLock) { + if (status.epoch() != epoch) return; + if (restartAttempt >= MAX_RESTART_ATTEMPTS) { + failLocked(epoch, reason, detail); + return; } - }, delayMs, TimeUnit.MILLISECONDS); + status = Status.starting(epoch); + notifyObservers(); + cancelRestartLocked(); + restartTask = serial.schedule(() -> { + long next; + synchronized (lifecycleLock) { + if (status.epoch() != epoch || status.phase() != Phase.STARTING) return; + next = beginLaunch(false); + } + launchLocked(next, lastEnvironment, lastConsent); + }, HealthPolicy.restartDelay(restartAttempt++), TimeUnit.MILLISECONDS); + } } - private void failLocked(String reason, String detail) { - cancelWatchdogLocked(); - phase = Phase.FAILED; - failureReason = reason; - errorDetail = detail; - notifyObservers(); + private void failLocked(long epoch, String reason, String detail) { + synchronized (lifecycleLock) { + if (status.epoch() != epoch) return; + cancelWatchdogLocked(); + status = new Status(Phase.FAILED, epoch, reason, detail); + notifyObservers(); + } } private void teardownChildLocked() { cancelWatchdogLocked(); - long retiringEpoch = activeEpoch; + long retiringEpoch = childEpoch; Process stopping = childProcess; Path retiringSocket = activeSocket; childProcess = null; activeSocket = null; - activeToken = null; - if (retiringEpoch > 0L) { - AgentService.channel().retire(retiringEpoch); - } + if (retiringEpoch > 0L) AgentService.channel().retire(retiringEpoch); + childEpoch = 0L; if (stopping != null) { stopping.destroy(); try { From 3846de2bec9021e4f1c1dd7ce7dbfdc3ae79956a Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:38:04 -0500 Subject: [PATCH 3/4] Keep the admitted Cloud handoff through local readiness retries --- .../ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java index 1b464ef3ca..3d6265a117 100644 --- a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java +++ b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java @@ -185,7 +185,7 @@ public JSONObject statusJson() { private long beginLaunch(boolean handoff) { var policy = AgentService.channel().policy(); - handoffEpoch = handoff ? policy.servingEpoch() : 0L; + if (handoff) handoffEpoch = policy.servingEpoch(); long epoch = nextEpoch.updateAndGet(current -> policy.firstOpenable(current + 1L)); status = Status.starting(epoch); notifyObservers(); @@ -235,6 +235,7 @@ public void stop() { long serving; synchronized (lifecycleLock) { serving = childEpoch; + handoffEpoch = 0L; status = STOPPED; notifyObservers(); serial.execute(() -> { @@ -411,6 +412,7 @@ private void markReadyLocked(Process process, long epoch, Path socketPath, Strin long serving = channel.policy().servingEpoch(); if (serving > 0L && serving == handoffEpoch) channel.retire(serving); if (channel.open(epoch, token, socketPath)) { + handoffEpoch = 0L; status = new Status(Phase.RUNNING, epoch, null, null); } else { failLocked(epoch, "channel", "Could not open local agent channel for epoch " + epoch); From 7e311c0bb59bb8e6540fe5871c8992a7ddd99061 Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:39:26 -0500 Subject: [PATCH 4/4] Exercise authorized handoff and independently replaced channel with native policy --- .../alphaphone/AlphaLocalAgentRunner.java | 22 +++++++----- .../AlphaAgentServiceLocalHandoffTest.java | 36 +++++++++++++++++++ 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java index 3d6265a117..4da4d0690d 100644 --- a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java +++ b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaLocalAgentRunner.java @@ -405,20 +405,24 @@ private void awaitChildReady(Process process, long epoch, Path socketPath, Strin } } - private void markReadyLocked(Process process, long epoch, Path socketPath, String token) { + private boolean publishReadyChannel(long epoch, Path socketPath, String token) { synchronized (lifecycleLock) { - if (childProcess != process || status.epoch() != epoch) return; + if (status.epoch() != epoch || status.phase() != Phase.STARTING) return false; AgentChannel channel = AgentService.channel(); - long serving = channel.policy().servingEpoch(); - if (serving > 0L && serving == handoffEpoch) channel.retire(serving); - if (channel.open(epoch, token, socketPath)) { - handoffEpoch = 0L; - status = new Status(Phase.RUNNING, epoch, null, null); - } else { + if (handoffEpoch > 0L) channel.retire(handoffEpoch); + if (!channel.open(epoch, token, socketPath)) { failLocked(epoch, "channel", "Could not open local agent channel for epoch " + epoch); + return false; } + handoffEpoch = 0L; + status = new Status(Phase.RUNNING, epoch, null, null); + return true; } - if (status.phase() != Phase.RUNNING || status.epoch() != epoch) { + } + + private void markReadyLocked(Process process, long epoch, Path socketPath, String token) { + if (childProcess != process) return; + if (!publishReadyChannel(epoch, socketPath, token)) { teardownChildLocked(); return; } diff --git a/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java b/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java index fea17055f6..2545dca788 100644 --- a/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java +++ b/apps/app/android/app/src/test/java/ai/alphacompute/alphaphone/AlphaAgentServiceLocalHandoffTest.java @@ -8,6 +8,7 @@ import ai.alphacompute.alphaphone.ipc.AlphaPreferencesProvider; import ai.alphacompute.ipc.AlphaIpcContract; +import ai.eliza.os.agent.AgentChannel; import ai.eliza.os.agent.AgentConfig; import ai.eliza.os.agent.AgentService; import android.app.Application; @@ -18,6 +19,7 @@ import android.content.res.Resources; import android.content.Intent; import android.content.SharedPreferences; +import java.nio.file.Path; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; @@ -132,6 +134,40 @@ public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() throws Ex assertEquals("stopped", runner.statusJson().optString("state")); assertObsoletePayloadCannotPublish(false); assertObsoletePayloadCannotPublish(true); + assertRetryClaimsOnlyItsOriginalChannel(false); + assertRetryClaimsOnlyItsOriginalChannel(true); + } + + private void assertRetryClaimsOnlyItsOriginalChannel(boolean interveningCloudLaunch) throws Exception { + AlphaLocalAgentRunner runner = ReflectionHelpers.callConstructor(AlphaLocalAgentRunner.class, + ReflectionHelpers.ClassParameter.from(Context.class, app)); + AgentChannel channel = AgentService.channel(); + Path socket = app.getCacheDir().toPath().resolve("handoff.sock"); + long cloud = channel.policy().firstOpenable(1L); + assertTrue(channel.open(cloud, "cloud", socket)); + long serving = cloud; + try { + long first = ReflectionHelpers.callInstanceMethod(runner, "beginLaunch", + ReflectionHelpers.ClassParameter.from(boolean.class, true)); + long retry = ReflectionHelpers.callInstanceMethod(runner, "beginLaunch", + ReflectionHelpers.ClassParameter.from(boolean.class, false)); + assertTrue(retry > first); + if (interveningCloudLaunch) { + assertTrue(channel.retire(cloud)); + serving = retry + 1L; + assertTrue(channel.open(serving, "replacement", socket)); + } + boolean ready = ReflectionHelpers.callInstanceMethod(runner, "publishReadyChannel", + ReflectionHelpers.ClassParameter.from(long.class, retry), + ReflectionHelpers.ClassParameter.from(Path.class, socket), + ReflectionHelpers.ClassParameter.from(String.class, "local")); + assertEquals(!interveningCloudLaunch, ready); + if (ready) serving = retry; + assertEquals(serving, channel.policy().servingEpoch()); + assertEquals(ready ? "running" : "failed", runner.statusJson().getString("state")); + } finally { + channel.retire(serving); + } } private void assertObsoletePayloadCannotPublish(boolean startAgain) throws Exception {