TypeScript
fix(mobile): live activity tracks thread status and settlement (#21405)
maria2f6755b7e32d
diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex 3ae05f309ad..003cb371b31 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -297,6 +297,7 @@ describe("AgentAwarenessRelay", () => {"provider-turn.updated","thread.visited","thread.pinned",+ "thread.unsettled",] as const) {assert.isFalse(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));}@@ -312,6 +313,7 @@ describe("AgentAwarenessRelay", () => {"thread.archived","thread.unarchived","thread.deleted",+ "thread.settled",] as const) {assert.isTrue(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));}@@ -772,6 +774,75 @@ describe("AgentAwarenessRelay", () => {}),);+ it.effect.each(["completed", "failed"] as const)(+ "publishes a tombstone when a %s thread is settled through a domain event",+ (status) =>+ Effect.gen(function* () {+ const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();+ const pulls = yield* Queue.unbounded<void>();+ const { relay, currentShell, publications } = yield* makeTestRelay({+ domainEvents: Stream.fromEffectRepeat(+ Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),+ ),+ });+ yield* relay.start();+ yield* Queue.take(pulls);+ yield* relay.publishThread(THREAD_ID);+ const terminal = shell({ status });+ yield* Ref.set(currentShell, terminal);+ yield* relay.publishThread(THREAD_ID);+ assert.equal(publications[1]?.state?.phase, status);++ const now = yield* DateTime.now;+ const settled = {+ ...terminal,+ settledOverride: "settled" as const,+ settledAt: now,+ lastVisitedAt: null,+ };+ yield* Ref.set(currentShell, settled);+ yield* Queue.offer(events, {+ id: EventId.make("event:settled"),+ type: "thread.settled",+ threadId: THREAD_ID,+ occurredAt: now,+ payload: settled,+ });+ yield* Queue.take(pulls);+ yield* relay.drain;+ assert.equal(publications.length, 2);+ yield* TestClock.adjust("5 seconds");+ yield* relay.drain;+ assert.equal(publications.length, 3);+ assert.equal(publications[2]?.state, null);+ }).pipe(Effect.scoped),+ );++ it.effect("keeps settled live work until its monitor finishes", () =>+ Effect.gen(function* () {+ const { relay, currentShell, publications } = yield* makeTestRelay();+ yield* relay.publishThread(THREAD_ID);+ const held = shell({+ status: "completed",+ settledOverride: "settled",+ pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],+ });+ yield* Ref.set(currentShell, held);+ yield* relay.publishThread(THREAD_ID);+ yield* TestClock.adjust("5 seconds");+ yield* relay.drain;+ assert.equal(publications.length, 1);+ assert.equal(publications[0]?.state?.phase, "running");++ yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });+ yield* relay.publishThread(THREAD_ID);+ yield* TestClock.adjust("5 seconds");+ yield* relay.drain;+ assert.equal(publications.length, 2);+ assert.equal(publications[1]?.state, null);+ }),+ );+it.effect.each(["completed", "failed"] as const)("settling a %s thread publishes a tombstone without re-alerting on unsettle",(status) =>diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.tsindex abb77408843..fc2c5f3e361 100644--- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts+++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts@@ -1,3 +1,4 @@+import { EnvironmentId, ThreadId } from "@t3tools/contracts";import type {RelayAgentActivityAggregateState,RelayAgentActivityState,@@ -602,34 +603,89 @@ describe("ApnsDeliveries", () => {},);- it.effect(- "throttles updates for changed aggregates with stable counts and no pending attention",- () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const changedAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- updatedAt: "1970-01-01T00:00:04.000Z",- };- const previousAggregateJson = JSON.stringify(aggregate);+ it.effect.each([+ {+ label: "connecting becomes working",+ previousRows: [{ ...aggregate.activities[0]!, phase: "starting", status: "Connecting" }],+ },+ {+ label: "input resumes working",+ previousRows: [{ ...aggregate.activities[0]!, phase: "waiting_for_input", status: "Input" }],+ },+ {+ label: "a settled terminal row leaves",+ previousRows: [+ aggregate.activities[0]!,+ {+ ...aggregate.activities[0]!,+ threadId: ThreadId.make("finished"),+ phase: "completed",+ status: "Done",+ },+ ],+ },+ {+ label: "the same thread id moves to another environment",+ previousRows: [+ { ...aggregate.activities[0]!, environmentId: EnvironmentId.make("other-env") },+ ],+ },+ ] as const)("queues an update inside the throttle window when $label", ({ previousRows }) => {+ const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];+ const queuedJobs: Array<SignedApnsDeliveryJob> = [];+ const previousAggregate: RelayAgentActivityAggregateState = {+ ...aggregate,+ activities: previousRows,+ };- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- last_aggregate_json: previousAggregateJson,- last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",- },- aggregate: changedAggregate,- nowMs: 5_000,- });+ return Effect.gen(function* () {+ const deliveries = yield* ApnsDeliveries.ApnsDeliveries;+ const result = yield* deliveries.sendForTarget({+ target: {+ ...target,+ last_aggregate_json: JSON.stringify(previousAggregate),+ last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",+ },+ aggregate,+ nowMs: 5_000,+ });- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));- },- );+ expect(result?.kind).toBe("live_activity_update");+ expect(queuedJobs).toMatchObject([{ payload: { kind: "live_activity_update", aggregate } }]);+ expect(queuedJobs[0]?.payload.alert ?? null).toBeNull();+ expect(attempts).toEqual([]);+ }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));+ });++ it.effect.each([+ { label: "inside", nowMs: 5_000, queued: false },+ { label: "after", nowMs: 19_000, queued: true },+ ])("throttles timestamp-only updates $label the window", ({ nowMs, queued }) => {+ const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];+ const queuedJobs: Array<SignedApnsDeliveryJob> = [];+ const changedAggregate: RelayAgentActivityAggregateState = {+ ...aggregate,+ updatedAt: "1970-01-01T00:00:04.000Z",+ activities: [{ ...aggregate.activities[0]!, updatedAt: "1970-01-01T00:00:04.000Z" }],+ };+ const previousAggregateJson = JSON.stringify(aggregate);++ return Effect.gen(function* () {+ const deliveries = yield* ApnsDeliveries.ApnsDeliveries;+ const result = yield* deliveries.sendForTarget({+ target: {+ ...target,+ last_aggregate_json: previousAggregateJson,+ last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",+ },+ aggregate: changedAggregate,+ nowMs,+ });++ expect(result?.kind ?? null).toBe(queued ? "live_activity_update" : null);+ expect(queuedJobs).toHaveLength(queued ? 1 : 0);+ }).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));+ });it.effect("queues an end for an active Live Activity when Live Activities are disabled", () => {const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.ts b/infra/relay/src/agentActivity/ApnsDeliveries.tsindex 390f2a8eb5d..6e48ac3663f 100644--- a/infra/relay/src/agentActivity/ApnsDeliveries.ts+++ b/infra/relay/src/agentActivity/ApnsDeliveries.ts@@ -48,7 +48,7 @@ import {alertForAttentionTransition,alertForNewlyTerminal,alertForTerminalAggregate,- newlyTerminalRows,+ rowPhasesChanged,shouldAlertForActivity,} from "./agentActivityAlerts.ts";export {@@ -176,10 +176,9 @@ function shouldUpdateLiveActivity(input: {if (aggregateNeedsAttention(input.nextAggregate)) {return true;}- // A thread finishing must never be throttled away: when a completion and a- // new start land in the same window, activeCount is unchanged and the Done- // transition (and its alert) would otherwise be suppressed.- if (newlyTerminalRows(input.previousAggregate, input.nextAggregate, true).length > 0) {+ // Phase and row changes may be the last update until the next transition.+ // Throttling them would leave the card showing a stale state indefinitely.+ if (rowPhasesChanged(input.previousAggregate, input.nextAggregate)) {return true;}const lastDeliveryAtMs =diff --git a/infra/relay/src/agentActivity/agentActivityAlerts.ts b/infra/relay/src/agentActivity/agentActivityAlerts.tsindex 913dd99bd9d..64670632c80 100644--- a/infra/relay/src/agentActivity/agentActivityAlerts.ts+++ b/infra/relay/src/agentActivity/agentActivityAlerts.ts@@ -30,6 +30,17 @@ function rowKey(row: RelayAgentActivityAggregateRow): string {return JSON.stringify([row.environmentId, row.threadId]);}+export function rowPhasesChanged(+ previousAggregate: RelayAgentActivityAggregateState,+ nextAggregate: RelayAgentActivityAggregateState,+): boolean {+ if (previousAggregate.activities.length !== nextAggregate.activities.length) return true;+ const previousPhases = new Map(+ previousAggregate.activities.map((row) => [rowKey(row), row.phase]),+ );+ return nextAggregate.activities.some((row) => previousPhases.get(rowKey(row)) !== row.phase);+}+function isAttentionPhase(phase: string): boolean {return phase === "waiting_for_approval" || phase === "waiting_for_input";}diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.tsindex e325fa263e9..a68f9e69ae0 100644--- a/packages/shared/src/agentAwareness.test.ts+++ b/packages/shared/src/agentAwareness.test.ts@@ -87,6 +87,66 @@ describe("projectThreadAwarenessV2", () => {).toMatchObject({ phase: "running", headline: "Agent is working" });});+ it.each(["completed", "failed"] as const)("removes settled %s work", (status) => {+ expect(+ projectThreadAwarenessV2({+ environmentId: "env-1" as EnvironmentId,+ project,+ thread: v2Thread({ status, settledOverride: "settled" }),+ }),+ ).toBeNull();+ });++ it.each(["starting", "running", "waiting"] as const)(+ "keeps settled %s work visible",+ (status) => {+ expect(+ projectThreadAwarenessV2({+ environmentId: "env-1" as EnvironmentId,+ project,+ thread: v2Thread({ status, settledOverride: "settled" }),+ }),+ ).toMatchObject({ phase: status === "starting" ? "starting" : "running" });+ },+ );++ it.each(["user_input", "command"] as const)(+ "keeps a settled terminal thread with a pending %s request",+ (kind) => {+ expect(+ projectThreadAwarenessV2({+ environmentId: "env-1" as EnvironmentId,+ project,+ thread: v2Thread({+ status: "completed",+ settledOverride: "settled",+ pendingRuntimeRequest: {+ id: RuntimeRequestId.make("request-settled"),+ kind,+ createdAt: updatedAt,+ },+ }),+ }),+ ).toMatchObject({+ phase: kind === "user_input" ? "waiting_for_input" : "waiting_for_approval",+ });+ },+ );++ it("keeps settled work held open by a monitor", () => {+ expect(+ projectThreadAwarenessV2({+ environmentId: "env-1" as EnvironmentId,+ project,+ thread: v2Thread({+ status: "completed",+ settledOverride: "settled",+ pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],+ }),+ }),+ ).toMatchObject({ phase: "running" });+ });+it.each([["only a dev server", "completed", [{ taskId: "dev", kind: "command" }]],["a monitor", "running", [{ taskId: "watch", kind: "monitor" }]],