Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/server/src/relay/AgentAwarenessRelay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,8 @@ describe("AgentAwarenessRelay", () => {
assert.equal(publications.length, 2);
assert.isTrue(publications[1]?.url.includes(`/threads/${THREAD_ID}/`) ?? false);
assert.equal(publications[1]?.state?.phase, "waiting_for_approval");
assert.equal(publications[1]?.state?.detail, "Child needs approval.");
assert.isTrue(publications[1]?.state?.deepLink.endsWith(`/${CHILD_THREAD_ID}`) ?? false);

// A rename keeps the same request's alert time, so the phone doesn't re-alert.
yield* setShell(
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/relay/AgentAwarenessRelay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ export const make = Effect.gen(function* () {
if (requestId !== entry.requestId) subagentRequests.set(childId, { ...entry, requestId });
// The newest wait is the one to announce.
if (pending === null || DateTime.isGreaterThan(child.updatedAt, pending.updatedAt)) {
pending = { requestId, updatedAt: child.updatedAt };
pending = { threadId: childId, title: child.title, requestId, updatedAt: child.updatedAt };
}
}
return pending;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ vi.mock(import("../state/threads"), async (original) => {
...actual,
environmentThreadShells: {
...actual.environmentThreadShells,
pendingSubagentRequestsAtom: (() => noRequestsAtom) as never,
pendingSubagentRequestsAtom: (() => requestsAtom) as never,
childThreadInputsAtom: (() => childInputsAtom) as never,
get delegatedUnderParentAtom() {
return noDelegatedAtom as never;
},
Expand Down Expand Up @@ -81,7 +82,8 @@ import { startThreadNotifications } from "./ThreadNotificationCoordinator";
let registry: AtomRegistry.AtomRegistry;
const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));
const environmentIdsAtom = Atom.make<ReadonlyArray<string>>([]);
const noRequestsAtom = Atom.make(new Map());
const requestsAtom = Atom.make<ReadonlyMap<string, string>>(new Map());
const childInputsAtom = Atom.make<ReadonlyArray<unknown>>([]);
const noDelegatedAtom = Atom.make<ReadonlySet<string>>(new Set<string>());
state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };

Expand Down Expand Up @@ -254,6 +256,31 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
},
);

it("names a subagent asking for approval through its parent and opens it", async () => {
await using app = setup();
app.start();
registry.set(childInputsAtom, [
{
environmentId: "two",
id: "child",
title: "Fix flaky test",
hasPendingApprovals: true,
lineage: { sideChat: false },
},
]);
registry.set(requestsAtom, new Map([["thread", "approval"]]));
const [notification] = TestNotification.sent;
expect([notification?.title, notification?.options.body]).toEqual([
"Approval needed",
"Fix flaky test (in Test thread)",
]);
notification!.dispatchEvent(new Event("click"));
expect(state.navigate).toHaveBeenCalledWith({
to: "/$environmentId/$threadId",
params: { environmentId: "two", threadId: "child" },
});
});

it("presents completion notifications and sound as soon as the shell completes", async () => {
await using app = setup();
state.mode = "notifications-and-sound";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,22 @@ const working: ThreadNotificationObservation = {
settled: false,
completedAt: null,
backgroundWake: false,
heldCompletedAt: null,
};
const completed = (at: number): ThreadNotificationObservation => ({
attention: null,
requestId: null,
settled: true,
completedAt: at,
backgroundWake: false,
heldCompletedAt: null,
});
const waking: ThreadNotificationObservation = { ...working, backgroundWake: true };
const woke = (at: number): ThreadNotificationObservation => ({
...completed(at),
backgroundWake: true,
});
const held = (at: number): ThreadNotificationObservation => ({ ...working, heldCompletedAt: at });
const visible = { archived: false, quiet: false };

function fakeTimers(): Disposable {
Expand Down Expand Up @@ -161,6 +164,26 @@ describe("createThreadNotificationGate", () => {
]);
});

it("waits out the grace when held work ends, so the wake it starts replaces the completion", () => {
using _timers = fakeTimers();
const { notify, observe } = harness();
observe(working);
// The run ended while a delegated task still ran, then the task finished before its wake.
observe(held(1));
observe(completed(1));
expect(notify).not.toHaveBeenCalled();
observe(working);
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
expect(notify).not.toHaveBeenCalled();
observe(held(2));
observe(completed(2));
vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS - 1);
observe({ ...completed(2) });
expect(notify).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(notify.mock.calls).toEqual([["thread", "completion"]]);
});

it("notifies a wake's completion once after the grace when no run follows, even across a pause", () => {
using _timers = fakeTimers();
const { gate, notify, observe } = harness();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ export interface ThreadNotificationObservation {
readonly completedAt: number | null;
/** The latest run answers a background-work progress wake, like a Monitor line. */
readonly backgroundWake: boolean;
/** When the latest run completed, while background work such as a delegated task holds it. */
readonly heldCompletedAt: number | null;
}

/** Matches the push relay's completion confirmation: a final wake can start right after a progress wake. */
/** Matches the push relay's completion confirmation: a wake can start right after held work ends. */
export const RELEASED_COMPLETION_GRACE_MS = 5_000;

export function createThreadNotificationGate<Key>(
Expand Down Expand Up @@ -83,7 +85,8 @@ export function createThreadNotificationGate<Key>(
}
const at = next.completedAt;
if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return;
if (next.backgroundWake) {
// Held work that ends wakes the agent, and its result commits before that wake run exists.
if (next.backgroundWake || prior.heldCompletedAt === at) {
release(key, at);
return;
}
Expand Down
39 changes: 27 additions & 12 deletions apps/web/src/components/ThreadNotificationCoordinator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,26 @@ export function startThreadNotifications(
: status === "request"
? "Guest request"
: "Input needed";
// A subagent or side chat asking through its parent is named and opened directly.
const requester =
kind === "input" &&
state.subagentRequest !== null &&
!thread.hasPendingApprovals &&
!thread.hasPendingUserInput
? (registry
.get(
environmentThreadShells.childThreadInputsAtom({ environmentId, threadId: thread.id }),
)
.find((child) =>
state.subagentRequest === "approval"
? child.hasPendingApprovals
: child.lineage.sideChat === true,
) ?? null)
: null;
const body = requester ? `${requester.title} (in ${thread.title})` : thread.title;
const target = requester
? { environmentId: requester.environmentId, threadId: requester.id }
: { environmentId, threadId: thread.id };
if (hasNotificationSound(mode)) {
void playNotificationSound(kind, () =>
hasNotificationSound(getClientSettings().notificationMode),
Expand All @@ -158,7 +178,7 @@ export function startThreadNotifications(
onRemove: (): void => forgetToast(toastKey, toastId),
type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
title,
description: thread.title,
description: body,
data: {
hideCopyButton: true,
leadingIcon:
Expand All @@ -178,10 +198,7 @@ export function startThreadNotifications(
children: "Open thread",
onClick: () => {
toastManager.close(toastId);
void router.navigate({
to: "/$environmentId/$threadId",
params: { environmentId, threadId: thread.id },
});
void router.navigate({ to: "/$environmentId/$threadId", params: target });
},
},
});
Expand All @@ -197,7 +214,7 @@ export function startThreadNotifications(
return;
try {
const notification = new Notification(title, {
body: thread.title,
body,
tag: threadNotificationTag(environmentId, thread.id),
silent: true,
// Windows drops clicks after a toast moves into Notification Center.
Expand All @@ -208,10 +225,7 @@ export function startThreadNotifications(
notification.close();
window.focus();
void window.desktopBridge?.revealWindow().catch(() => undefined);
void router.navigate({
to: "/$environmentId/$threadId",
params: { environmentId, threadId: thread.id },
});
void router.navigate({ to: "/$environmentId/$threadId", params: target });
});
} catch {
// Some browsers expose Notification but reject desktop presentation.
Expand Down Expand Up @@ -264,8 +278,8 @@ export function startThreadNotifications(
const attention = needsAttention
? `${thread.latestRun?.runId ?? ""}:${status}:${requestId ?? ""}`
: null;
const completed = status === "ready" && thread.latestRun?.status === "completed";
const settled = completed && !monitorHoldsWakeCompletion(rawThread);
const runCompleted = thread.latestRun?.status === "completed";
const settled = status === "ready" && runCompleted && !monitorHoldsWakeCompletion(rawThread);
const parsedCompletedAt = Date.parse(thread.latestRun?.completedAt ?? "");
const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null;
const state = {
Expand All @@ -278,6 +292,7 @@ export function startThreadNotifications(
settled,
completedAt: settled ? completedAt : null,
backgroundWake: rawThread.latestRunBackgroundWake === true,
heldCompletedAt: runCompleted && !settled ? completedAt : null,
};
next.set(thread.id, state);
changed.push([prior, state]);
Expand Down
2 changes: 1 addition & 1 deletion docs/user/mobile-notifications.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Mobile notifications

Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled.
Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread, or the subagent whose approval it asks for. Your environment must have agent activity publishing enabled.

Enable **Live Activity Updates** on iOS, **Agent Live Updates** on Android 16 and newer, or **Ongoing Agent Activity** on older Android versions to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off the same switch to stop future cards.

Expand Down
4 changes: 3 additions & 1 deletion docs/user/thread-sidebar.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,9 @@ Stop on a thread also stops the subagents it delegated to.

Subagent threads started by the agent can't take messages; message the parent
thread instead. When such a subagent needs an approval or an answer, the parent
thread asks for it.
thread asks for it, and an approval notification names the subagent and opens it.
Subagents don't notify you when they finish. The parent notifies you once it
finishes with no delegated work left running.

Expand a tool call in the conversation to see its full command and output.
Summaries shorten shell wrappers and can still describe the latest call after it
Expand Down
24 changes: 18 additions & 6 deletions packages/shared/src/agentAwareness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ export type AgentAwarenessPhase =
| "stale";

export interface SubagentRequestAwareness {
/** The asking subagent, which the alert names and opens. */
readonly threadId: ThreadId;
readonly title: string;
readonly requestId: RuntimeRequestId;
/** The child's own update time, which moves whenever its request changes. */
readonly updatedAt: DateTime.Utc;
Expand Down Expand Up @@ -112,12 +115,18 @@ export function projectThreadAwarenessV2(
) {
return null;
}
const asking =
subagentRequest !== null && resolveThreadAwarenessPhaseV2(thread, false) !== phase
? subagentRequest
: null;
const detail =
phase === "completed"
? "Review the completed task."
: phase === "failed"
? "The agent run failed."
: undefined;
asking !== null
? `${asking.title} needs approval.`
: phase === "completed"
? "Review the completed task."
: phase === "failed"
? "The agent run failed."
: undefined;
return {
environmentId,
threadId: thread.id,
Expand All @@ -134,7 +143,10 @@ export function projectThreadAwarenessV2(
? thread.updatedAt
: DateTime.max(thread.updatedAt, subagentRequest.updatedAt),
),
deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),
deepLink: buildAgentAwarenessDeepLink({
environmentId,
threadId: asking?.threadId ?? thread.id,
}),
};
}

Expand Down
Loading