Skip to content

Commit 2f6755b

Browse files
authored
fix(mobile): live activity tracks thread status and settlement (pingdotgg#21405)
1 parent 145d73b commit 2f6755b

5 files changed

Lines changed: 228 additions & 31 deletions

File tree

‎apps/server/src/relay/AgentAwarenessRelay.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ describe("AgentAwarenessRelay", () => {
297297
"provider-turn.updated",
298298
"thread.visited",
299299
"thread.pinned",
300+
"thread.unsettled",
300301
] as const) {
301302
assert.isFalse(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
302303
}
@@ -312,6 +313,7 @@ describe("AgentAwarenessRelay", () => {
312313
"thread.archived",
313314
"thread.unarchived",
314315
"thread.deleted",
316+
"thread.settled",
315317
] as const) {
316318
assert.isTrue(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type }));
317319
}
@@ -772,6 +774,75 @@ describe("AgentAwarenessRelay", () => {
772774
}),
773775
);
774776

777+
it.effect.each(["completed", "failed"] as const)(
778+
"publishes a tombstone when a %s thread is settled through a domain event",
779+
(status) =>
780+
Effect.gen(function* () {
781+
const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
782+
const pulls = yield* Queue.unbounded<void>();
783+
const { relay, currentShell, publications } = yield* makeTestRelay({
784+
domainEvents: Stream.fromEffectRepeat(
785+
Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))),
786+
),
787+
});
788+
yield* relay.start();
789+
yield* Queue.take(pulls);
790+
yield* relay.publishThread(THREAD_ID);
791+
const terminal = shell({ status });
792+
yield* Ref.set(currentShell, terminal);
793+
yield* relay.publishThread(THREAD_ID);
794+
assert.equal(publications[1]?.state?.phase, status);
795+
796+
const now = yield* DateTime.now;
797+
const settled = {
798+
...terminal,
799+
settledOverride: "settled" as const,
800+
settledAt: now,
801+
lastVisitedAt: null,
802+
};
803+
yield* Ref.set(currentShell, settled);
804+
yield* Queue.offer(events, {
805+
id: EventId.make("event:settled"),
806+
type: "thread.settled",
807+
threadId: THREAD_ID,
808+
occurredAt: now,
809+
payload: settled,
810+
});
811+
yield* Queue.take(pulls);
812+
yield* relay.drain;
813+
assert.equal(publications.length, 2);
814+
yield* TestClock.adjust("5 seconds");
815+
yield* relay.drain;
816+
assert.equal(publications.length, 3);
817+
assert.equal(publications[2]?.state, null);
818+
}).pipe(Effect.scoped),
819+
);
820+
821+
it.effect("keeps settled live work until its monitor finishes", () =>
822+
Effect.gen(function* () {
823+
const { relay, currentShell, publications } = yield* makeTestRelay();
824+
yield* relay.publishThread(THREAD_ID);
825+
const held = shell({
826+
status: "completed",
827+
settledOverride: "settled",
828+
pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],
829+
});
830+
yield* Ref.set(currentShell, held);
831+
yield* relay.publishThread(THREAD_ID);
832+
yield* TestClock.adjust("5 seconds");
833+
yield* relay.drain;
834+
assert.equal(publications.length, 1);
835+
assert.equal(publications[0]?.state?.phase, "running");
836+
837+
yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] });
838+
yield* relay.publishThread(THREAD_ID);
839+
yield* TestClock.adjust("5 seconds");
840+
yield* relay.drain;
841+
assert.equal(publications.length, 2);
842+
assert.equal(publications[1]?.state, null);
843+
}),
844+
);
845+
775846
it.effect.each(["completed", "failed"] as const)(
776847
"settling a %s thread publishes a tombstone without re-alerting on unsettle",
777848
(status) =>

‎infra/relay/src/agentActivity/ApnsDeliveries.test.ts‎

Lines changed: 82 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
12
import type {
23
RelayAgentActivityAggregateState,
34
RelayAgentActivityState,
@@ -602,34 +603,89 @@ describe("ApnsDeliveries", () => {
602603
},
603604
);
604605

605-
it.effect(
606-
"throttles updates for changed aggregates with stable counts and no pending attention",
607-
() => {
608-
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
609-
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
610-
const changedAggregate: RelayAgentActivityAggregateState = {
611-
...aggregate,
612-
updatedAt: "1970-01-01T00:00:04.000Z",
613-
};
614-
const previousAggregateJson = JSON.stringify(aggregate);
606+
it.effect.each([
607+
{
608+
label: "connecting becomes working",
609+
previousRows: [{ ...aggregate.activities[0]!, phase: "starting", status: "Connecting" }],
610+
},
611+
{
612+
label: "input resumes working",
613+
previousRows: [{ ...aggregate.activities[0]!, phase: "waiting_for_input", status: "Input" }],
614+
},
615+
{
616+
label: "a settled terminal row leaves",
617+
previousRows: [
618+
aggregate.activities[0]!,
619+
{
620+
...aggregate.activities[0]!,
621+
threadId: ThreadId.make("finished"),
622+
phase: "completed",
623+
status: "Done",
624+
},
625+
],
626+
},
627+
{
628+
label: "the same thread id moves to another environment",
629+
previousRows: [
630+
{ ...aggregate.activities[0]!, environmentId: EnvironmentId.make("other-env") },
631+
],
632+
},
633+
] as const)("queues an update inside the throttle window when $label", ({ previousRows }) => {
634+
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
635+
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
636+
const previousAggregate: RelayAgentActivityAggregateState = {
637+
...aggregate,
638+
activities: previousRows,
639+
};
615640

616-
return Effect.gen(function* () {
617-
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
618-
const result = yield* deliveries.sendForTarget({
619-
target: {
620-
...target,
621-
last_aggregate_json: previousAggregateJson,
622-
last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",
623-
},
624-
aggregate: changedAggregate,
625-
nowMs: 5_000,
626-
});
641+
return Effect.gen(function* () {
642+
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
643+
const result = yield* deliveries.sendForTarget({
644+
target: {
645+
...target,
646+
last_aggregate_json: JSON.stringify(previousAggregate),
647+
last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",
648+
},
649+
aggregate,
650+
nowMs: 5_000,
651+
});
627652

628-
expect(result).toBeNull();
629-
expect(queuedJobs).toEqual([]);
630-
}).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
631-
},
632-
);
653+
expect(result?.kind).toBe("live_activity_update");
654+
expect(queuedJobs).toMatchObject([{ payload: { kind: "live_activity_update", aggregate } }]);
655+
expect(queuedJobs[0]?.payload.alert ?? null).toBeNull();
656+
expect(attempts).toEqual([]);
657+
}).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
658+
});
659+
660+
it.effect.each([
661+
{ label: "inside", nowMs: 5_000, queued: false },
662+
{ label: "after", nowMs: 19_000, queued: true },
663+
])("throttles timestamp-only updates $label the window", ({ nowMs, queued }) => {
664+
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
665+
const queuedJobs: Array<SignedApnsDeliveryJob> = [];
666+
const changedAggregate: RelayAgentActivityAggregateState = {
667+
...aggregate,
668+
updatedAt: "1970-01-01T00:00:04.000Z",
669+
activities: [{ ...aggregate.activities[0]!, updatedAt: "1970-01-01T00:00:04.000Z" }],
670+
};
671+
const previousAggregateJson = JSON.stringify(aggregate);
672+
673+
return Effect.gen(function* () {
674+
const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
675+
const result = yield* deliveries.sendForTarget({
676+
target: {
677+
...target,
678+
last_aggregate_json: previousAggregateJson,
679+
last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",
680+
},
681+
aggregate: changedAggregate,
682+
nowMs,
683+
});
684+
685+
expect(result?.kind ?? null).toBe(queued ? "live_activity_update" : null);
686+
expect(queuedJobs).toHaveLength(queued ? 1 : 0);
687+
}).pipe(Effect.provide(layerFor({ attempts, queuedJobs })));
688+
});
633689

634690
it.effect("queues an end for an active Live Activity when Live Activities are disabled", () => {
635691
const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];

‎infra/relay/src/agentActivity/ApnsDeliveries.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import {
4848
alertForAttentionTransition,
4949
alertForNewlyTerminal,
5050
alertForTerminalAggregate,
51-
newlyTerminalRows,
51+
rowPhasesChanged,
5252
shouldAlertForActivity,
5353
} from "./agentActivityAlerts.ts";
5454
export {
@@ -176,10 +176,9 @@ function shouldUpdateLiveActivity(input: {
176176
if (aggregateNeedsAttention(input.nextAggregate)) {
177177
return true;
178178
}
179-
// A thread finishing must never be throttled away: when a completion and a
180-
// new start land in the same window, activeCount is unchanged and the Done
181-
// transition (and its alert) would otherwise be suppressed.
182-
if (newlyTerminalRows(input.previousAggregate, input.nextAggregate, true).length > 0) {
179+
// Phase and row changes may be the last update until the next transition.
180+
// Throttling them would leave the card showing a stale state indefinitely.
181+
if (rowPhasesChanged(input.previousAggregate, input.nextAggregate)) {
183182
return true;
184183
}
185184
const lastDeliveryAtMs =

‎infra/relay/src/agentActivity/agentActivityAlerts.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,17 @@ function rowKey(row: RelayAgentActivityAggregateRow): string {
3030
return JSON.stringify([row.environmentId, row.threadId]);
3131
}
3232

33+
export function rowPhasesChanged(
34+
previousAggregate: RelayAgentActivityAggregateState,
35+
nextAggregate: RelayAgentActivityAggregateState,
36+
): boolean {
37+
if (previousAggregate.activities.length !== nextAggregate.activities.length) return true;
38+
const previousPhases = new Map(
39+
previousAggregate.activities.map((row) => [rowKey(row), row.phase]),
40+
);
41+
return nextAggregate.activities.some((row) => previousPhases.get(rowKey(row)) !== row.phase);
42+
}
43+
3344
function isAttentionPhase(phase: string): boolean {
3445
return phase === "waiting_for_approval" || phase === "waiting_for_input";
3546
}

‎packages/shared/src/agentAwareness.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,66 @@ describe("projectThreadAwarenessV2", () => {
8787
).toMatchObject({ phase: "running", headline: "Agent is working" });
8888
});
8989

90+
it.each(["completed", "failed"] as const)("removes settled %s work", (status) => {
91+
expect(
92+
projectThreadAwarenessV2({
93+
environmentId: "env-1" as EnvironmentId,
94+
project,
95+
thread: v2Thread({ status, settledOverride: "settled" }),
96+
}),
97+
).toBeNull();
98+
});
99+
100+
it.each(["starting", "running", "waiting"] as const)(
101+
"keeps settled %s work visible",
102+
(status) => {
103+
expect(
104+
projectThreadAwarenessV2({
105+
environmentId: "env-1" as EnvironmentId,
106+
project,
107+
thread: v2Thread({ status, settledOverride: "settled" }),
108+
}),
109+
).toMatchObject({ phase: status === "starting" ? "starting" : "running" });
110+
},
111+
);
112+
113+
it.each(["user_input", "command"] as const)(
114+
"keeps a settled terminal thread with a pending %s request",
115+
(kind) => {
116+
expect(
117+
projectThreadAwarenessV2({
118+
environmentId: "env-1" as EnvironmentId,
119+
project,
120+
thread: v2Thread({
121+
status: "completed",
122+
settledOverride: "settled",
123+
pendingRuntimeRequest: {
124+
id: RuntimeRequestId.make("request-settled"),
125+
kind,
126+
createdAt: updatedAt,
127+
},
128+
}),
129+
}),
130+
).toMatchObject({
131+
phase: kind === "user_input" ? "waiting_for_input" : "waiting_for_approval",
132+
});
133+
},
134+
);
135+
136+
it("keeps settled work held open by a monitor", () => {
137+
expect(
138+
projectThreadAwarenessV2({
139+
environmentId: "env-1" as EnvironmentId,
140+
project,
141+
thread: v2Thread({
142+
status: "completed",
143+
settledOverride: "settled",
144+
pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor" }],
145+
}),
146+
}),
147+
).toMatchObject({ phase: "running" });
148+
});
149+
90150
it.each([
91151
["only a dev server", "completed", [{ taskId: "dev", kind: "command" }]],
92152
["a monitor", "running", [{ taskId: "watch", kind: "monitor" }]],

0 commit comments

Comments
 (0)