mirror of
https://github.com/nightly-labs/openbot.git
synced 2026-11-24 10:13:55 +08:00
* Make notifications and Live Activities reach the phone, and add notifications for each agent Notifications and Live Activities: - The host keeps an event that comes while the phone only looks on screen, and sends it when the phone turns out to be away and the member did not see it. - A Live Activity takes the place of a notification only when its view shows that event, and only while its updates go out. Its timestamps always increase. - The host sends a notification again after 10 s and 60 s when the relay does not take it. - Only the last closed connection of a session marks the phone as away. - The relay keeps the end of a Live Activity for 1 hour for a phone without network. - The phone replaces an ended Live Activity when the app opens, and one that is almost 8 hours old. - The phone keeps its notification keys when the server list does not load, and reads the push token again after a failure. - An iPhone reads its APNs environment from the profile that signed the app. - A desktop notification of a remote server uses the last agent list when the request fails. Notifications for each agent: - New optional capability agent-notification-levels-v1. Each member reads and sets their own level of each agent. The host keeps it, applies it to phone notifications, and deletes it for a removed member. - Desktop, web client and mobile show a "Notify me" choice in the agent settings, and apply it. Tests: push-notification-away E2E, new checks in the Team API routes and desktop notification E2E. * Make Settings › Notifications the one place for notifications, synced on all devices - The host keeps each member's level of the whole server next to their agent levels (agent-notification-levels-v1, not released yet), applies both to phone notifications, and sends agent-notification-levels-changed to that member's connections after each change. - Desktop, web client and mobile show one matrix of servers and agents (All activity, Only when it needs me, Nothing) and a mute for each server on this device. A change on one device shows at once on the others. - The desktop server list, menus and island use the effective server level: the synced level, else the level of this device. The phone registration and the Live Activity use it too. - The server menu and the agent settings show the level and open the matrix. Server settings have no notification section any more. Agent rows show only the agent title, and the columns keep their width. Tests: new Team API route checks (server level, live change to the member only), a desktop notification E2E step for the synced server level, and the NotificationMatrix story. * Manage notifications only in the Notifications view - Remove the agent Notifications switch from the agent settings on desktop, web client and mobile. The host still honors the shared switch. For an agent that is off for everyone, the matrix shows a "Turn on" button in place of the levels. - On mobile, "Notify me about" opens the matrix inside the agent sheet, not in a new sheet. - On mobile, the level selections and the server chips have a 12 pt corner radius. * Show the lead of a message in notifications and fit the Live Activity to the watch - Notifications on the computer, in the web client and on the phone show the first sentences of the agent message. They leave out code blocks, tables, headings and mail headers, show tool names as words and hidden secrets as "•••" (#3930). - The Live Activity shows the same lead, and the host and the phone hide secrets in it. It offers Approve only for a command that it shows in full. - The Apple Watch Smart Stack gets its own Live Activity layout with margins, and a white state line for several agents. Tests: new notification summary E2E through the real push and Live Activity services; the Live Activity fence E2E now expects the prose after a code block. * Remove two exports that only their own files use * Send to each phone in its own fiber, and read cached levels for desktop notifications - A failed phone send waits 10 s and then 60 s before it goes again. The other phones no longer wait for it. - A desktop notification of a joined server uses the levels that the manager keeps current. It reads them from the host only when this computer could not read them yet. * Add Team API protocol 9 for capability lists of up to 256 Protocols 7 and 8 read at most 128 capabilities, and main filled that list. With agent-notification-levels-v1 it had 129, so peers on protocol 8 refused the list. - Protocol 9 is the protocol 8 wire with up to 256 capabilities. On WebRTC the marker long-capability-lists-v1 says that a peer reads them. It is in the bootstrap list, so the first compatibility read of a protocol 9 host is complete. - A host leaves the protocol 9 capabilities out of the list of a peer below 9, so protocol 7 and 8 peers get the same list as before. A client sends them only to a protocol 9 host. - agent-notification-levels-v1 is a protocol 9 capability. - Desktop, web client and mobile read compatibility with the 256 limit. E2E: team-api-routes (lists for protocols 7, 8 and 9, newer protocol is 10), team-legacy-clients (protocol 9 and 8 peers over WebRTC). Scripts that announce protocol 7 or 8 now send that protocol's list. * Keep notification level changes that a member makes at the same time The store read the levels before it got the write permit, so two changes that overlapped started from the same levels, and the second save removed the first change. The change now reads the levels inside the permit. E2E: team-api-routes sends two agent levels and a server level at the same time and reads all three back. The step fails on the earlier store. * Do not repeat events that the app could show when the phone goes away The host keeps the events that arrive while the phone app is on screen. When the app said that it goes away, the host sent each kept event it could not judge, such as replies in other threads, so a user who read a channel got them again. Over an open connection the app was on screen, so it now gets only what it surely did not see: an unread reply in the agent's own chat, a turn that still shows as failed, and a request that still waits. After a lost connection, when iOS can have suspended the app first, the host still sends the events it cannot judge. E2E: push-notification-away sends a reply in another thread in both cases. The away step fails on the earlier code.
322 lines
12 KiB
TypeScript
322 lines
12 KiB
TypeScript
// Runs the real Live Activity push service with synthetic unread replies and a local relay adapter.
|
|
// Run: bun scripts/live-activity-code-span-e2e.ts --phase=before
|
|
// Phase selects only the report folder. A cut code span with a lone UTF-16 surrogate always fails,
|
|
// including on the unfixed source. The widget gets the detail as UTF-8, so a lone surrogate shows as U+FFFD.
|
|
import assert from "node:assert/strict";
|
|
import { createHash, randomBytes } from "node:crypto";
|
|
import { EventEmitter } from "node:events";
|
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
import { join, resolve } from "node:path";
|
|
import { type AgentEvent, type AgentRuntimeSnapshot, isAgentRuntimeSnapshot } from "@openbot/contracts/ipc";
|
|
import { LIVE_ACTIVITY_SEALED_LIMIT, type LiveActivityRelayPush } from "@openbot/contracts/live-activity-relay";
|
|
import { isDynamicRecord } from "@openbot/contracts/runtime-values";
|
|
import type { AgentLiveActivityProps } from "@openbot/team-client/live-activity-props";
|
|
import {
|
|
encodeLiveActivityBytes,
|
|
LIVE_ACTIVITY_SECRET_BYTES,
|
|
liveActivityKeys,
|
|
} from "@openbot/team-client/live-activity-seal";
|
|
import { Effect } from "effect";
|
|
import { openSealedLiveActivity } from "../apps/mobile/src/features/live-activity/model/live-activity-open";
|
|
import { LiveActivityPushService } from "../src/main/live-activity-push";
|
|
|
|
const ROOT = resolve(import.meta.dirname, "..");
|
|
const DEADLINE_MS = 10_000;
|
|
const EMOJI = "\u{1F600}";
|
|
// The runtime snapshot holds at most 240 UTF-16 units of a message, and the detail shows 180
|
|
// characters. So each long case mixes ASCII and emoji to pass the snapshot and still be cut.
|
|
const CASES = [
|
|
{
|
|
name: "emoji-code-span-cut",
|
|
input: `Run \`${"a".repeat(149)}${EMOJI.repeat(40)}\` now.`,
|
|
expected: `Run \`${"a".repeat(149)}${EMOJI.repeat(26)}\`…`,
|
|
},
|
|
{
|
|
name: "emoji-code-span-cut-odd",
|
|
input: `Run \`${"a".repeat(150)}${EMOJI.repeat(39)}\` now.`,
|
|
expected: `Run \`${"a".repeat(150)}${EMOJI.repeat(25)}\`…`,
|
|
},
|
|
{ name: "short-emoji-code-span", input: `Run \`ab${EMOJI}cd\` now.`, expected: `Run \`ab${EMOJI}cd\` now.` },
|
|
{ name: "ascii-code-span-cut", input: `Run \`${"a".repeat(200)}\` now.`, expected: `Run \`${"a".repeat(175)}\`…` },
|
|
{
|
|
name: "emoji-text-cut",
|
|
input: `${"a".repeat(170)}${EMOJI.repeat(30)}`,
|
|
expected: `${"a".repeat(170)}${EMOJI.repeat(9)}…`,
|
|
},
|
|
];
|
|
const SOURCES = [
|
|
"scripts/live-activity-code-span-e2e.ts",
|
|
"src/main/live-activity-push.ts",
|
|
"packages/team-client/src/dynamic-island-coordinator.ts",
|
|
"packages/team-client/src/dynamic-island-presentation.ts",
|
|
"packages/team-client/src/agent-message-text.ts",
|
|
"packages/team-client/src/live-activity-props.ts",
|
|
"packages/team-client/src/live-activity-text.ts",
|
|
"packages/team-client/src/message-summary.ts",
|
|
"packages/team-client/src/live-activity-seal.ts",
|
|
"apps/mobile/src/features/live-activity/model/live-activity-open.ts",
|
|
];
|
|
|
|
interface CaseResult {
|
|
name: string;
|
|
input: string;
|
|
expected: string;
|
|
observedDetail: string | null;
|
|
stage: string;
|
|
passed: boolean;
|
|
relayPushes: number;
|
|
snapshotReads: number;
|
|
readStateReads: number;
|
|
relay: { event: string; sealedLength: number; priority: number } | null;
|
|
cleanup: {
|
|
disposeCompleted: boolean;
|
|
registrationRemoved: boolean;
|
|
listenersRemaining: number;
|
|
listenerAdds: number;
|
|
listenerRemoves: number;
|
|
deadlineCleared: boolean;
|
|
};
|
|
}
|
|
|
|
interface Report {
|
|
phase: string;
|
|
surface: string;
|
|
transport: string;
|
|
sourceHashes: Record<string, string>;
|
|
cases: CaseResult[];
|
|
passed: boolean;
|
|
status: string;
|
|
}
|
|
|
|
type DisplayedProps = Pick<AgentLiveActivityProps, "mode" | "title" | "compact" | "detailMarkdown" | "detail">;
|
|
|
|
function decodeDisplayedProps(value: unknown): DisplayedProps {
|
|
assert.ok(isDynamicRecord(value), "The opened content must be a props object.");
|
|
assert.ok(value.mode === "message");
|
|
assert.ok(typeof value.title === "string");
|
|
assert.ok(typeof value.compact === "string");
|
|
assert.ok(typeof value.detailMarkdown === "boolean");
|
|
assert.ok(typeof value.detail === "string");
|
|
return {
|
|
mode: value.mode,
|
|
title: value.title,
|
|
compact: value.compact,
|
|
detailMarkdown: value.detailMarkdown,
|
|
detail: value.detail,
|
|
};
|
|
}
|
|
|
|
function snapshot(text: string): AgentRuntimeSnapshot {
|
|
return {
|
|
agents: [
|
|
{
|
|
id: "fixture-agent",
|
|
name: "Fixture agent",
|
|
notifications: true,
|
|
preview: text,
|
|
updatedAt: "2026-10-17T00:00:00.000Z",
|
|
avatarSeed: "fixture-agent",
|
|
avatarHue: null,
|
|
avatarUrl: null,
|
|
},
|
|
],
|
|
activeTurns: [],
|
|
work: [],
|
|
latestMessages: [{ agentId: "fixture-agent", id: "fixture-message", text, createdAt: "2026-10-17T00:00:00.000Z" }],
|
|
attentionComplete: true,
|
|
pendingPrompts: [],
|
|
pendingApprovals: [],
|
|
pendingBrowserTakeovers: [],
|
|
failedTurns: [],
|
|
};
|
|
}
|
|
|
|
async function runCase(fixture: (typeof CASES)[number]): Promise<CaseResult> {
|
|
const result: CaseResult = {
|
|
...fixture,
|
|
observedDetail: null,
|
|
stage: "setup",
|
|
passed: false,
|
|
relayPushes: 0,
|
|
snapshotReads: 0,
|
|
readStateReads: 0,
|
|
relay: null,
|
|
cleanup: {
|
|
disposeCompleted: false,
|
|
registrationRemoved: false,
|
|
listenersRemaining: 0,
|
|
listenerAdds: 0,
|
|
listenerRemoves: 0,
|
|
deadlineCleared: false,
|
|
},
|
|
};
|
|
const events = new EventEmitter<{ event: [AgentEvent] }>();
|
|
const secret = randomBytes(LIVE_ACTIVITY_SECRET_BYTES);
|
|
const keys = liveActivityKeys(secret);
|
|
let deadline: ReturnType<typeof setTimeout> | undefined;
|
|
let service: LiveActivityPushService | undefined;
|
|
try {
|
|
const runtime = snapshot(fixture.input);
|
|
assert.ok(isAgentRuntimeSnapshot(runtime), "The fixture must be a valid runtime snapshot.");
|
|
let receive: (push: LiveActivityRelayPush) => void = () => {};
|
|
const received = new Promise<LiveActivityRelayPush>((resolvePush, reject) => {
|
|
receive = resolvePush;
|
|
deadline = setTimeout(() => reject(new Error("No local relay push before the deadline.")), DEADLINE_MS);
|
|
});
|
|
service = new LiveActivityPushService({
|
|
agents: {
|
|
on: (event, listener) => {
|
|
result.cleanup.listenerAdds += 1;
|
|
events.on(event, listener);
|
|
},
|
|
off: (event, listener) => {
|
|
result.cleanup.listenerRemoves += 1;
|
|
events.off(event, listener);
|
|
},
|
|
getRuntimeSnapshot: () => {
|
|
result.snapshotReads += 1;
|
|
return runtime;
|
|
},
|
|
listConversationReads: () => {
|
|
result.readStateReads += 1;
|
|
return {
|
|
"fixture-agent": { unreadCount: 1, firstUnreadMessageId: "fixture-message", throughMessageId: null },
|
|
};
|
|
},
|
|
},
|
|
send: (push) =>
|
|
Effect.sync(() => {
|
|
result.relayPushes += 1;
|
|
receive(push);
|
|
return "sent" as const;
|
|
}),
|
|
memberActive: (memberId) => memberId === "fixture-member",
|
|
randomBytes,
|
|
});
|
|
// The connected registration must not send. Disconnect starts the real service update timer.
|
|
service.register(
|
|
"fixture-session",
|
|
{
|
|
memberId: "fixture-member",
|
|
hiddenAgentIds: () => new Set<string>(),
|
|
readOptions: {
|
|
excludeRoutineEvents: true,
|
|
excludeRoutineRunEvents: true,
|
|
excludeHostedSiteEvents: true,
|
|
excludeRoutineQuietAnswers: true,
|
|
},
|
|
},
|
|
{
|
|
serverId: "fixture-server",
|
|
token: "ab".repeat(32),
|
|
environment: "development",
|
|
secret: encodeLiveActivityBytes(secret),
|
|
locale: "en",
|
|
away: false,
|
|
photos: [],
|
|
},
|
|
);
|
|
assert.equal(result.relayPushes, 0);
|
|
assert.equal(events.listenerCount("event"), 1);
|
|
service.disconnected("fixture-session");
|
|
assert.equal(service.showsEvent("fixture-session", { agentId: "fixture-agent", kind: "reply" }, null, null), true);
|
|
result.stage = "relay";
|
|
const push = await received;
|
|
result.relay = { event: push.event, sealedLength: push.sealed?.length ?? 0, priority: push.priority };
|
|
assert.equal(push.event, "update");
|
|
assert.equal(push.environment, "development");
|
|
assert.ok(push.sealed && push.sealed.length <= LIVE_ACTIVITY_SEALED_LIMIT);
|
|
assert.ok(result.snapshotReads > 0 && result.readStateReads > 0);
|
|
result.stage = "decrypt";
|
|
const opened = openSealedLiveActivity(
|
|
push.sealed,
|
|
encodeLiveActivityBytes(keys.seal),
|
|
encodeLiveActivityBytes(keys.tag),
|
|
);
|
|
assert.ok(opened, "The widget must open the real service seal.");
|
|
const props = decodeDisplayedProps(JSON.parse(opened));
|
|
assert.equal(props.mode, "message");
|
|
assert.equal(props.title, "Fixture agent");
|
|
assert.equal(props.compact, "1");
|
|
assert.equal(props.detailMarkdown, true);
|
|
result.observedDetail = props.detail;
|
|
result.stage = "displayed-detail";
|
|
// With the `u` flag, this range matches only a surrogate that is not part of a pair.
|
|
assert.ok(!/[\uD800-\uDFFF]/u.test(props.detail), "The decrypted display detail must have no lone surrogate.");
|
|
assert.ok(!props.detail.includes("\uFFFD"), "The decrypted display detail must have no replacement character.");
|
|
assert.equal(props.detail, fixture.expected, "The decrypted display detail must keep the expected text.");
|
|
result.stage = "complete";
|
|
result.passed = true;
|
|
} catch {
|
|
// Stage and synthetic observations describe the failure without exporting errors or push data.
|
|
result.passed = false;
|
|
} finally {
|
|
if (deadline !== undefined) clearTimeout(deadline);
|
|
result.cleanup.deadlineCleared = true;
|
|
try {
|
|
if (service) {
|
|
// dispose closes the send scope and clears the registration's retry/keepalive timer.
|
|
await Effect.runPromise(service.dispose());
|
|
result.cleanup.disposeCompleted = true;
|
|
result.cleanup.registrationRemoved = !service.showsEvent(
|
|
"fixture-session",
|
|
{ agentId: "fixture-agent", kind: "reply" },
|
|
null,
|
|
null,
|
|
);
|
|
}
|
|
} catch {
|
|
result.passed = false;
|
|
result.stage = "cleanup";
|
|
}
|
|
result.cleanup.listenersRemaining = events.listenerCount("event");
|
|
if (
|
|
!result.cleanup.disposeCompleted ||
|
|
!result.cleanup.registrationRemoved ||
|
|
result.cleanup.listenersRemaining !== 0 ||
|
|
result.cleanup.listenerAdds !== 1 ||
|
|
result.cleanup.listenerRemoves !== 1
|
|
) {
|
|
result.passed = false;
|
|
result.stage = "cleanup";
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
const phaseArgument = process.argv.slice(2);
|
|
const phase = phaseArgument[0]?.replace(/^--phase=/u, "") ?? "before";
|
|
const validArguments =
|
|
phaseArgument.length <= 1 &&
|
|
(phaseArgument.length === 0 || phaseArgument[0]?.startsWith("--phase=")) &&
|
|
/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/u.test(phase);
|
|
const output = join(ROOT, ".openbot-build/live-activity-code-span-e2e", validArguments ? phase : "invalid-arguments");
|
|
const report: Report = {
|
|
phase: validArguments ? phase : "invalid-arguments",
|
|
surface:
|
|
"LiveActivityPushService -> DynamicIslandCoordinator -> liveActivityView -> seal -> local relay -> widget open",
|
|
transport: "injected local send adapter; no account, APNs, provider, or model",
|
|
sourceHashes: {},
|
|
cases: [],
|
|
passed: false,
|
|
status: "setup",
|
|
};
|
|
try {
|
|
assert.ok(validArguments, "Use one --phase=<folder-name> argument.");
|
|
for (const file of SOURCES) {
|
|
report.sourceHashes[file] = createHash("sha256")
|
|
.update(readFileSync(join(ROOT, file)))
|
|
.digest("hex");
|
|
}
|
|
for (const fixture of CASES) report.cases.push(await runCase(fixture));
|
|
report.passed = report.cases.length === CASES.length && report.cases.every((result) => result.passed);
|
|
report.status = report.passed ? "pass" : "fail";
|
|
} catch {
|
|
report.status = validArguments ? "setup-failure" : "invalid-arguments";
|
|
} finally {
|
|
mkdirSync(output, { recursive: true });
|
|
writeFileSync(join(output, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
|
}
|
|
process.stdout.write(`${report.passed ? "PASS" : "FAIL"}: ${join(output, "report.json")}\n`);
|
|
if (!report.passed) process.exitCode = 1;
|