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..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 @@ -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(); + if (handoff) handoffEpoch = policy.servingEpoch(); + 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,14 @@ 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; + handoffEpoch = 0L; + 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 +267,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 +299,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 +355,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 +372,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 +389,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; @@ -419,23 +405,28 @@ 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; + private boolean publishReadyChannel(long epoch, Path socketPath, String token) { + synchronized (lifecycleLock) { + if (status.epoch() != epoch || status.phase() != Phase.STARTING) return false; + AgentChannel channel = AgentService.channel(); + 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; + } + } + + private void markReadyLocked(Process process, long epoch, Path socketPath, String token) { + if (childProcess != process) return; + if (!publishReadyChannel(epoch, socketPath, token)) { + teardownChildLocked(); + return; } - phase = Phase.RUNNING; restartAttempt = 0; - failureReason = null; - errorDetail = null; Log.i(TAG, "Zero-cloud local agent ready epoch=" + epoch); startWatchdogLocked(process, epoch, socketPath); notifyObservers(); @@ -454,71 +445,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 { 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..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,14 +8,24 @@ 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; 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.nio.file.Path; 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 +35,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 +109,7 @@ public void explicitActionStopInLocalModeStopsLocalRunner() { } @Test - public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() { + public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() throws Exception { AlphaLocalAgentRunner runner = AlphaLocalAgentRunner.shared(app); assertFalse(runner.isActive()); @@ -121,6 +132,81 @@ public void localRunnerLifecycleTransitionsAreSynchronousAndRaceFree() { runner.stop(); assertFalse(runner.isActive()); 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 { + 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 diff --git a/apps/app/src/assistant/follow.tsx b/apps/app/src/assistant/follow.tsx index 24c02d0fd2..39d8c5aaeb 100644 --- a/apps/app/src/assistant/follow.tsx +++ b/apps/app/src/assistant/follow.tsx @@ -145,7 +145,9 @@ function ghostOf(section: HTMLElement, composer: boolean) { } /** Ends a sheet's motions where they stand. */ -function stop(motions: readonly Animation[]) { +function stop(owner: RefObject) { + const motions = owner.current; + owner.current = []; for (const motion of motions) { motion.finished.catch(() => undefined); motion.cancel(); @@ -327,14 +329,24 @@ export function useSheetFollow({ send, kept, canvas, detent, pill, comms, voice, if (!held) return; const first = !held.drag.moved; if (first && voice) return; + const opening = first && held.drag.open && motionsRef.current.length > 0 ? sectionRef.current : null; + if (opening) { + const transform = getComputedStyle(opening).transform; + const offset = transform === "none" ? 0 : new DOMMatrixReadOnly(transform).m42; + held.drag.start = opening.getBoundingClientRect().height - offset; + } if (!moveDrag(held.drag, y - held.y)) return; + if (opening) stop(motionsRef); if (first) void send({ type: "drag" }); const drawn = held.form === "open" || held.drag.height > 0; const hold = comms || !animates() ? undefined : Math.max(held.drag.full, held.drag.floor); if (first || drawn !== live?.drawn) { unhold(sectionRef.current); // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- v119 drew the sheet for the first move before the next frame (chat-overlay-motion-adapter.ts:836), so the bar never shows under the finger's first paint - flushSync(() => setLive({ form: held.form, start: held.start, drawn, painted: dragPaint(held.drag), hold })); + flushSync(() => { + if (opening) setSeen((s) => ({ ...s, growing: undefined })); + setLive({ form: held.form, start: held.start, drawn, painted: dragPaint(held.drag), hold }); + }); held.painting = undefined; if (drawn && hold !== undefined) sectionRef.current?.setAttribute("data-alpha-sliding", ""); } @@ -398,7 +410,7 @@ export function useSheetFollow({ send, kept, canvas, detent, pill, comms, voice, const animate = useCallback((element: HTMLElement | null) => { sectionRef.current = element; if (!element || !animates()) return; - stop(motionsRef.current.splice(0)); + stop(motionsRef); element.removeAttribute("data-alpha-sliding"); const drawnHeight = element.getBoundingClientRect().height; if (!growing && !handing) { @@ -422,10 +434,9 @@ export function useSheetFollow({ send, kept, canvas, detent, pill, comms, voice, const motions = [grow, ...rest, ...(header ? [header.animate(revealFrames(from, drawnHeight, fit), { duration: resize.duration, easing: "linear" })] : [])]; motionsRef.current = motions; const settled = () => { - if (motionsRef.current === motions) { - stop(motionsRef.current.splice(0)); - element.removeAttribute("data-alpha-sliding"); - } + if (motionsRef.current !== motions) return; + stop(motionsRef); + element.removeAttribute("data-alpha-sliding"); finish(); }; grow?.finished.then(settled, settled); diff --git a/apps/app/test/dock.browser.test.tsx b/apps/app/test/dock.browser.test.tsx index ea29fc7ecf..d41a0be33d 100644 --- a/apps/app/test/dock.browser.test.tsx +++ b/apps/app/test/dock.browser.test.tsx @@ -300,13 +300,32 @@ describe("Ask Alpha dock", () => { expect(blackOnTheBar).toEqual([]); }); - const openHomeSheet = async () => { + const openHomeSheet = async (when: "settled" | "opening" = "settled") => { await page.viewport(390, 844); const { runtime } = await mountDock({ view: "Home" }); const section = () => document.querySelector("section[aria-label='Ask Alpha']"); - await page.getByRole("button", { name: "Open conversation" }).click(); - await shellReaches(runtime, (s) => s.assistant === "Sheet"); - await Effect.runPromise(Effect.sleep("600 millis")); + let paused = false; + const opening = new MutationObserver(() => { + const sheet = section(); + if (!sheet?.hasAttribute("data-alpha-sliding")) return; + const motions = sheet.getAnimations({ subtree: true }).filter((motion) => !(motion instanceof CSSAnimation || motion instanceof CSSTransition)); + if (motions.length === 0) return; + for (const motion of motions) { + motion.pause(); + motion.currentTime = 100; + } + paused = true; + opening.disconnect(); + }); + if (when === "opening") opening.observe(document.body, { subtree: true, childList: true, attributes: true }); + try { + await openSheetByMark(runtime); + await expect.element(page.getByRole("button", { name: "Resize chat" })).toBeVisible(); + if (when === "opening") await expect.poll(() => paused).toBe(true); + else await settled(page.getByRole("region", { name: "Ask Alpha" }).element()); + } finally { + opening.disconnect(); + } return { runtime, section }; }; @@ -425,14 +444,18 @@ describe("Ask Alpha dock", () => { }); // spec/app/assistant/dock.md, "Story: Drag Ask Alpha where I want it": as v119's (45f6bed30 chat-overlay-motion-adapter.ts:261-272, 1037-1039), an open sheet pulled down fades by how far it is into the zone above a floor of 62 and 28 points, where no bar is drawn at the press, and a flick down lets its header slide down onto the bar as it fades - it("Flick an open sheet down onto the bar as v119 drew it (spec/app/assistant/dock.md, \"Story: Drag Ask Alpha where I want it\")", async () => { - const { runtime, section } = await openHomeSheet(); + it.each(["settled", "opening"] as const)("Flick an open sheet down while %s (spec/app/assistant/dock.md, \"Story: Drag Ask Alpha where I want it\")", async (when) => { + const { runtime, section } = await openHomeSheet(when); const handle = section()?.querySelector("[aria-label='Resize chat']"); const box = handle?.getBoundingClientRect(); const y = Math.round((box?.top ?? 0) + (box?.height ?? 0) / 2); const finger = (type: string, clientY: number) => (handle?.isConnected ? handle : section())?.dispatchEvent(new PointerEvent(type, { bubbles: true, cancelable: true, clientY, pointerId: 13, pointerType: "touch", isPrimary: true })); const header = () => section()?.querySelector("[data-alpha-chat-header]")?.getBoundingClientRect().top ?? 0; - const opened = section()?.getBoundingClientRect().height ?? 0; + const visibleHeight = () => { + const box = page.getByRole("region", { name: "Ask Alpha" }).element().getBoundingClientRect(); + return Math.min(box.bottom, window.innerHeight) - box.top; + }; + const opened = visibleHeight(); const floor = 62 + 28; const v119Opacity = (height: number) => 1 - Math.min(1, Math.max(0, (floor + 120 - height) / 120)); @@ -443,8 +466,8 @@ describe("Ask Alpha dock", () => { by += 20; await pause(10); finger("pointermove", y + by); - const box = section()?.getBoundingClientRect(); - const height = box === undefined ? 0 : Math.min(box.bottom, window.innerHeight) - box.top; + const height = visibleHeight(); + expect(Math.abs(height - (opened - by))).toBeLessThanOrEqual(2); drawn.push({ height: Math.round(height), opacity: Number(getComputedStyle(section() as HTMLElement).opacity), v119: v119Opacity(height) }); } const inZone = drawn.filter(({ height }) => height < floor + 120);