Skip to content

Commit 97ed442

Browse files
Address review findings: worker-ordered confirms, unthrottled Done, LA pref gates
Fixes the real findings from the PR review bots ahead of the TestFlight build: - Deferred publish confirmations (tombstones and first-state completions) now re-enqueue through the same drainable worker as every other publish instead of a detached fiber calling the publisher directly, so a confirmed tombstone can never race an in-flight live update; a deadline map replaces the pending set, which also guarantees a single scheduled confirmation per thread and clears when the state recovers. (cursor/macroscope High) - Newly-terminal transitions bypass the 15s live-activity update throttle: a completion landing in the same window as a new start keeps activeCount unchanged and would previously be suppressed, silently dropping the Done transition and its buzz. (macroscope High) - The newly-terminal alert honors the same 2-minute freshness rule as terminal push notifications, so replayed aggregates repaint without ringing. (cursor Medium) - Live Activity arming and priming treat an unset preference as enabled (the toggle's default): fresh installs now prime, and arm-on-send respects an explicit off. (cursor High/Medium) Remaining findings triaged as stale (superseded designs), intended behavior (replay painting recent Done, LA-disabled end retiring the token), or accepted edge cases (grace extension on re-registration, completion alerts beyond the 3-row display cap, ready-with-lastError mapping to Done, cancelled turns showing Done). Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 387d068 commit 97ed442

5 files changed

Lines changed: 120 additions & 97 deletions

File tree

‎apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ vi.mock("../../lib/runtime", () => ({
145145
vi.mock("../../lib/storage", () => ({
146146
loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
147147
loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),
148-
loadPreferences: vi.fn(() => Promise.resolve({})),
148+
loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),
149149
loadAgentAwarenessRegistrationRecord: vi.fn(() =>
150150
Promise.resolve(registrationRecordStore.current),
151151
),

‎apps/mobile/src/features/agent-awareness/remoteRegistration.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,20 @@ export function armAgentAwarenessLiveActivityForLocalWork(input: {
447447
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
448448
return;
449449
}
450+
void loadPreferences()
451+
.catch(() => null)
452+
.then((preferences) => {
453+
if (preferences?.liveActivitiesEnabled === false) {
454+
return;
455+
}
456+
armAgentAwarenessLiveActivityForLocalWorkNow(input);
457+
});
458+
}
459+
460+
function armAgentAwarenessLiveActivityForLocalWorkNow(input: {
461+
readonly threadTitle: string;
462+
readonly projectTitle: string;
463+
}): void {
450464
try {
451465
if (AgentActivity.getInstances().length > 0) {
452466
return;
@@ -1007,7 +1021,9 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
10071021
cause,
10081022
}),
10091023
}).pipe(Effect.orElseSucceed(() => null));
1010-
if (preferences?.liveActivitiesEnabled) {
1024+
// The toggle defaults to on: an unset preference (fresh install) must
1025+
// prime, so only an explicit false blocks it.
1026+
if (preferences?.liveActivitiesEnabled !== false) {
10111027
const snapshot = yield* readAgentActivitySnapshot();
10121028
// The snapshot request yields; an arm-on-send may have created the
10131029
// card in the meantime. Re-check so two cards are never started.

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

Lines changed: 55 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -326,18 +326,15 @@ export const make = Effect.gen(function* () {
326326
transformClient: relayEnvironmentClient(relayConfig.environmentCredential),
327327
}).pipe(Effect.provide(FetchHttpClient.layer));
328328

329-
// Assigned after publishThreadUnsafe below; indirection keeps the deferred
330-
// tombstone confirmation from making the definition self-referential.
331-
let confirmTombstoneLater: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
332-
// One pending confirmation per thread: birth/teardown flapping can resolve
333-
// null on several consecutive events, and each would otherwise fork its own
334-
// confirm fiber.
335-
const pendingTombstoneConfirms = new Set<ThreadId>();
336-
337-
const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (
338-
threadId: ThreadId,
339-
options?: { readonly confirmTombstone?: boolean },
340-
) {
329+
// Deadlines for publishes that need confirmation (tombstones and
330+
// first-state completions). The confirming publish is re-enqueued through
331+
// the same drainable worker as every other publish, so a confirmed
332+
// tombstone can never race an in-flight live update; a recovered state
333+
// clears the deadline. Assigned after the worker exists.
334+
const publishConfirmDeadlines = new Map<ThreadId, number>();
335+
let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;
336+
337+
const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {
341338
const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(
342339
Effect.orElseSucceed(() => false),
343340
);
@@ -421,73 +418,48 @@ export const make = Effect.gen(function* () {
421418
return;
422419
}
423420

424-
// A brand-new session boots at "ready" before its first turn starts, which
425-
// projects as completed for an instant; publishing that sends a spurious
426-
// Done notification at thread birth. Completed as the thread's FIRST
427-
// published state gets the same defer-and-confirm treatment as
428-
// tombstones: real completions (previous state was live) publish
429-
// immediately, and at-rest threads still publish 5 seconds later.
430-
if (
431-
snapshot.state?.phase === "completed" &&
432-
options?.confirmTombstone !== true &&
433-
!publishedStateByThread.has(threadId)
434-
) {
435-
if (pendingTombstoneConfirms.has(threadId)) {
421+
// Two projections need confirmation before publishing, because both can
422+
// appear transiently while the projector is mid-write and publishing them
423+
// immediately is destructive or noisy:
424+
// - null (tombstone) while the previous published state was live: deletes
425+
// the thread from every armed card mid-conversation.
426+
// - completed as the thread's FIRST published state: sessions boot at
427+
// "ready" before their first turn, which projects as completed for an
428+
// instant and sends a spurious Done notification at thread birth.
429+
// Defer, schedule a re-publish through the ordinary worker queue, and
430+
// only publish if the projection still holds when it drains.
431+
const requiresConfirmation =
432+
(snapshot.state === null &&
433+
publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||
434+
(snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));
435+
if (requiresConfirmation) {
436+
const nowMs = (yield* DateTime.now).epochMilliseconds;
437+
const deadline = publishConfirmDeadlines.get(threadId);
438+
if (deadline === undefined) {
439+
publishConfirmDeadlines.set(threadId, nowMs + 5_000);
440+
yield* Effect.logInfo("agent activity publish deferred pending confirmation", {
441+
environmentId,
442+
threadId,
443+
reason: snapshot.reason,
444+
statePhase: snapshot.state?.phase ?? null,
445+
shell: describeThreadShellForAwareness(thread),
446+
});
447+
yield* schedulePublishConfirm(threadId);
436448
return;
437449
}
438-
pendingTombstoneConfirms.add(threadId);
439-
yield* Effect.logInfo("agent activity first-state completion deferred", {
440-
environmentId,
441-
threadId,
442-
shell: describeThreadShellForAwareness(thread),
443-
});
444-
yield* Effect.forkDetach(
445-
confirmTombstoneLater(threadId).pipe(
446-
Effect.ensuring(Effect.sync(() => pendingTombstoneConfirms.delete(threadId))),
447-
),
448-
);
449-
return;
450-
}
451-
452-
if (
453-
snapshot.state === null &&
454-
options?.confirmTombstone !== true &&
455-
publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)
456-
) {
457-
// A live thread that suddenly resolves to null is usually a transient
458-
// handoff gap (an answered prompt whose next turn has not started yet,
459-
// a shell lookup racing a write), and publishing the tombstone
460-
// immediately deletes the thread from the lock-screen card mid-
461-
// conversation. Defer, re-resolve, and only tombstone if it holds;
462-
// genuinely deleted threads still propagate a few seconds later.
463-
if (pendingTombstoneConfirms.has(threadId)) {
450+
if (nowMs < deadline) {
464451
return;
465452
}
466-
pendingTombstoneConfirms.add(threadId);
467-
yield* Effect.logInfo("agent activity tombstone deferred pending confirmation", {
468-
environmentId,
469-
threadId,
470-
reason: snapshot.reason,
471-
shell: describeThreadShellForAwareness(thread),
472-
});
473-
yield* Effect.forkDetach(
474-
confirmTombstoneLater(threadId).pipe(
475-
Effect.ensuring(Effect.sync(() => pendingTombstoneConfirms.delete(threadId))),
476-
),
477-
);
478-
return;
479-
}
480-
481-
if (snapshot.state === null && options?.confirmTombstone === true) {
482-
// Publishing a confirmed tombstone deletes the thread from every armed
483-
// card; log exactly what the shell resolved to so a wrongly-null
484-
// projection is diagnosable from the server log alone.
485-
yield* Effect.logInfo("agent activity tombstone confirmed", {
453+
publishConfirmDeadlines.delete(threadId);
454+
yield* Effect.logInfo("agent activity deferred publish confirmed", {
486455
environmentId,
487456
threadId,
488457
reason: snapshot.reason,
458+
statePhase: snapshot.state?.phase ?? null,
489459
shell: describeThreadShellForAwareness(thread),
490460
});
461+
} else {
462+
publishConfirmDeadlines.delete(threadId);
491463
}
492464

493465
if (snapshot.reason === "thread-not-found") {
@@ -515,18 +487,6 @@ export const make = Effect.gen(function* () {
515487
});
516488
});
517489

518-
confirmTombstoneLater = (threadId) =>
519-
publishThreadUnsafe(threadId, { confirmTombstone: true }).pipe(
520-
Effect.delay("5 seconds"),
521-
Effect.catchCause((cause) =>
522-
Effect.logWarning("deferred agent activity tombstone failed", {
523-
threadId,
524-
cause: Cause.pretty(cause),
525-
}),
526-
),
527-
Effect.asVoid,
528-
);
529-
530490
const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>
531491
publishThreadUnsafe(threadId).pipe(
532492
Effect.catchCause((cause) => {
@@ -590,6 +550,19 @@ export const make = Effect.gen(function* () {
590550

591551
const worker = yield* makeDrainableWorker(publishThread);
592552

553+
schedulePublishConfirm = (threadId) =>
554+
Effect.forkDetach(
555+
Effect.sleep("5 seconds").pipe(
556+
Effect.andThen(worker.enqueue(threadId)),
557+
Effect.catchCause((cause) =>
558+
Effect.logWarning("deferred agent activity confirmation failed", {
559+
threadId,
560+
cause: Cause.pretty(cause),
561+
}),
562+
),
563+
),
564+
).pipe(Effect.asVoid);
565+
593566
const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(
594567
function* () {
595568
const [relayConfig, publishEnabled] = yield* Effect.all([

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1552,6 +1552,7 @@ describe("live activity alert decisions", () => {
15521552
previousAggregate: aggregate,
15531553
nextAggregate: next,
15541554
preferences,
1555+
nowMs: 0,
15551556
}),
15561557
).toEqual({ title: "Thread", body: "Done: Project" });
15571558
// The completion switch mutes it.
@@ -1560,6 +1561,7 @@ describe("live activity alert decisions", () => {
15601561
previousAggregate: aggregate,
15611562
nextAggregate: next,
15621563
preferences: { ...preferences, notifyOnCompletion: false },
1564+
nowMs: 0,
15631565
}),
15641566
).toBeNull();
15651567
// No baseline means no transition to ring on.
@@ -1568,6 +1570,7 @@ describe("live activity alert decisions", () => {
15681570
previousAggregate: null,
15691571
nextAggregate: next,
15701572
preferences,
1573+
nowMs: 0,
15711574
}),
15721575
).toBeNull();
15731576
// A Done row that was already terminal (or absent) before stays silent.
@@ -1576,13 +1579,15 @@ describe("live activity alert decisions", () => {
15761579
previousAggregate: next,
15771580
nextAggregate: next,
15781581
preferences,
1582+
nowMs: 0,
15791583
}),
15801584
).toBeNull();
15811585
expect(
15821586
ApnsDeliveries.alertForNewlyTerminal({
15831587
previousAggregate: { ...aggregate, activities: [attentionRow] },
15841588
nextAggregate: next,
15851589
preferences,
1590+
nowMs: 0,
15861591
}),
15871592
).toBeNull();
15881593
});

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

Lines changed: 42 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -215,29 +215,51 @@ export function alertForAttentionTransition(input: {
215215
// completion buzz while other agents keep the activity alive. Requires the
216216
// thread to have been present and non-terminal before, so a baseline-less
217217
// replay or a row that merely fell off the display cap never rings.
218-
export function alertForNewlyTerminal(input: {
219-
readonly previousAggregate: RelayAgentActivityAggregateState | null;
220-
readonly nextAggregate: RelayAgentActivityAggregateState;
221-
readonly preferences: RelayAgentAwarenessPreferences | null;
222-
}): ApnsLiveActivityAlert | null {
223-
if (input.previousAggregate === null) {
224-
return null;
218+
function newlyTerminalRows(
219+
previousAggregate: RelayAgentActivityAggregateState | null,
220+
nextAggregate: RelayAgentActivityAggregateState,
221+
): ReadonlyArray<RelayAgentActivityAggregateState["activities"][number]> {
222+
if (previousAggregate === null) {
223+
return [];
225224
}
226225
const previousPhases = new Map(
227-
input.previousAggregate.activities.map((row) => [row.threadId, row.phase]),
226+
previousAggregate.activities.map((row) => [row.threadId, row.phase]),
228227
);
229-
const newlyTerminal = input.nextAggregate.activities.filter((row) => {
228+
return nextAggregate.activities.filter((row) => {
230229
if (row.phase !== "completed" && row.phase !== "failed") {
231230
return false;
232231
}
233232
const previousPhase = previousPhases.get(row.threadId);
234233
return (
235-
previousPhase !== undefined &&
236-
previousPhase !== "completed" &&
237-
previousPhase !== "failed" &&
238-
alertAllowedForPhase(input.preferences, row.phase)
234+
previousPhase !== undefined && previousPhase !== "completed" && previousPhase !== "failed"
239235
);
240236
});
237+
}
238+
239+
function isFreshTerminalRow(
240+
row: RelayAgentActivityAggregateState["activities"][number],
241+
nowMs: number,
242+
): boolean {
243+
const updatedAtMs = Option.match(DateTime.make(row.updatedAt), {
244+
onNone: () => null,
245+
onSome: (dt) => dt.epochMilliseconds,
246+
});
247+
return updatedAtMs !== null && nowMs - updatedAtMs <= TERMINAL_NOTIFICATION_FRESHNESS_MS;
248+
}
249+
250+
export function alertForNewlyTerminal(input: {
251+
readonly previousAggregate: RelayAgentActivityAggregateState | null;
252+
readonly nextAggregate: RelayAgentActivityAggregateState;
253+
readonly preferences: RelayAgentAwarenessPreferences | null;
254+
readonly nowMs: number;
255+
}): ApnsLiveActivityAlert | null {
256+
const newlyTerminal = newlyTerminalRows(input.previousAggregate, input.nextAggregate).filter(
257+
(row) =>
258+
alertAllowedForPhase(input.preferences, row.phase) &&
259+
// Replays of old aggregates (server restarts, redeliveries) repaint
260+
// state without ringing; only fresh completions buzz.
261+
isFreshTerminalRow(row, input.nowMs),
262+
);
241263
const first = newlyTerminal[0];
242264
if (!first) {
243265
return null;
@@ -284,6 +306,12 @@ function shouldUpdateLiveActivity(input: {
284306
if (aggregateNeedsAttention(input.nextAggregate)) {
285307
return true;
286308
}
309+
// A thread finishing must never be throttled away: when a completion and a
310+
// new start land in the same window, activeCount is unchanged and the Done
311+
// transition (and its alert) would otherwise be suppressed.
312+
if (newlyTerminalRows(input.previousAggregate, input.nextAggregate).length > 0) {
313+
return true;
314+
}
287315
const lastDeliveryAtMs =
288316
input.lastDeliveryAt === null
289317
? null
@@ -419,6 +447,7 @@ function chooseLiveActivityDelivery(input: {
419447
previousAggregate,
420448
nextAggregate,
421449
preferences,
450+
nowMs: input.nowMs,
422451
}),
423452
}
424453
: "suppressed";

0 commit comments

Comments
 (0)