Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add owner bot activity preview to profile cards (#553)

Gustavo Yecd5e430568f9
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index d62e89166..e88e2f2a5 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -38,6 +38,7 @@ export const SPEC_SECONDS = {
"28-community-delete-media-cleanup.spec.ts": 45,
"29-community-bot-avatar-cleanup.spec.ts": 15,
"29-multi-device-read-state.spec.ts": 45,
+ "30-bot-profile-audit-preview.spec.ts": 35,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 19893eea7..6801f0ab9 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([211, 212, 212, 214, 214])
+ expect(totals.sort((left, right) => left - right)).toEqual([218, 219, 219, 219, 223])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/shared/src/db/queries/community/bot-audit-log.ts b/src/shared/src/db/queries/community/bot-audit-log.ts
index 3e78680be..2acf1e693 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -128,28 +128,29 @@ export function pruneBotActivityEventsStatement(db: Database, botId: string) {
}
/**
- * List events for a bot, newest first, with composite cursor pagination on
- * `(createdAt DESC, id DESC)`.
+ * Owner-scoped event page for one live bot, newest first, with composite
+ * cursor pagination on `(createdAt DESC, id DESC)`.
*
- * The list is filtered to bots that are still live (`user.deletedAt IS NULL`);
- * a soft-deleted bot returns an empty list even if raw rows remain.
+ * Ownership and bot/live state are predicates on the query's starting user
+ * row. Event cursor predicates stay inside the LEFT JOIN so an authorized bot
+ * with no events (or no events before the cursor) still returns its sentinel
+ * and maps to an empty page. No matching sentinel means missing, deleted,
+ * human, or non-owned and maps to null.
*/
-export async function listBotActivityEvents(
+export async function listOwnedBotActivityEvents(
db: Database,
opts: {
botId: string;
+ ownerUserId: string;
beforeCreatedAt?: string;
beforeId?: string;
limit?: number;
}
-): Promise<BotActivityEventRow[]> {
- const limit = Math.min(opts.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
- const conds = [
- eq(communityBotActivityEvent.botId, opts.botId),
- isNull(user.deletedAt),
- ];
+): Promise<BotActivityEventRow[] | null> {
+ const limit = Math.max(1, Math.min(opts.limit ?? DEFAULT_LIMIT, MAX_LIMIT));
+ const eventConds = [eq(communityBotActivityEvent.botId, user.id)];
if (opts.beforeCreatedAt !== undefined && opts.beforeId !== undefined) {
- conds.push(
+ eventConds.push(
or(
lt(communityBotActivityEvent.createdAt, opts.beforeCreatedAt),
and(
@@ -159,26 +160,49 @@ export async function listBotActivityEvents(
)!
);
} else if (opts.beforeCreatedAt !== undefined) {
- conds.push(lt(communityBotActivityEvent.createdAt, opts.beforeCreatedAt));
+ eventConds.push(lt(communityBotActivityEvent.createdAt, opts.beforeCreatedAt));
}
const rows = await db
.select({
- id: communityBotActivityEvent.id,
- botId: communityBotActivityEvent.botId,
+ botId: user.id,
+ eventId: communityBotActivityEvent.id,
sessionId: communityBotActivityEvent.sessionId,
launchId: communityBotActivityEvent.launchId,
kind: communityBotActivityEvent.kind,
payload: communityBotActivityEvent.payload,
createdAt: communityBotActivityEvent.createdAt,
})
- .from(communityBotActivityEvent)
- .innerJoin(user, eq(user.id, communityBotActivityEvent.botId))
- .where(and(...conds))
+ .from(user)
+ .leftJoin(communityBotActivityEvent, and(...eventConds))
+ .where(
+ and(
+ eq(user.id, opts.botId),
+ eq(user.isBot, true),
+ eq(user.ownerUserId, opts.ownerUserId),
+ isNull(user.deletedAt)
+ )
+ )
.orderBy(desc(communityBotActivityEvent.createdAt), desc(communityBotActivityEvent.id))
.limit(limit);
- return rows;
+ if (rows.length === 0) return null;
+
+ return rows.flatMap((row) =>
+ row.eventId === null
+ ? []
+ : [
+ {
+ id: row.eventId,
+ botId: row.botId,
+ sessionId: row.sessionId,
+ launchId: row.launchId,
+ kind: row.kind!,
+ payload: row.payload!,
+ createdAt: row.createdAt!,
+ },
+ ]
+ );
}
/**
diff --git a/src/shared/src/db/queries/community/user-profile.ts b/src/shared/src/db/queries/community/user-profile.ts
index d696c78ad..55bf65920 100644
--- a/src/shared/src/db/queries/community/user-profile.ts
+++ b/src/shared/src/db/queries/community/user-profile.ts
@@ -1,6 +1,104 @@
-import { eq } from "drizzle-orm";
+import { and, eq, isNotNull, isNull, or } from "drizzle-orm";
+import { alias } from "drizzle-orm/sqlite-core";
import { communityUserProfile } from "../../community-schema";
+import { user } from "../../schema";
import type { Database } from "../../index";
+import { formatHandle } from "../../../lib/discriminator";
+
+export type PublicProfileIdentity =
+ | { kind: "human" }
+ | {
+ kind: "bot";
+ ownerProfile: { id: string; handle: string };
+ ownedByViewer: boolean;
+ };
+
+export type PublicProfileForViewer = {
+ id: string;
+ name: string;
+ discriminator: string;
+ image: string | null;
+ aboutMe: string;
+ bannerColor: string | null;
+ statusEmoji: string | null;
+ statusText: string;
+ identity: PublicProfileIdentity;
+};
+
+/**
+ * One-read public profile projection for another user's ProfileCard.
+ *
+ * The target, optional profile row, and (for bots) live owner identity are
+ * joined in one query so the profile route does not add a serial owner lookup.
+ * A bot whose target or owner is soft-deleted does not resolve. Ownership is
+ * derived in SQL from the authenticated viewer id; the returned DTO exposes
+ * only the owner's public navigation identity, never the internal ownership
+ * field or email.
+ */
+export async function getPublicProfileForViewer(
+ db: Database,
+ targetUserId: string,
+ viewerUserId: string
+): Promise<PublicProfileForViewer | null> {
+ const target = alias(user, "profile_target");
+ const owner = alias(user, "profile_owner");
+ const rows = await db
+ .select({
+ id: target.id,
+ name: target.name,
+ discriminator: target.discriminator,
+ image: target.image,
+ isBot: target.isBot,
+ aboutMe: communityUserProfile.aboutMe,
+ bannerColor: communityUserProfile.bannerColor,
+ statusEmoji: communityUserProfile.statusEmoji,
+ statusText: communityUserProfile.statusText,
+ ownerId: owner.id,
+ ownerName: owner.name,
+ ownerDiscriminator: owner.discriminator,
+ ownedByViewer: eq(owner.id, viewerUserId).mapWith(Boolean),
+ })
+ .from(target)
+ .leftJoin(communityUserProfile, eq(communityUserProfile.userId, target.id))
+ .leftJoin(
+ owner,
+ and(eq(owner.id, target.ownerUserId), isNull(owner.deletedAt))
+ )
+ .where(
+ and(
+ eq(target.id, targetUserId),
+ isNull(target.deletedAt),
+ or(eq(target.isBot, false), isNotNull(owner.id))
+ )
+ )
+ .limit(1);
+
+ const row = rows[0];
+ if (!row) return null;
+
+ const identity: PublicProfileIdentity = row.isBot
+ ? {
+ kind: "bot",
+ ownerProfile: {
+ id: row.ownerId!,
+ handle: formatHandle(row.ownerName!, row.ownerDiscriminator!),
+ },
+ ownedByViewer: row.ownedByViewer,
+ }
+ : { kind: "human" };
+
+ return {
+ id: row.id,
+ name: row.name,
+ discriminator: row.discriminator,
+ image: row.image,
+ aboutMe: row.aboutMe ?? "",
+ bannerColor: row.bannerColor ?? null,
+ statusEmoji: row.statusEmoji ?? null,
+ statusText: row.statusText ?? "",
+ identity,
+ };
+}
export async function getProfile(db: Database, userId: string) {
const rows = await db
diff --git a/src/shared/test/queries/community-bot-audit-log.test.ts b/src/shared/test/queries/community-bot-audit-log.test.ts
index 14254564a..719db7ee4 100644
--- a/src/shared/test/queries/community-bot-audit-log.test.ts
+++ b/src/shared/test/queries/community-bot-audit-log.test.ts
@@ -1,5 +1,8 @@
-import { describe, it, expect } from "vitest"
+import Sqlite from "better-sqlite3"
+import { drizzle } from "drizzle-orm/better-sqlite3"
+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"
import * as q from "../../src/db/queries/community/bot-audit-log"
+import type { Database } from "../../src/db"
import { BotAuditEventSchema, HostBotAuditEventFrameSchema } from "../../src/schemas"
/**
@@ -18,7 +21,7 @@ describe("community/bot-audit-log exports", () => {
})
it("exposes a reader", () => {
- expect(typeof q.listBotActivityEvents).toBe("function")
+ expect(typeof q.listOwnedBotActivityEvents).toBe("function")
})
it("exposes the retention cap constant", () => {
@@ -28,6 +31,129 @@ describe("community/bot-audit-log exports", () => {
})
})
+describe("listOwnedBotActivityEvents", () => {
+ let sqlite: Sqlite.Database
+ let db: Database
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:")
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ deletedAt TEXT
+ );
+ CREATE TABLE community_bot_activity_event (
+ id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL,
+ session_id TEXT,
+ launch_id TEXT,
+ kind TEXT NOT NULL,
+ payload TEXT NOT NULL,
+ created_at TEXT NOT NULL
+ );
+ `)
+ db = drizzle(sqlite) as unknown as Database
+
+ const insertUser = sqlite.prepare(
+ "INSERT INTO user (id, isBot, ownerUserId, deletedAt) VALUES (?, ?, ?, ?)",
+ )
+ insertUser.run("owner_1", 0, null, null)
+ insertUser.run("owner_2", 0, null, null)
+ insertUser.run("bot_1", 1, "owner_1", null)
+ insertUser.run("empty_bot", 1, "owner_1", null)
+ insertUser.run("foreign_bot", 1, "owner_2", null)
+ insertUser.run("human_1", 0, "owner_1", null)
+ insertUser.run("deleted_bot", 1, "owner_1", "2026-08-01T00:00:00.000Z")
+
+ const insertEvent = sqlite.prepare(`
+ INSERT INTO community_bot_activity_event
+ (id, bot_id, session_id, launch_id, kind, payload, created_at)
+ VALUES (?, ?, NULL, NULL, 'tool_call', '{"name":"read"}', ?)
+ `)
+ insertEvent.run("bae_d", "bot_1", "2026-08-04T00:00:00.000Z")
+ insertEvent.run("bae_c", "bot_1", "2026-08-03T00:00:00.000Z")
+ insertEvent.run("bae_b", "bot_1", "2026-08-03T00:00:00.000Z")
+ insertEvent.run("bae_a", "bot_1", "2026-08-01T00:00:00.000Z")
+ insertEvent.run("bae_foreign", "foreign_bot", "2026-08-05T00:00:00.000Z")
+ insertEvent.run("bae_human", "human_1", "2026-08-05T00:00:00.000Z")
+ insertEvent.run("bae_deleted", "deleted_bot", "2026-08-05T00:00:00.000Z")
+ })
+
+ afterEach(() => sqlite.close())
+
+ it("returns a newest-first bounded page in exactly one select", async () => {
+ const selectSpy = vi.spyOn(db, "select")
+ const rows = await q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ limit: 3,
+ })
+
+ expect(selectSpy).toHaveBeenCalledTimes(1)
+ expect(rows?.map((row) => row.id)).toEqual(["bae_d", "bae_c", "bae_b"])
+ })
+
+ it("keeps tied timestamps lossless with the composite cursor", async () => {
+ const rows = await q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ beforeCreatedAt: "2026-08-03T00:00:00.000Z",
+ beforeId: "bae_c",
+ limit: 5,
+ })
+
+ expect(rows?.map((row) => row.id)).toEqual(["bae_b", "bae_a"])
+ })
+
+ it("supports a timestamp-only cursor", async () => {
+ const rows = await q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ beforeCreatedAt: "2026-08-03T00:00:00.000Z",
+ limit: 5,
+ })
+
+ expect(rows?.map((row) => row.id)).toEqual(["bae_a"])
+ })
+
+ it("returns an empty page for an owned live bot with no matching events", async () => {
+ await expect(
+ q.listOwnedBotActivityEvents(db, {
+ botId: "empty_bot",
+ ownerUserId: "owner_1",
+ limit: 5,
+ }),
+ ).resolves.toEqual([])
+
+ await expect(
+ q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1",
+ ownerUserId: "owner_1",
+ beforeCreatedAt: "2025-01-01T00:00:00.000Z",
+ beforeId: "bae_0",
+ limit: 5,
+ }),
+ ).resolves.toEqual([])
+ })
+
+ it.each([
+ ["foreign bot", "foreign_bot"],
+ ["human", "human_1"],
+ ["deleted bot", "deleted_bot"],
+ ["missing bot", "missing_bot"],
+ ])("returns null for a %s", async (_label, botId) => {
+ await expect(
+ q.listOwnedBotActivityEvents(db, {
+ botId,
+ ownerUserId: "owner_1",
+ limit: 5,
+ }),
+ ).resolves.toBeNull()
+ })
+})
+
describe("BotAuditEventSchema β€” payload discriminated union", () => {
it("accepts a cli_invocation payload", () => {
const r = BotAuditEventSchema.safeParse({
diff --git a/src/shared/test/queries/community-user-profile.test.ts b/src/shared/test/queries/community-user-profile.test.ts
index 3e9c61ccc..b4a20bcfc 100644
--- a/src/shared/test/queries/community-user-profile.test.ts
+++ b/src/shared/test/queries/community-user-profile.test.ts
@@ -1,6 +1,9 @@
-import { describe, it, expect, vi } from "vitest";
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import * as profileQueries from "../../src/db/queries/community/user-profile";
import { communityUserProfile } from "../../src/db/community-schema";
+import type { Database } from "../../src/db";
function createSelectMock(rows: any[]) {
const chain: any = {};
@@ -20,12 +23,117 @@ function createUpsertMock(returnRow: any) {
}
describe("community/user-profile exports", () => {
- it("exports getProfile + updateProfile", () => {
+ it("exports public profile + getProfile + updateProfile queries", () => {
+ expect(typeof profileQueries.getPublicProfileForViewer).toBe("function");
expect(typeof profileQueries.getProfile).toBe("function");
expect(typeof profileQueries.updateProfile).toBe("function");
});
});
+describe("getPublicProfileForViewer", () => {
+ let sqlite: Sqlite.Database;
+ let db: Database;
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:");
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL UNIQUE,
+ emailVerified INTEGER,
+ image TEXT,
+ createdAt TEXT NOT NULL,
+ updatedAt TEXT NOT NULL,
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ deletedAt TEXT,
+ discriminator TEXT NOT NULL DEFAULT '0000',
+ lastRefreshContextAt TEXT
+ );
+ CREATE TABLE community_user_profile (
+ user_id TEXT PRIMARY KEY,
+ about_me TEXT DEFAULT '',
+ banner_color TEXT,
+ status_emoji TEXT,
+ status_text TEXT DEFAULT ''
+ );
+ `);
+ db = drizzle(sqlite) as unknown as Database;
+
+ const insertUser = sqlite.prepare(`
+ INSERT INTO user
+ (id, name, email, image, createdAt, updatedAt, isBot, ownerUserId, deletedAt, discriminator)
+ VALUES (?, ?, ?, ?, '2026-01-01', '2026-01-01', ?, ?, ?, ?)
+ `);
+ insertUser.run("viewer_1", "Viewer", "[email protected]", null, 0, null, null, "0001");
+ insertUser.run("human_1", "Human", "[email protected]", "human.png", 0, null, null, "0002");
+ insertUser.run("owner_1", "Owner", "[email protected]", null, 0, null, null, "0042");
+ insertUser.run("bot_1", "Helper", "[email protected]", "bot.png", 1, "owner_1", null, "0100");
+ insertUser.run("deleted_target", "Gone", "[email protected]", null, 0, null, "2026-02-01", "0003");
+ insertUser.run("deleted_owner", "Old Owner", "[email protected]", null, 0, null, "2026-02-01", "0004");
+ insertUser.run("orphaned_bot", "Orphan", "[email protected]", null, 1, "deleted_owner", null, "0101");
+
+ sqlite.prepare(`
+ INSERT INTO community_user_profile
+ (user_id, about_me, banner_color, status_emoji, status_text)
+ VALUES ('bot_1', 'backend bot', '#123456', 'πŸ› οΈ', 'Working')
+ `).run();
+ });
+
+ afterEach(() => sqlite.close());
+
+ it("returns the human discriminator without bot-only identity fields", async () => {
+ await expect(profileQueries.getPublicProfileForViewer(db, "human_1", "viewer_1"))
+ .resolves.toEqual({
+ id: "human_1",
+ name: "Human",
+ discriminator: "0002",
+ image: "human.png",
+ aboutMe: "",
+ bannerColor: null,
+ statusEmoji: null,
+ statusText: "",
+ identity: { kind: "human" },
+ });
+ });
+
+ it("returns canonical public owner navigation and SQL-derived viewer ownership", async () => {
+ const ownerView = await profileQueries.getPublicProfileForViewer(db, "bot_1", "owner_1");
+ expect(ownerView).toEqual({
+ id: "bot_1",
+ name: "Helper",
+ discriminator: "0100",
+ image: "bot.png",
+ aboutMe: "backend bot",
+ bannerColor: "#123456",
+ statusEmoji: "πŸ› οΈ",
+ statusText: "Working",
+ identity: {
+ kind: "bot",
+ ownerProfile: { id: "owner_1", handle: "Owner#0042" },
+ ownedByViewer: true,
+ },
+ });
+
+ const otherView = await profileQueries.getPublicProfileForViewer(db, "bot_1", "viewer_1");
+ expect(otherView?.identity).toEqual({
+ kind: "bot",
+ ownerProfile: { id: "owner_1", handle: "Owner#0042" },
+ ownedByViewer: false,
+ });
+ expect(otherView).not.toHaveProperty("ownerUserId");
+ expect(otherView).not.toHaveProperty("email");
+ });
+
+ it("does not resolve a soft-deleted target or a bot whose owner is soft-deleted", async () => {
+ await expect(profileQueries.getPublicProfileForViewer(db, "deleted_target", "viewer_1"))
+ .resolves.toBeNull();
+ await expect(profileQueries.getPublicProfileForViewer(db, "orphaned_bot", "viewer_1"))
+ .resolves.toBeNull();
+ });
+});
+
describe("getProfile", () => {
it("returns the row including statusEmoji/statusText when a profile exists", async () => {
const db = createSelectMock([
diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts
index 9daafabb4..cfe138844 100644
--- a/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts
+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.test.ts
@@ -1,8 +1,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
-const mockGetBotOwnedBy = vi.fn()
-const mockListBotActivityEvents = vi.fn()
+const mockListOwnedBotActivityEvents = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -15,11 +14,8 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
- communityBot: {
- getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),
- },
communityBotAuditLog: {
- listBotActivityEvents: (...a: unknown[]) => mockListBotActivityEvents(...a),
+ listOwnedBotActivityEvents: (...a: unknown[]) => mockListOwnedBotActivityEvents(...a),
},
},
}
@@ -71,20 +67,22 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
isAuthed = false
const res = await GET(req(), ctx("b1"))
expect(res.status).toBe(401)
- expect(mockGetBotOwnedBy).not.toHaveBeenCalled()
+ expect(mockListOwnedBotActivityEvents).not.toHaveBeenCalled()
})
- it("returns 404 when the bot is missing or not owned by the session user (getBotOwnedBy filters both)", async () => {
- mockGetBotOwnedBy.mockResolvedValue(null)
+ it("returns 404 when the one owner-scoped query finds no live owned bot", async () => {
+ mockListOwnedBotActivityEvents.mockResolvedValue(null)
const res = await GET(req(), ctx("b1"))
expect(res.status).toBe(404)
- expect(mockGetBotOwnedBy).toHaveBeenCalledWith(expect.anything(), "b1", "u1")
- expect(mockListBotActivityEvents).not.toHaveBeenCalled()
+ expect(mockListOwnedBotActivityEvents).toHaveBeenCalledTimes(1)
+ expect(mockListOwnedBotActivityEvents).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ botId: "b1", ownerUserId: "u1" }),
+ )
})
it("returns rows + a null nextCursor when fewer than `limit` results come back", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })
- mockListBotActivityEvents.mockResolvedValue([
+ mockListOwnedBotActivityEvents.mockResolvedValue([
{
id: "bae_1",
botId: "b1",
@@ -111,9 +109,17 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
expect(body.nextCursor).toBe(null)
})
+ it("returns 200 with an empty page for an owned bot with no events", async () => {
+ mockListOwnedBotActivityEvents.mockResolvedValue([])
+ const res = await GET(req("?limit=5"), ctx("b1"))
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ events: [], nextCursor: null })
+ expect(mockListOwnedBotActivityEvents).toHaveBeenCalledTimes(1)
+ })
+
it("round-trips a canonical tool_call row: name is lowercased, target survives", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })
- mockListBotActivityEvents.mockResolvedValue([
+ mockListOwnedBotActivityEvents.mockResolvedValue([
{
id: "bae_1",
botId: "b1",
@@ -132,7 +138,6 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
})
it("returns a composite nextCursor when the page fills to the limit", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })
const rows = Array.from({ length: 2 }).map((_, i) => ({
id: `bae_${i}`,
botId: "b1",
@@ -142,7 +147,7 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
payload: JSON.stringify({ name: "Read" }),
createdAt: `2025-01-01T00:00:0${i}.000Z`,
}))
- mockListBotActivityEvents.mockResolvedValue(rows)
+ mockListOwnedBotActivityEvents.mockResolvedValue(rows)
const res = await GET(req("?limit=2"), ctx("b1"))
const body = (await res.json()) as { nextCursor: { beforeCreatedAt: string; beforeId: string } | null }
// Composite cursor uses the LAST row (oldest in the newest-first page) so
@@ -154,16 +159,16 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
})
it("forwards beforeCreatedAt + beforeId to the query for cursor pagination", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })
- mockListBotActivityEvents.mockResolvedValue([])
+ mockListOwnedBotActivityEvents.mockResolvedValue([])
await GET(
req("?beforeCreatedAt=2025-01-01T00:00:00.000Z&beforeId=bae_x&limit=25"),
ctx("b1"),
)
- expect(mockListBotActivityEvents).toHaveBeenCalledWith(
+ expect(mockListOwnedBotActivityEvents).toHaveBeenCalledWith(
expect.anything(),
{
botId: "b1",
+ ownerUserId: "u1",
beforeCreatedAt: "2025-01-01T00:00:00.000Z",
beforeId: "bae_x",
limit: 25,
@@ -172,8 +177,7 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
})
it("returns a parsed {from,to} payload for a model_changed row (guards parseAuditLogPayload's default)", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })
- mockListBotActivityEvents.mockResolvedValue([
+ mockListOwnedBotActivityEvents.mockResolvedValue([
{
id: "bae_m",
botId: "b1",
@@ -192,16 +196,15 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
})
it("caps limit at 100 and floors it at 1 (defends against unbounded page requests)", async () => {
- mockGetBotOwnedBy.mockResolvedValue({ id: "b1" })
- mockListBotActivityEvents.mockResolvedValue([])
+ mockListOwnedBotActivityEvents.mockResolvedValue([])
await GET(req("?limit=99999"), ctx("b1"))
- expect(mockListBotActivityEvents).toHaveBeenCalledWith(
+ expect(mockListOwnedBotActivityEvents).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ limit: 100 }),
)
await GET(req("?limit=0"), ctx("b1"))
// 0 β†’ falls back to default (50) via the || fallback.
- expect(mockListBotActivityEvents).toHaveBeenLastCalledWith(
+ expect(mockListOwnedBotActivityEvents).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ limit: 50 }),
)
diff --git a/src/web/src/app/api/community/bots/[id]/audit-log/route.ts b/src/web/src/app/api/community/bots/[id]/audit-log/route.ts
index fdb3967ad..da0fb4a31 100644
--- a/src/web/src/app/api/community/bots/[id]/audit-log/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/audit-log/route.ts
@@ -24,10 +24,6 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const id = ctx.params?.id as string
const db = getDb(ctx.env.DB)
- // Ownership + soft-delete gate β€” matches `getBotOwnedBy` predicate.
- const bot = await queries.communityBot.getBotOwnedBy(db, id, ctx.userId)
- if (!bot) return writeError("bot not found", 404)
-
const url = new URL(req.url)
const beforeCreatedAt = url.searchParams.get("beforeCreatedAt") ?? undefined
const beforeId = url.searchParams.get("beforeId") ?? undefined
@@ -36,12 +32,14 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
? Math.max(1, Math.min(MAX_LIMIT, Number.parseInt(limitRaw, 10) || DEFAULT_LIMIT))
: DEFAULT_LIMIT
- const rows = await queries.communityBotAuditLog.listBotActivityEvents(db, {
+ const rows = await queries.communityBotAuditLog.listOwnedBotActivityEvents(db, {
botId: id,
+ ownerUserId: ctx.userId,
beforeCreatedAt,
beforeId,
limit,
})
+ if (rows === null) return writeError("bot not found", 404)
const events = rows.map((r) => ({
id: r.id,
diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
index d64e4baf0..82507f245 100644
--- a/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/[userId]/profile/route.test.ts
@@ -1,8 +1,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
-const getUserPublic = vi.fn()
-const getProfile = vi.fn()
+const getPublicProfileForViewer = vi.fn()
const listMemberServerIds = vi.fn()
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
@@ -12,8 +11,9 @@ vi.mock("@alook/shared", async () => {
return {
...actual,
queries: {
- user: { getUserPublic: (...a: unknown[]) => getUserPublic(...a) },
- communityUserProfile: { getProfile: (...a: unknown[]) => getProfile(...a) },
+ communityUserProfile: {
+ getPublicProfileForViewer: (...a: unknown[]) => getPublicProfileForViewer(...a),
+ },
communityMember: { listMemberServerIds: (...a: unknown[]) => listMemberServerIds(...a) },
},
}
@@ -41,7 +41,17 @@ const req = new NextRequest("http://localhost/api/community/users/u2/profile")
describe("GET /api/community/users/[userId]/profile", () => {
beforeEach(() => {
vi.clearAllMocks()
- getUserPublic.mockResolvedValue({ id: "u2", name: "Gus", discriminator: "1337", image: null })
+ getPublicProfileForViewer.mockResolvedValue({
+ id: "u2",
+ name: "Gus",
+ discriminator: "1337",
+ image: null,
+ aboutMe: "hi",
+ bannerColor: null,
+ statusEmoji: "🎧",
+ statusText: "Vibing",
+ identity: { kind: "human" },
+ })
listMemberServerIds.mockImplementation(async (_db: unknown, userId: string) => {
if (userId === "u1") return ["s1", "s2"]
if (userId === "u2") return ["s2", "s3"]
@@ -49,12 +59,13 @@ describe("GET /api/community/users/[userId]/profile", () => {
})
})
- it("does not include email in the response payload and returns the exact expected shape, including statusEmoji/statusText from the joined profile row", async () => {
- getProfile.mockResolvedValue({ aboutMe: "hi", bannerColor: null, statusEmoji: "🎧", statusText: "Vibing" })
+ it("returns the exact human profile union and does not include private identity fields", async () => {
const res = await GET(req, { params: { userId: "u2" } } as never)
expect(res.status).toBe(200)
const body = await res.json() as Record<string, unknown>
expect(body).not.toHaveProperty("email")
+ expect(body).not.toHaveProperty("ownerUserId")
+ expect(body).not.toHaveProperty("isBot")
expect(body).toEqual({
id: "u2",
name: "Gus",
@@ -65,11 +76,23 @@ describe("GET /api/community/users/[userId]/profile", () => {
mutualServers: 1,
statusEmoji: "🎧",
statusText: "Vibing",
+ kind: "human",
})
+ expect(getPublicProfileForViewer).toHaveBeenCalledWith(expect.anything(), "u2", "u1")
})
it("defaults to null/\"\" when the target has no profile row (no crash)", async () => {
- getProfile.mockResolvedValue(null)
+ getPublicProfileForViewer.mockResolvedValue({
+ id: "u2",
+ name: "Gus",
+ discriminator: "1337",
+ image: null,
+ aboutMe: "",
+ bannerColor: null,
+ statusEmoji: null,
+ statusText: "",
+ identity: { kind: "human" },
+ })
const res = await GET(req, { params: { userId: "u2" } } as never)
expect(res.status).toBe(200)
const body = await res.json()
@@ -77,11 +100,55 @@ describe("GET /api/community/users/[userId]/profile", () => {
expect(body.statusText).toBe("")
})
- it("404s when the target doesn't exist or is soft-deleted β€” getUserPublic excludes deleted rows unconditionally", async () => {
- getUserPublic.mockResolvedValue(null)
+ it("returns the bot union with a public owner navigation ref and exact owner flag", async () => {
+ getPublicProfileForViewer.mockResolvedValue({
+ id: "b1",
+ name: "Maia",
+ discriminator: "6751",
+ image: null,
+ aboutMe: "backend",
+ bannerColor: null,
+ statusEmoji: null,
+ statusText: "",
+ identity: {
+ kind: "bot",
+ ownerProfile: { id: "u1", handle: "gus#1813" },
+ ownedByViewer: true,
+ },
+ })
+ const res = await GET(req, { params: { userId: "b1" } } as never)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual(expect.objectContaining({
+ kind: "bot",
+ ownerProfile: { id: "u1", handle: "gus#1813" },
+ ownedByViewer: true,
+ }))
+ })
+
+ it("404s when the joined live target/owner query does not resolve", async () => {
+ getPublicProfileForViewer.mockResolvedValue(null)
const res = await GET(req, { params: { userId: "u2" } } as never)
expect(res.status).toBe(404)
const body = await res.json() as Record<string, unknown>
expect(body.error).toBe("user not found")
})
+
+ it("starts both mutual-server reads concurrently after the joined profile read", async () => {
+ let resolveViewer!: (ids: string[]) => void
+ let resolveTarget!: (ids: string[]) => void
+ const viewer = new Promise<string[]>((resolve) => { resolveViewer = resolve })
+ const target = new Promise<string[]>((resolve) => { resolveTarget = resolve })
+ listMemberServerIds.mockImplementation((_db: unknown, userId: string) =>
+ userId === "u1" ? viewer : target,
+ )
+
+ const response = GET(req, { params: { userId: "u2" } } as never)
+ await vi.waitFor(() => expect(listMemberServerIds).toHaveBeenCalledTimes(2))
+ resolveViewer(["s1", "s2"])
+ resolveTarget(["s2", "s3"])
+
+ const res = await response
+ expect(res.status).toBe(200)
+ expect((await res.json()).mutualServers).toBe(1)
+ })
})
diff --git a/src/web/src/app/api/community/users/[userId]/profile/route.ts b/src/web/src/app/api/community/users/[userId]/profile/route.ts
index 4e8da7598..d01c1480a 100644
--- a/src/web/src/app/api/community/users/[userId]/profile/route.ts
+++ b/src/web/src/app/api/community/users/[userId]/profile/route.ts
@@ -9,29 +9,32 @@ export const GET = withAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
- // Get target user basic info
- const targetUser = await queries.user.getUserPublic(db, id)
- if (!targetUser) return writeError("user not found", 404)
-
- // Get profile data
- const profile = await queries.communityUserProfile.getProfile(db, id)
+ const profile = await queries.communityUserProfile.getPublicProfileForViewer(
+ db,
+ id,
+ ctx.userId,
+ )
+ if (!profile) return writeError("user not found", 404)
// Find mutual servers (servers where both viewer and target are members)
- const viewerServerIds = await queries.communityMember.listMemberServerIds(db, ctx.userId)
- const targetServerIds = await queries.communityMember.listMemberServerIds(db, id)
+ const [viewerServerIds, targetServerIds] = await Promise.all([
+ queries.communityMember.listMemberServerIds(db, ctx.userId),
+ queries.communityMember.listMemberServerIds(db, id),
+ ])
const viewerSet = new Set(viewerServerIds)
const mutualServers = targetServerIds.filter((sid) => viewerSet.has(sid)).length
return writeJSON({
- id: targetUser.id,
- name: targetUser.name,
- discriminator: targetUser.discriminator,
- image: targetUser.image,
- aboutMe: profile?.aboutMe ?? "",
- bannerColor: profile?.bannerColor ?? null,
+ id: profile.id,
+ name: profile.name,
+ discriminator: profile.discriminator,
+ image: profile.image,
+ aboutMe: profile.aboutMe,
+ bannerColor: profile.bannerColor,
mutualServers,
- statusEmoji: profile?.statusEmoji ?? null,
- statusText: profile?.statusText ?? "",
+ statusEmoji: profile.statusEmoji,
+ statusText: profile.statusText,
+ ...profile.identity,
})
})
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index f87bec51a..1ce99ec4c 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -2753,3 +2753,35 @@ body {
background-color: var(--background);
min-height: 100dvh;
}
+
+/* Hallmark Β· active bot boundary: strong beat, weak beat, pause. */
+.bot-audit-active-heartbeat::before {
+ animation: bot-audit-heartbeat 2s ease-in-out infinite;
+}
+
+@keyframes bot-audit-heartbeat {
+ 0%,
+ 36%,
+ 100% {
+ opacity: 0.28;
+ }
+
+ 8% {
+ opacity: 0.9;
+ }
+
+ 16% {
+ opacity: 0.34;
+ }
+
+ 26% {
+ opacity: 0.62;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .bot-audit-active-heartbeat::before {
+ animation: none;
+ opacity: 0.55;
+ }
+}
diff --git a/src/web/src/components/community/bots/bot-activity-row.test.ts b/src/web/src/components/community/bots/bot-activity-row.test.ts
index e984a0550..7e865691e 100644
--- a/src/web/src/components/community/bots/bot-activity-row.test.ts
+++ b/src/web/src/components/community/bots/bot-activity-row.test.ts
@@ -17,6 +17,9 @@ function render(event: AuditEvent): TestRenderer.ReactTestRenderer {
const flatten = (children: unknown): string => {
if (typeof children === "string") return children
if (Array.isArray(children)) return children.map(flatten).join("")
+ if (children && typeof children === "object" && "children" in (children as any)) {
+ return flatten((children as any).children)
+ }
if (children && typeof children === "object" && "props" in (children as any)) {
return flatten((children as any).props.children)
}
@@ -61,6 +64,32 @@ describe("BotActivityRow β€” model_changed", () => {
})
})
+describe("BotActivityRow β€” concrete command copy", () => {
+ it("renders the actual short CLI command", () => {
+ const renderer = render({
+ id: "e-cli",
+ kind: "cli_invocation",
+ payload: { subcommand: "inboxPull" },
+ sessionId: null,
+ launchId: null,
+ createdAt: "2026-07-26T00:00:00.000Z",
+ })
+ expect(flatten(renderer.root)).toContain("alook inbox pull")
+ })
+
+ it("renders the normalized tool name", () => {
+ const renderer = render({
+ id: "e-tool",
+ kind: "tool_call",
+ payload: { name: "Read", target: "/tmp/notes.md" },
+ sessionId: null,
+ launchId: null,
+ createdAt: "2026-07-26T00:00:00.000Z",
+ })
+ expect(flatten(renderer.root)).toContain("read")
+ })
+})
+
describe("BotActivityRow β€” provider_changed", () => {
function providerRowText(renderer: TestRenderer.ReactTestRenderer): string {
return rowText(renderer, "bot-activity-event-provider_changed")
diff --git a/src/web/src/components/community/bots/bot-activity-row.tsx b/src/web/src/components/community/bots/bot-activity-row.tsx
index 3852a2972..e22b5be46 100644
--- a/src/web/src/components/community/bots/bot-activity-row.tsx
+++ b/src/web/src/components/community/bots/bot-activity-row.tsx
@@ -2,6 +2,10 @@
import { useState } from "react"
import type { AuditEvent, AuditKind } from "@/hooks/community/use-bot-audit-log"
+import {
+ formatAlookAuditCommand,
+ formatAuditToolName,
+} from "@/lib/community/audit-event-summary"
/**
* One audit-log entry. Rendered as a 3-column strip:
@@ -77,17 +81,17 @@ function RowBody({
onToggle: () => void
}) {
if (event.kind === "cli_invocation") {
- const p = event.payload as { subcommand?: string } | null
- const sub = p?.subcommand ?? "?"
+ const command = formatAlookAuditCommand(event.payload)
+ const subcommand = command.replace(/^alook\s+/, "")
return (
<span className="font-mono text-[13px] text-foreground">
- alook <span className="text-muted-foreground">{sub}</span>
+ alook <span className="text-muted-foreground">{subcommand}</span>
</span>
)
}
if (event.kind === "tool_call") {
const p = event.payload as { name?: string; target?: string } | null
- const name = (p?.name ?? "?").toLowerCase()
+ const name = formatAuditToolName(event.payload)
if (p?.target) {
return (
<div
diff --git a/src/web/src/components/community/bots/bot-list-controller.test.ts b/src/web/src/components/community/bots/bot-list-controller.test.ts
index 5c95dbe57..89cc0eaca 100644
--- a/src/web/src/components/community/bots/bot-list-controller.test.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.test.ts
@@ -13,7 +13,9 @@ const readWebSource = (path: string) => readFileSync(resolve(webRoot, path), "ut
const mocks = vi.hoisted(() => ({
hookOrder: [] as string[],
target: "mac1" as string | null,
+ audit: null as string | null,
bots: [] as BotSummary[],
+ botsDataReady: true,
machines: [] as Array<Record<string, unknown>>,
botsLoading: false,
machinesLoading: false,
@@ -21,6 +23,7 @@ const mocks = vi.hoisted(() => ({
onboardingSnapshot: null as Record<string, unknown> | null,
actionState: null as Record<string, unknown> | null,
push: vi.fn(),
+ replace: vi.fn(),
createDm: vi.fn(),
del: vi.fn(),
resetBot: vi.fn(),
@@ -36,17 +39,29 @@ const mocks = vi.hoisted(() => ({
vi.mock("next/navigation", () => ({
useRouter: () => {
mocks.hookOrder.push("router")
- return { push: mocks.push }
+ return { push: mocks.push, replace: mocks.replace }
},
useSearchParams: () => {
mocks.hookOrder.push("searchParams")
- return { get: () => mocks.target }
+ return {
+ get: (key: string) => key === "machineId" ? mocks.target : mocks.audit,
+ toString: () => {
+ const params = new URLSearchParams()
+ if (mocks.target) params.set("machineId", mocks.target)
+ if (mocks.audit) params.set("audit", mocks.audit)
+ return params.toString()
+ },
+ }
},
}))
vi.mock("@/hooks/community/use-bots", () => ({
useBots: () => {
mocks.hookOrder.push("bots")
- return { bots: mocks.bots, isLoading: mocks.botsLoading }
+ return {
+ bots: mocks.bots,
+ data: mocks.botsDataReady ? { bots: mocks.bots } : undefined,
+ isLoading: mocks.botsLoading,
+ }
},
useDeleteBot: () => {
mocks.hookOrder.push("delete")
@@ -130,7 +145,9 @@ describe("useBotListController", () => {
vi.useFakeTimers()
mocks.hookOrder.length = 0
mocks.target = "mac1"
+ mocks.audit = null
mocks.bots = [bot("b1", "mac1")]
+ mocks.botsDataReady = true
mocks.machines = [
{ id: "mac1", displayName: "One", hostname: "one", status: "online" },
{ id: "mac2", displayName: "Two", hostname: "two", status: "online" },
@@ -219,7 +236,7 @@ describe("useBotListController", () => {
}
})
- it("retains all observable state and both ref-backed lifecycles across loading/data rerenders", () => {
+ it("retains non-URL state and both ref-backed lifecycles across loading/data rerenders", () => {
mocks.target = null
const renderer = render()
const refs = latest.groupRefs
@@ -229,8 +246,6 @@ describe("useBotListController", () => {
latest.setCreateOpen(true)
latest.setEditingBot(selected)
latest.setEditOpen(true)
- latest.setActivityBot(selected)
- latest.setActivityOpen(true)
latest.setBugReportBot({ id: selected.id, name: selected.name })
latest.setBugReportOpen(true)
latest.setConfirmDelete(selected)
@@ -247,8 +262,8 @@ describe("useBotListController", () => {
expect(latest.createOpen).toBe(true)
expect(latest.editingBot).toBe(selected)
expect(latest.editOpen).toBe(true)
- expect(latest.activityBot).toBe(selected)
- expect(latest.activityOpen).toBe(true)
+ expect(latest.activityBot).toBeNull()
+ expect(latest.activityOpen).toBe(false)
expect(latest.bugReportBot).toEqual({ id: "selected", name: "selected" })
expect(latest.bugReportOpen).toBe(true)
expect(latest.confirmDelete).toBe(selected)
@@ -287,6 +302,79 @@ describe("useBotListController", () => {
expect(vi.getTimerCount()).toBe(0)
})
+ it("opens an owned audit deep link only after its bot is available", () => {
+ mocks.audit = "b1"
+ mocks.botsDataReady = false
+ mocks.botsLoading = true
+ const renderer = render()
+ expect(latest.activityOpen).toBe(false)
+ expect(latest.activityBot).toBeNull()
+
+ mocks.botsLoading = false
+ mocks.botsDataReady = true
+ act(() => renderer.update(React.createElement(Probe)))
+ expect(latest.activityOpen).toBe(true)
+ expect(latest.activityBot?.id).toBe("b1")
+ expect(mocks.replace).not.toHaveBeenCalled()
+ })
+
+ it("does not consume a reload deep link during a transient idle query without data", () => {
+ mocks.audit = "b1"
+ mocks.bots = []
+ mocks.botsLoading = false
+ mocks.botsDataReady = false
+ const renderer = render()
+ expect(latest.activityOpen).toBe(false)
+ expect(mocks.replace).not.toHaveBeenCalled()
+
+ mocks.bots = [bot("b1", "mac1")]
+ mocks.botsDataReady = true
+ act(() => renderer.update(React.createElement(Probe)))
+ expect(latest.activityOpen).toBe(true)
+ expect(latest.activityBot?.id).toBe("b1")
+ expect(mocks.replace).not.toHaveBeenCalled()
+ })
+
+ it("clears invalid or nonowned audit ids without opening the modal", () => {
+ mocks.audit = "foreign"
+ render()
+ expect(latest.activityOpen).toBe(false)
+ expect(latest.activityBot).toBeNull()
+ expect(mocks.replace).toHaveBeenCalledWith("/c/me/bots?machineId=mac1")
+ })
+
+ it("pushes URL-owned activity state, preserves machineId, and closes with replace", () => {
+ const renderer = render()
+ act(() => latest.openActivity(mocks.bots[0]!))
+ expect(mocks.push).toHaveBeenCalledWith("/c/me/bots?machineId=mac1&audit=b1")
+
+ mocks.audit = "b1"
+ act(() => renderer.update(React.createElement(Probe)))
+ expect(latest.activityOpen).toBe(true)
+ expect(latest.activityBot?.id).toBe("b1")
+
+ act(() => latest.onActivityOpenChange(false))
+ expect(latest.activityOpen).toBe(false)
+ expect(latest.activityBot).toBeNull()
+ expect(mocks.replace).toHaveBeenLastCalledWith("/c/me/bots?machineId=mac1")
+ })
+
+ it("closes on Back and reopens the same owned target on Forward", () => {
+ mocks.audit = "b1"
+ const renderer = render()
+ expect(latest.activityOpen).toBe(true)
+
+ mocks.audit = null
+ act(() => renderer.update(React.createElement(Probe)))
+ expect(latest.activityOpen).toBe(false)
+ expect(latest.activityBot).toBeNull()
+
+ mocks.audit = "b1"
+ act(() => renderer.update(React.createElement(Probe)))
+ expect(latest.activityOpen).toBe(true)
+ expect(latest.activityBot?.id).toBe("b1")
+ })
+
it("clears a normally consumed target after exactly 2000ms", () => {
render()
expect(latest.highlightId).toBe("mac1")
diff --git a/src/web/src/components/community/bots/bot-list-controller.ts b/src/web/src/components/community/bots/bot-list-controller.ts
index 9dda835a7..408e7b631 100644
--- a/src/web/src/components/community/bots/bot-list-controller.ts
+++ b/src/web/src/components/community/bots/bot-list-controller.ts
@@ -5,6 +5,7 @@ import { useRouter, useSearchParams } from "next/navigation"
import { isPresenceOnline } from "@alook/shared"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
+import { removeCommunityParam } from "@/lib/community/community-route"
import { machineName as resolveMachineName } from "@/lib/community/machine-name"
import { useMachines } from "@/hooks/community/use-machines"
import {
@@ -30,6 +31,7 @@ export function useBotListController(): BotListController {
const searchParams = useSearchParams()
const botsQuery = useBots()
const { bots, isLoading } = botsQuery
+ const botsResolved = botsQuery.data !== undefined
const { machines, isLoading: machinesLoading } = useMachines()
const onlineUserIds = useOnlineUserIds()
const [createOpen, setCreateOpen] = useState(false)
@@ -131,9 +133,11 @@ export function useBotListController(): BotListController {
}, [bots, machines])
const targetMachineId = searchParams.get("machineId")
+ const targetAuditBotId = searchParams.get("audit")
const [highlightId, setHighlightId] = useState<string | null>(null)
const groupRefs = useRef<Record<string, HTMLDivElement | null>>({})
const scrolledForRef = useRef<string | null>(null)
+ const suppressedAuditRef = useRef<string | null>(null)
useEffect(() => {
if (!targetMachineId || bots.length === 0) return
setCollapsedMachines((current) => {
@@ -150,6 +154,46 @@ export function useBotListController(): BotListController {
return () => clearTimeout(timer)
}, [targetMachineId, bots.length])
+ useEffect(() => {
+ if (!botsResolved) return
+ if (!targetAuditBotId) {
+ suppressedAuditRef.current = null
+ if (activityOpen) setActivityOpen(false)
+ if (activityBot) setActivityBot(null)
+ return
+ }
+ if (suppressedAuditRef.current === targetAuditBotId) return
+
+ const targetBot = bots.find((bot) => bot.id === targetAuditBotId)
+ if (!targetBot) {
+ suppressedAuditRef.current = targetAuditBotId
+ if (activityOpen) setActivityOpen(false)
+ if (activityBot) setActivityBot(null)
+ const query = searchParams.toString()
+ router.replace(removeCommunityParam(`/c/me/bots${query ? `?${query}` : ""}`, "audit"))
+ return
+ }
+
+ if (activityBot?.id !== targetBot.id) setActivityBot(targetBot)
+ if (!activityOpen) setActivityOpen(true)
+ }, [activityBot, activityOpen, bots, botsResolved, router, searchParams, targetAuditBotId])
+
+ const openActivity = (bot: BotSummary) => {
+ suppressedAuditRef.current = null
+ const next = new URLSearchParams(searchParams.toString())
+ next.set("audit", bot.id)
+ router.push(`/c/me/bots?${next.toString()}`)
+ }
+
+ const onActivityOpenChange = (open: boolean) => {
+ if (open) return
+ if (targetAuditBotId) suppressedAuditRef.current = targetAuditBotId
+ setActivityOpen(false)
+ setActivityBot(null)
+ const query = searchParams.toString()
+ router.replace(removeCommunityParam(`/c/me/bots${query ? `?${query}` : ""}`, "audit"))
+ }
+
const openMachines = () => router.push("/c/me/machines")
const bringMachineOnline = (machineId: string) => {
router.push(`/c/me/machines?reconnect=${machineId}`)
@@ -220,9 +264,9 @@ export function useBotListController(): BotListController {
editOpen,
setEditOpen,
activityBot,
- setActivityBot,
activityOpen,
- setActivityOpen,
+ openActivity,
+ onActivityOpenChange,
bugReportBot,
setBugReportBot,
bugReportOpen,
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.test.ts b/src/web/src/components/community/bots/bot-list-machine-group.test.ts
index 6252a356d..bce270ca8 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.test.ts
+++ b/src/web/src/components/community/bots/bot-list-machine-group.test.ts
@@ -64,8 +64,8 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
collapsedMachines: new Set(),
setCollapsedMachines: noop,
setConfirmResetMachine: noop,
- setActivityBot: noop,
- setActivityOpen: noop,
+ openActivity: noop,
+ onActivityOpenChange: noop,
setEditingBot: noop,
setEditOpen: noop,
setConfirmReset: noop,
@@ -241,8 +241,7 @@ describe("renderBotMachineGroup", () => {
})
it("keeps menu order, testids, and selected-bot action projections", () => {
- const setActivityBot = vi.fn()
- const setActivityOpen = vi.fn()
+ const openActivity = vi.fn()
const setEditingBot = vi.fn()
const setEditOpen = vi.fn()
const setConfirmReset = vi.fn()
@@ -254,8 +253,7 @@ describe("renderBotMachineGroup", () => {
let renderer!: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(renderBotMachineGroup(group({ bots: [item] }), controller({
- setActivityBot,
- setActivityOpen,
+ openActivity,
setEditingBot,
setEditOpen,
setConfirmReset,
@@ -292,8 +290,7 @@ describe("renderBotMachineGroup", () => {
act(() => items[4]!.props.onClick())
act(() => items[5]!.props.onClick())
expect(chatWithBot).toHaveBeenCalledWith(item)
- expect(setActivityBot).toHaveBeenCalledWith(item)
- expect(setActivityOpen).toHaveBeenCalledWith(true)
+ expect(openActivity).toHaveBeenCalledWith(item)
expect(setEditingBot).toHaveBeenCalledWith(item)
expect(setEditOpen).toHaveBeenCalledWith(true)
expect(setConfirmReset).toHaveBeenCalledWith(item)
diff --git a/src/web/src/components/community/bots/bot-list-machine-group.tsx b/src/web/src/components/community/bots/bot-list-machine-group.tsx
index 8fd236649..749dca706 100644
--- a/src/web/src/components/community/bots/bot-list-machine-group.tsx
+++ b/src/web/src/components/community/bots/bot-list-machine-group.tsx
@@ -162,10 +162,7 @@ export function renderBotMachineGroup(
<span className="size-4" aria-hidden /> Chat
</DropdownMenuItem>
<DropdownMenuItem
- onClick={() => {
- controller.setActivityBot(bot)
- controller.setActivityOpen(true)
- }}
+ onClick={() => controller.openActivity(bot)}
>
<Activity className="size-4" /> View activity
</DropdownMenuItem>
diff --git a/src/web/src/components/community/bots/bot-list-overlays.test.ts b/src/web/src/components/community/bots/bot-list-overlays.test.ts
index a5fe95213..3eb80dd35 100644
--- a/src/web/src/components/community/bots/bot-list-overlays.test.ts
+++ b/src/web/src/components/community/bots/bot-list-overlays.test.ts
@@ -51,7 +51,8 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
setEditOpen: noop,
activityBot: null,
activityOpen: false,
- setActivityOpen: noop,
+ onActivityOpenChange: noop,
+ openActivity: noop,
bugReportBot: null,
bugReportOpen: false,
setBugReportOpen: noop,
@@ -111,7 +112,7 @@ describe("renderBotListOverlaySlots", () => {
it("keeps selected child props and the conditional keyed bug slot", () => {
const bot = { id: "b1", name: "Blake" }
const setEditOpen = vi.fn()
- const setActivityOpen = vi.fn()
+ const onActivityOpenChange = vi.fn()
const setBugReportOpen = vi.fn()
const state = controller({
createOpen: true,
@@ -123,7 +124,7 @@ describe("renderBotListOverlaySlots", () => {
setEditOpen,
activityBot: bot as BotListController["activityBot"],
activityOpen: true,
- setActivityOpen,
+ onActivityOpenChange,
bugReportBot: bot,
bugReportOpen: true,
setBugReportOpen,
@@ -137,7 +138,7 @@ describe("renderBotListOverlaySlots", () => {
avatarSeed: "seed",
})
expect(slots.edit.props).toEqual({ bot, open: true, onOpenChange: setEditOpen })
- expect(slots.activity.props).toEqual({ bot, open: true, onOpenChange: setActivityOpen })
+ expect(slots.activity.props).toEqual({ bot, open: true, onOpenChange: onActivityOpenChange })
expect(slots.help.props).toEqual({
open: true,
onOpenChange: state.setHelpOpen,
@@ -149,7 +150,7 @@ describe("renderBotListOverlaySlots", () => {
act(() => slots.activity.props.onOpenChange(false))
act(() => slots.bug?.props.onOpenChange(false))
expect(setEditOpen).toHaveBeenCalledWith(false)
- expect(setActivityOpen).toHaveBeenCalledWith(false)
+ expect(onActivityOpenChange).toHaveBeenCalledWith(false)
expect(setBugReportOpen).toHaveBeenCalledWith(false)
expect(state.editingBot).toBe(bot)
expect(state.activityBot).toBe(bot)
diff --git a/src/web/src/components/community/bots/bot-list-overlays.tsx b/src/web/src/components/community/bots/bot-list-overlays.tsx
index 12cc3e898..0d9480565 100644
--- a/src/web/src/components/community/bots/bot-list-overlays.tsx
+++ b/src/web/src/components/community/bots/bot-list-overlays.tsx
@@ -42,7 +42,7 @@ export function renderBotListOverlaySlots(
<BotActivityModal
bot={controller.activityBot}
open={controller.activityOpen}
- onOpenChange={controller.setActivityOpen}
+ onOpenChange={controller.onActivityOpenChange}
/>
),
bug: controller.bugReportBot ? (
diff --git a/src/web/src/components/community/bots/bot-list-types.ts b/src/web/src/components/community/bots/bot-list-types.ts
index 4dc490a83..65c2681a4 100644
--- a/src/web/src/components/community/bots/bot-list-types.ts
+++ b/src/web/src/components/community/bots/bot-list-types.ts
@@ -25,9 +25,9 @@ export type BotListController = {
editOpen: boolean
setEditOpen: Dispatch<SetStateAction<boolean>>
activityBot: BotSummary | null
- setActivityBot: Dispatch<SetStateAction<BotSummary | null>>
activityOpen: boolean
- setActivityOpen: Dispatch<SetStateAction<boolean>>
+ openActivity: (bot: BotSummary) => void
+ onActivityOpenChange: (open: boolean) => void
bugReportBot: Pick<BotSummary, "id" | "name"> | null
setBugReportBot: Dispatch<SetStateAction<Pick<BotSummary, "id" | "name"> | null>>
bugReportOpen: boolean
diff --git a/src/web/src/components/community/bots/bot-list-view.test.ts b/src/web/src/components/community/bots/bot-list-view.test.ts
index 9d98d5eaa..915047469 100644
--- a/src/web/src/components/community/bots/bot-list-view.test.ts
+++ b/src/web/src/components/community/bots/bot-list-view.test.ts
@@ -57,9 +57,9 @@ function controller(overrides: Partial<BotListController> = {}): BotListControll
editOpen: false,
setEditOpen: noop,
activityBot: null,
- setActivityBot: noop,
activityOpen: false,
- setActivityOpen: noop,
+ openActivity: noop,
+ onActivityOpenChange: noop,
bugReportBot: null,
setBugReportBot: noop,
bugReportOpen: false,
diff --git a/src/web/src/components/community/shell/shell-frame-overlays.test.ts b/src/web/src/components/community/shell/shell-frame-overlays.test.ts
index e36505f9c..8d2a3a41c 100644
--- a/src/web/src/components/community/shell/shell-frame-overlays.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-overlays.test.ts
@@ -36,6 +36,8 @@ const controller = {
closeProfile: vi.fn(),
profileMessage: vi.fn(),
updateOwnStatus: vi.fn(),
+ openOwnerProfile: vi.fn(),
+ openBotAudit: vi.fn(),
preview: { url: "/image.png", alt: "image" },
closePreview: vi.fn(),
attachmentPreview: { id: "a1", filename: "notes.txt" },
@@ -92,6 +94,10 @@ describe("ShellFrameOverlays", () => {
const profileCard = renderer.root.findByType("profile-card")
expect(profileCard.props.initialStatusEmoji).toBe("🌱")
expect(profileCard.props.initialStatusText).toBe("Growing")
+ expect(profileCard.props.activityStatusEmoji).toBe("🌱")
+ expect(profileCard.props.activityStatusText).toBe("Growing")
+ expect(profileCard.props.onOpenOwnerProfile).toBe(controller.openOwnerProfile)
+ expect(profileCard.props.onOpenBotAudit).toBe(controller.openBotAudit)
expect(renderer.root.findByType("crop-dialog").props.maskShape).toBe("circle")
renderer.root.findByType("attachment-sheet").props.onOpenChange(false)
@@ -113,6 +119,8 @@ describe("ShellFrameOverlays", () => {
const profileCard = renderer.root.findByType("profile-card")
expect("initialStatusEmoji" in profileCard.props).toBe(false)
expect("initialStatusText" in profileCard.props).toBe(false)
+ expect(profileCard.props.activityStatusEmoji).toBe("🌱")
+ expect(profileCard.props.activityStatusText).toBe("Growing")
})
it("omits nullable overlays while keeping closed sheet and settings wiring", async () => {
diff --git a/src/web/src/components/community/shell/shell-frame-overlays.tsx b/src/web/src/components/community/shell/shell-frame-overlays.tsx
index 8d494b6d6..dbd3cd741 100644
--- a/src/web/src/components/community/shell/shell-frame-overlays.tsx
+++ b/src/web/src/components/community/shell/shell-frame-overlays.tsx
@@ -41,6 +41,10 @@ export function ShellFrameOverlays({
onMessage={controller.profileMessage}
isSelf={!!profile.data.userId && profile.data.userId === currentUser.id}
onUpdateStatus={controller.updateOwnStatus}
+ onOpenOwnerProfile={controller.openOwnerProfile}
+ onOpenBotAudit={controller.openBotAudit}
+ activityStatusEmoji={profile.initialStatusEmoji}
+ activityStatusText={profile.initialStatusText}
{...profileStatusSeeds}
/>
)}
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts
index 49fe67478..38f4abb49 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts
@@ -84,6 +84,7 @@ vi.mock("@/components/community/social/profile-lookup", () => ({
about: "About",
mutual: 0,
presence: "online",
+ identity: { kind: "human" },
}),
}))
vi.mock("@/lib/community/presence", () => ({ resolveProfilePresence: () => "online" }))
@@ -176,11 +177,13 @@ describe("useShellProfileController", () => {
it("opens a remote seed before fetch and hydrates only card state", async () => {
const response = deferred<{
+ id: string
aboutMe: string
mutualServers: number
discriminator: string
statusEmoji: string | null
statusText: string | null
+ kind: "human"
}>()
mocks.fetchQuery.mockReturnValue(response.promise)
const hook = await renderController()
@@ -191,11 +194,13 @@ describe("useShellProfileController", () => {
}))
await act(async () => response.resolve({
+ id: "remote",
aboutMe: "hydrated",
mutualServers: 3,
discriminator: "1234",
statusEmoji: "🌱",
statusText: "Growing",
+ kind: "human",
}))
expect(hook.current.profile?.data).toMatchObject({
about: "hydrated",
@@ -206,6 +211,100 @@ describe("useShellProfileController", () => {
expect(mocks.setUserStatus).not.toHaveBeenCalled()
})
+ it("does not let a slow profile response overwrite the next opened card", async () => {
+ const first = deferred<Record<string, unknown>>()
+ const second = deferred<Record<string, unknown>>()
+ mocks.fetchQuery
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise)
+ const hook = await renderController()
+
+ await act(async () => hook.current.openProfile(
+ "Remote",
+ { clientX: 4, clientY: 5 } as never,
+ undefined,
+ "remote",
+ ))
+ await act(async () => hook.current.openProfile(
+ "Next",
+ { clientX: 8, clientY: 9 } as never,
+ undefined,
+ "next",
+ ))
+ await act(async () => second.resolve({
+ id: "next",
+ aboutMe: "next hydrated",
+ mutualServers: 1,
+ discriminator: "9001",
+ statusEmoji: null,
+ statusText: "",
+ kind: "human",
+ }))
+ await act(async () => first.resolve({
+ id: "remote",
+ aboutMe: "stale response",
+ mutualServers: 9,
+ discriminator: "0001",
+ statusEmoji: "❌",
+ statusText: "stale",
+ kind: "human",
+ }))
+
+ expect(hook.current.profile?.data).toMatchObject({
+ userId: "next",
+ name: "Next",
+ about: "next hydrated",
+ discriminator: "9001",
+ })
+ })
+
+ it("hydrates bot ownership, swaps to the exact owner, and routes audit preview", async () => {
+ mocks.fetchQuery.mockResolvedValueOnce({
+ id: "remote",
+ aboutMe: "bot",
+ mutualServers: 0,
+ discriminator: "1234",
+ statusEmoji: null,
+ statusText: "",
+ kind: "bot",
+ ownerProfile: { id: "owner", handle: "Owner#0042" },
+ ownedByViewer: true,
+ }).mockResolvedValueOnce({
+ id: "owner",
+ aboutMe: "owner",
+ mutualServers: 0,
+ discriminator: "0042",
+ statusEmoji: null,
+ statusText: "",
+ kind: "human",
+ })
+ const hook = await renderController()
+
+ await act(async () => hook.current.openProfile(
+ "Remote",
+ { clientX: 4, clientY: 5 } as never,
+ undefined,
+ "remote",
+ ))
+ expect(hook.current.profile?.data.identity).toEqual({
+ kind: "bot",
+ ownerProfile: { id: "owner", handle: "Owner#0042" },
+ ownedByViewer: true,
+ })
+
+ await act(async () => hook.current.openOwnerProfile({ id: "owner", handle: "Owner#0042" }))
+ expect(hook.current.profile).toMatchObject({
+ x: 4,
+ y: 5,
+ data: { userId: "owner", name: "Owner", discriminator: "0042" },
+ })
+
+ act(() => hook.current.openBotAudit("remote"))
+ expect(hook.cancelPendingNavigation).toHaveBeenCalledOnce()
+ expect(hook.pushed).toContain("/c/me/bots?audit=remote")
+ expect(hook.current.profile).toBeNull()
+ })
+
it("opens empty-text DMs, does not await accepted commits, and blocks rejected sends", async () => {
mocks.createDm.mockResolvedValue({ conversation: { id: "dm1" } })
const hook = await renderController()
diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.ts
index c8fa273e3..5357d5144 100644
--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts
@@ -1,13 +1,17 @@
"use client"
import { useCallback, useState, type ComponentProps } from "react"
+import { parseNameAndTag } from "@alook/shared"
import { toast } from "sonner"
import { toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { userProfileQueryFn, PROFILE_STALE_TIME_MS } from "@/hooks/community/use-user-profile"
import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"
-import type { Profile } from "@/components/community/social/profile-types"
+import type {
+ OwnerProfileRef,
+ Profile,
+} from "@/components/community/social/profile-types"
import {
resolveProfileContextLabel,
resolveProfileServerId,
@@ -79,9 +83,10 @@ export function useShellProfileController({
fileName: string
} | null>(null)
- const openProfile = useCallback((
+ const openProfileAt = useCallback((
name: string,
- event: React.MouseEvent,
+ x: number,
+ y: number,
discriminator?: string,
targetUserId?: string,
) => {
@@ -96,8 +101,8 @@ export function useShellProfileController({
onlineUserIds,
resolveProfileContextLabel(profileServerId, selfMember),
),
- x: event.clientX,
- y: event.clientY,
+ x,
+ y,
initialStatusEmoji: currentUser.statusEmoji ?? null,
initialStatusText: currentUser.statusText ?? null,
})
@@ -121,8 +126,8 @@ export function useShellProfileController({
mutual: 0,
presence: resolveProfilePresence(false, userId, onlineUserIds),
},
- x: event.clientX,
- y: event.clientY,
+ x,
+ y,
initialStatusEmoji: member?.statusEmoji ?? null,
initialStatusText: member?.statusText ?? null,
})
@@ -135,7 +140,7 @@ export function useShellProfileController({
})
.then((profileResponse) => {
setProfile((previous) =>
- previous
+ previous?.data.userId === profileResponse.id
? {
...previous,
data: {
@@ -143,6 +148,13 @@ export function useShellProfileController({
about: profileResponse.aboutMe ?? previous.data.about,
mutual: profileResponse.mutualServers ?? 0,
discriminator: profileResponse.discriminator ?? previous.data.discriminator,
+ identity: profileResponse.kind === "bot"
+ ? {
+ kind: "bot",
+ ownerProfile: profileResponse.ownerProfile,
+ ownedByViewer: profileResponse.ownedByViewer,
+ }
+ : { kind: "human" },
},
initialStatusEmoji: profileResponse.statusEmoji,
initialStatusText: profileResponse.statusText,
@@ -154,6 +166,34 @@ export function useShellProfileController({
}
}, [currentUser, friends, members, onlineUserIds, profileServerId, queryClient])
+ const openProfile = useCallback((
+ name: string,
+ event: React.MouseEvent,
+ discriminator?: string,
+ targetUserId?: string,
+ ) => {
+ openProfileAt(name, event.clientX, event.clientY, discriminator, targetUserId)
+ }, [openProfileAt])
+
+ const openOwnerProfile = useCallback((owner: OwnerProfileRef) => {
+ if (!profile) return
+ const parsed = parseNameAndTag(owner.handle)
+ if (!parsed) return
+ openProfileAt(
+ parsed.name,
+ profile.x,
+ profile.y,
+ parsed.discriminator,
+ owner.id,
+ )
+ }, [openProfileAt, profile])
+
+ const openBotAudit = useCallback((botId: string) => {
+ cancelPendingNavigation()
+ router.push(`/c/me/bots?audit=${encodeURIComponent(botId)}`)
+ setProfile(null)
+ }, [cancelPendingNavigation, router])
+
const previewImage = useCallback((image: ImagePreview) => setPreview(image), [])
const previewAttachment = useCallback(
(attachment: FileAttachment) => setAttachmentPreview(attachment),
@@ -302,6 +342,8 @@ export function useShellProfileController({
return {
currentUser,
openProfile,
+ openOwnerProfile,
+ openBotAudit,
previewImage,
previewAttachment,
profile,
diff --git a/src/web/src/components/community/social/bot-audit-preview.test.ts b/src/web/src/components/community/social/bot-audit-preview.test.ts
new file mode 100644
index 000000000..cf769e7ac
--- /dev/null
+++ b/src/web/src/components/community/social/bot-audit-preview.test.ts
@@ -0,0 +1,255 @@
+import { readFileSync } from "node:fs"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ result: {
+ events: [] as Array<Record<string, unknown>>,
+ isLoading: false,
+ isError: false,
+ isNotFound: false,
+ },
+}))
+
+vi.mock("@/hooks/community/use-bot-audit-preview", () => ({
+ useBotAuditPreview: () => mocks.result,
+}))
+vi.mock("lucide-react", () => ({
+ Activity: "activity-icon",
+ ChevronRight: "chevron-icon",
+ Lock: "lock-icon",
+}))
+
+import { BotAuditPreview, isBotActivityActive } from "./bot-audit-preview"
+
+const globalCss = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")
+
+const event = (id: string, kind: "tool_call" | "cli_invocation" = "tool_call") => ({
+ id,
+ kind,
+ payload: kind === "tool_call"
+ ? { name: `Tool ${id.slice(1)}`, target: `/private/${id}` }
+ : { subcommand: "inboxPull" },
+ sessionId: null,
+ launchId: null,
+ createdAt: `2026-01-01T00:00:0${id.slice(1)}.000Z`,
+})
+
+describe("BotAuditPreview", () => {
+ beforeEach(() => {
+ mocks.result = {
+ events: [],
+ isLoading: false,
+ isError: false,
+ isNotFound: false,
+ }
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it("uses exact system status pairs for active state", () => {
+ expect(isBotActivityActive("πŸŒ€", "Waking up")).toBe(true)
+ expect(isBotActivityActive("⚑", "Working on it")).toBe(true)
+ expect(isBotActivityActive("πŸŒ™", "Wrapping up")).toBe(true)
+ expect(isBotActivityActive("πŸ’€", "Idle")).toBe(false)
+ expect(isBotActivityActive("⚑", "Custom status")).toBe(false)
+ })
+
+ it("defines an opacity-only double-beat with a static reduced-motion ring", () => {
+ expect(globalCss).toContain(".bot-audit-active-heartbeat::before")
+ expect(globalCss).toContain("animation: bot-audit-heartbeat 2s ease-in-out infinite")
+ expect(globalCss).toMatch(/8%\s*\{\s*opacity: 0\.9;/)
+ expect(globalCss).toMatch(/26%\s*\{\s*opacity: 0\.62;/)
+ expect(globalCss).toMatch(/36%,\s*100%\s*\{\s*opacity: 0\.28;/)
+ expect(globalCss).toMatch(
+ /@media \(prefers-reduced-motion: reduce\)[\s\S]*animation: none;[\s\S]*opacity: 0\.55;/,
+ )
+ })
+
+ it("keeps one keyboard target, a synthetic active row, and four persisted rows", () => {
+ mocks.result.events = ["e5", "e4", "e3", "e2", "e1"].map((id) => event(id))
+ const onOpen = vi.fn()
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BotAuditPreview, { botId: "b1", active: true, onOpen }),
+ )
+ })
+
+ const button = renderer.root.findByProps({
+ "data-testid": "community-bot-audit-preview",
+ })
+ expect(button.type).toBe("button")
+ expect(button.props["data-active"]).toBe(true)
+ expect(button.props["aria-label"]).toBe(
+ "Bot activity in progress. Open full bot activity log",
+ )
+ expect(button.props.className).toContain("duration-150")
+ expect(button.props.className).not.toContain("hover:bg-accent")
+ expect(button.props.className).toContain("hover:after:opacity-100")
+ expect(button.props.className).toContain("after:ring-inset")
+ expect(button.props.className).toContain("bot-audit-active-heartbeat")
+ expect(button.props.className).toContain("before:ring-primary/60")
+ expect(button.props.className).toContain("before:z-20")
+ expect(button.props.className).toContain("after:z-10")
+ expect(button.findAll((node) => node.children.includes("Only you can see this")))
+ .toHaveLength(1)
+ expect(button.findAllByType("lock-icon")).toHaveLength(1)
+ expect(renderer.root.findAllByProps({
+ "data-testid": "community-bot-audit-preview-active",
+ })).toHaveLength(1)
+ expect(renderer.root.findAll((node) =>
+ typeof node.props["data-testid"] === "string"
+ && node.props["data-testid"].startsWith("community-bot-audit-preview-row-")))
+ .toHaveLength(4)
+ expect(renderer.root.findAllByType("button")).toHaveLength(1)
+ const rows = renderer.root.findAll((node) =>
+ typeof node.props["data-testid"] === "string"
+ && node.props["data-testid"].startsWith("community-bot-audit-preview-row-"))
+ expect(rows.map((row) => row.props["data-testid"])).toEqual([
+ "community-bot-audit-preview-row-e2",
+ "community-bot-audit-preview-row-e3",
+ "community-bot-audit-preview-row-e4",
+ "community-bot-audit-preview-row-e5",
+ ])
+ const activeRow = renderer.root.findByProps({
+ "data-testid": "community-bot-audit-preview-active",
+ })
+ expect(activeRow.props.className).toContain("motion-safe:duration-200")
+ expect(activeRow.findAll((node) => node.children.includes("running"))).not.toHaveLength(0)
+ const activeTime = activeRow.findByType("time")
+ expect(activeTime.props.dateTime).toBeTypeOf("string")
+ expect(Math.abs(Date.now() - Date.parse(activeTime.props.dateTime))).toBeLessThan(5_000)
+ expect(activeTime.children).not.toContain("running")
+ expect(activeRow.findAll((node) => node.props.className?.includes("rounded-full")))
+ .toHaveLength(3)
+ expect(activeRow.findAll((node) => node.props.className?.includes("bg-linear-to-r")))
+ .toHaveLength(0)
+ const timelineRows = renderer.root.findAll((node) => {
+ const testid = node.props["data-testid"]
+ return testid === "community-bot-audit-preview-active"
+ || (typeof testid === "string" && testid.startsWith("community-bot-audit-preview-row-"))
+ })
+ expect(timelineRows.at(-1)?.props["data-testid"]).toBe(
+ "community-bot-audit-preview-active",
+ )
+ act(() => button.props.onClick())
+ expect(onOpen).toHaveBeenCalledOnce()
+ act(() => renderer.unmount())
+ })
+
+ it("keeps the running time current and never earlier than the latest event", () => {
+ vi.useFakeTimers()
+ vi.setSystemTime("2026-01-01T00:00:30.000Z")
+ mocks.result.events = [{
+ ...event("e1"),
+ createdAt: "2026-01-01T00:00:05.000Z",
+ }]
+ const props = { botId: "b1", active: true, onOpen: vi.fn() }
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(BotAuditPreview, props))
+ })
+
+ const activeTime = () => renderer.root.findByProps({
+ "data-testid": "community-bot-audit-preview-active",
+ }).findByType("time")
+ expect(activeTime().props.dateTime).toBe("2026-01-01T00:00:30.000Z")
+
+ act(() => {
+ vi.advanceTimersByTime(30_000)
+ })
+ expect(activeTime().props.dateTime).toBe("2026-01-01T00:01:00.000Z")
+
+ mocks.result.events = [{
+ ...event("e2"),
+ createdAt: "2026-01-01T00:05:00.000Z",
+ }]
+ act(() => {
+ renderer.update(React.createElement(BotAuditPreview, props))
+ })
+ expect(activeTime().props.dateTime).toBe("2026-01-01T00:05:00.000Z")
+
+ act(() => renderer.unmount())
+ })
+
+ it("renders five static rows while idle and disappears on authoritative 404", () => {
+ mocks.result.events = ["e5", "e4", "e3", "e2", "e1"].map((id) => event(id))
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BotAuditPreview, { botId: "b1", active: false, onOpen: vi.fn() }),
+ )
+ })
+ expect(renderer.root.findAll((node) =>
+ typeof node.props["data-testid"] === "string"
+ && node.props["data-testid"].startsWith("community-bot-audit-preview-row-")))
+ .toHaveLength(5)
+ const button = renderer.root.findByProps({
+ "data-testid": "community-bot-audit-preview",
+ })
+ expect(button.props["aria-label"]).toBe(
+ "Bot at rest. Open full bot activity log",
+ )
+ expect(button.props.className).toContain("hover:after:opacity-100")
+ expect(button.props.className).not.toContain("bot-audit-active-heartbeat")
+ expect(button.props.className).not.toContain("before:ring-primary/60")
+
+ mocks.result.isNotFound = true
+ act(() => renderer.update(
+ React.createElement(BotAuditPreview, { botId: "b1", active: false, onOpen: vi.fn() }),
+ ))
+ expect(renderer.toJSON()).toBeNull()
+ })
+
+ it("shows concrete command and tool names without tool parameters", () => {
+ mocks.result.events = [
+ event("e2", "tool_call"),
+ event("e1", "cli_invocation"),
+ ]
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BotAuditPreview, { botId: "b1", active: false, onOpen: vi.fn() }),
+ )
+ })
+ const text = renderer.root.findAllByType("span")
+ .flatMap((node) => node.children)
+ .filter((child): child is string => typeof child === "string")
+ .join(" ")
+ expect(text).toContain("alook inbox pull")
+ expect(text).toContain("tool 2")
+ expect(text).not.toContain("/private/")
+ })
+
+ it("keeps the active row visible while persisted rows load or fail", () => {
+ mocks.result.isLoading = true
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BotAuditPreview, { botId: "b1", active: true, onOpen: vi.fn() }),
+ )
+ })
+ expect(renderer.root.findAllByProps({
+ "data-testid": "community-bot-audit-preview-active",
+ })).toHaveLength(1)
+ expect(renderer.root.findAllByProps({
+ "aria-label": "Loading recent activity",
+ })).toHaveLength(1)
+
+ mocks.result.isLoading = false
+ mocks.result.isError = true
+ act(() => renderer.update(
+ React.createElement(BotAuditPreview, { botId: "b1", active: true, onOpen: vi.fn() }),
+ ))
+ expect(renderer.root.findAllByProps({
+ "data-testid": "community-bot-audit-preview-active",
+ })).toHaveLength(1)
+ expect(renderer.root.findAll((node) => node.children.includes("Activity unavailable")))
+ .not.toHaveLength(0)
+ act(() => renderer.unmount())
+ })
+})
diff --git a/src/web/src/components/community/social/bot-audit-preview.tsx b/src/web/src/components/community/social/bot-audit-preview.tsx
new file mode 100644
index 000000000..aeffdf47a
--- /dev/null
+++ b/src/web/src/components/community/social/bot-audit-preview.tsx
@@ -0,0 +1,184 @@
+"use client"
+
+/* Hallmark Β· pre-emit critique: P5 H5 E5 S5 R5 V4 */
+
+import {
+ BOT_ACTIVITY_PRESETS,
+ RUNNING_PRESETS,
+} from "@alook/shared"
+import { Activity, ChevronRight, Lock } from "lucide-react"
+import { useEffect, useState } from "react"
+import { useBotAuditPreview } from "@/hooks/community/use-bot-audit-preview"
+import {
+ formatAuditPreviewTime,
+ summarizeAuditEvent,
+} from "@/lib/community/audit-event-summary"
+import { tid } from "@/lib/community/testids"
+
+type StatusPair = { emoji: string; text: string }
+
+function matchesStatus(
+ emoji: string | null | undefined,
+ text: string | null | undefined,
+ pair: StatusPair,
+): boolean {
+ return emoji === pair.emoji && text === pair.text
+}
+
+export function isBotActivityActive(
+ emoji: string | null | undefined,
+ text: string | null | undefined,
+): boolean {
+ return matchesStatus(emoji, text, BOT_ACTIVITY_PRESETS.starting)
+ || matchesStatus(emoji, text, BOT_ACTIVITY_PRESETS.stopping)
+ || RUNNING_PRESETS.some((pair) => matchesStatus(emoji, text, pair))
+}
+
+export function BotAuditPreview({
+ botId,
+ active,
+ onOpen,
+}: {
+ botId: string
+ active: boolean
+ onOpen: () => void
+}) {
+ const { events, isLoading, isError, isNotFound } = useBotAuditPreview(botId)
+
+ if (isNotFound) return null
+
+ const visibleEvents = [...events]
+ .sort((a, b) => {
+ if (a.createdAt !== b.createdAt) return a.createdAt > b.createdAt ? -1 : 1
+ return a.id > b.id ? -1 : a.id < b.id ? 1 : 0
+ })
+ .slice(0, active ? 4 : 5)
+ .reverse()
+
+ return (
+ <button
+ type="button"
+ data-testid={tid.botAuditPreview}
+ data-active={active || undefined}
+ onClick={onOpen}
+ aria-label={active
+ ? "Bot activity in progress. Open full bot activity log"
+ : "Bot at rest. Open full bot activity log"}
+ className={[
+ "relative flex h-40 w-full shrink-0 flex-col overflow-hidden rounded-xl border bg-card text-left shadow-(--e1) transition-[border-color] duration-150",
+ "after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-[inherit] after:opacity-0 after:ring-2 after:ring-inset after:ring-ring/50 after:transition-opacity after:duration-150 after:content-[''] hover:after:opacity-100 active:after:ring-ring/70",
+ "focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
+ active
+ ? "bot-audit-active-heartbeat border-primary/35 before:pointer-events-none before:absolute before:inset-0 before:z-20 before:rounded-[inherit] before:ring-2 before:ring-inset before:ring-primary/60 before:content-['']"
+ : "border-border",
+ ].join(" ")}
+ >
+ <div className="flex h-9 shrink-0 items-center gap-2 border-b border-border/40 px-3">
+ <Activity className="size-3.5 text-muted-foreground" aria-hidden />
+ <span className="shrink-0 text-xs font-medium text-foreground">Recent activity</span>
+ <span className="ml-auto flex shrink-0 items-center gap-1 whitespace-nowrap text-[10px] text-muted-foreground">
+ <Lock className="size-3" aria-hidden />
+ Only you can see this
+ </span>
+ <ChevronRight className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto py-1 thin-scrollbar">
+ {isLoading ? (
+ <PreviewSkeleton />
+ ) : isError ? (
+ <PreviewStateRow label="Activity unavailable" />
+ ) : visibleEvents.length > 0 ? (
+ visibleEvents.map((event) => (
+ <div
+ key={event.id}
+ data-testid={tid.botAuditPreviewRow(event.id)}
+ className="grid h-6 grid-cols-[3.25rem_minmax(0,1fr)] items-center gap-2 px-3 text-xs"
+ >
+ <time
+ dateTime={event.createdAt}
+ className="font-mono text-[10px] tabular-nums text-muted-foreground/70"
+ >
+ {formatAuditPreviewTime(event.createdAt)}
+ </time>
+ <span className="truncate text-muted-foreground">
+ {summarizeAuditEvent(event)}
+ </span>
+ </div>
+ ))
+ ) : (
+ <PreviewStateRow label="No recent activity" />
+ )}
+ {active && <ActiveRow latestEventAt={visibleEvents.at(-1)?.createdAt} />}
+ </div>
+ </button>
+ )
+}
+
+function ActiveRow({ latestEventAt }: { latestEventAt?: string }) {
+ const [nowMs, setNowMs] = useState(Date.now)
+
+ useEffect(() => {
+ let timer: ReturnType<typeof globalThis.setTimeout>
+ const scheduleNextMinute = () => {
+ const delay = 60_000 - (Date.now() % 60_000)
+ timer = globalThis.setTimeout(() => {
+ setNowMs(Date.now())
+ scheduleNextMinute()
+ }, delay)
+ }
+ scheduleNextMinute()
+ return () => globalThis.clearTimeout(timer)
+ }, [])
+
+ const latestEventMs = latestEventAt ? Date.parse(latestEventAt) : Number.NaN
+ const displayedAt = new Date(
+ Number.isFinite(latestEventMs) ? Math.max(nowMs, latestEventMs) : nowMs,
+ ).toISOString()
+
+ return (
+ <div
+ data-testid={tid.botAuditPreviewActive}
+ className="grid h-6 shrink-0 grid-cols-[3.25rem_minmax(0,1fr)] items-center gap-2 px-3 motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 motion-safe:duration-200 motion-reduce:animate-none"
+ >
+ <time
+ dateTime={displayedAt}
+ suppressHydrationWarning
+ className="font-mono text-[10px] tabular-nums text-muted-foreground/70"
+ >
+ {formatAuditPreviewTime(displayedAt)}
+ </time>
+ <span className="flex items-center gap-1" aria-label="Bot activity in progress">
+ <span className="mr-1 text-xs text-primary/70">running</span>
+ {[0, 1, 2].map((index) => (
+ <span
+ key={index}
+ aria-hidden
+ className="size-1.5 rounded-full bg-primary motion-safe:animate-pulse motion-reduce:animate-none"
+ style={{ animationDelay: `${index * 160}ms` }}
+ />
+ ))}
+ </span>
+ </div>
+ )
+}
+
+function PreviewSkeleton() {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-1 px-3 py-1" aria-label="Loading recent activity">
+ {[0, 1, 2, 3].map((index) => (
+ <div key={index} className="flex h-5 items-center gap-2">
+ <span className="h-2 w-10 animate-pulse rounded bg-muted motion-reduce:animate-none" />
+ <span className="h-2 flex-1 animate-pulse rounded bg-muted motion-reduce:animate-none" />
+ </div>
+ ))}
+ </div>
+ )
+}
+
+function PreviewStateRow({ label }: { label: string }) {
+ return (
+ <div className="flex min-h-0 flex-1 items-center justify-center px-4 text-xs text-muted-foreground">
+ {label}
+ </div>
+ )
+}
diff --git a/src/web/src/components/community/social/profile-card.test.ts b/src/web/src/components/community/social/profile-card.test.ts
index c35b915e3..a69fbf9a3 100644
--- a/src/web/src/components/community/social/profile-card.test.ts
+++ b/src/web/src/components/community/social/profile-card.test.ts
@@ -1,27 +1,41 @@
import { createElement } from "react"
import { renderToStaticMarkup } from "react-dom/server"
+import { readFileSync } from "node:fs"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { describe, it, expect } from "vitest"
-import { resolveCardStatus, resolveProfileBackdropSeed } from "./profile-card"
+import {
+ displayOwnerHandle,
+ resolveAuditPreviewPlacement,
+ resolveCardStatus,
+ resolveProfileBackdropSeed,
+} from "./profile-card"
import { ProfileCard } from "./profile-card"
import { serializeBeamSeed } from "@/lib/avatar/seed-url"
import type { Profile } from "@/components/community/social/profile-types"
function renderProfile(overrides: Partial<Profile> = {}) {
- return renderToStaticMarkup(createElement(ProfileCard, {
- embedded: true,
- data: {
- name: "Ren",
- userId: "user_1",
- avatar: "R",
- about: "",
- mutual: 0,
- ...overrides,
- },
- x: 0,
- y: 0,
- bp: "desktop",
- onClose: () => undefined,
- }))
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ return renderToStaticMarkup(createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(ProfileCard, {
+ embedded: true,
+ data: {
+ name: "Ren",
+ userId: "user_1",
+ avatar: "R",
+ about: "",
+ mutual: 0,
+ ...overrides,
+ },
+ x: 0,
+ y: 0,
+ bp: "desktop",
+ onClose: () => undefined,
+ }),
+ ))
}
describe("ProfileCard contextual metadata", () => {
@@ -45,6 +59,118 @@ describe("ProfileCard contextual metadata", () => {
expect(html).not.toContain("community-profile-context-badge")
expect(html).toContain("2 mutual servers")
})
+
+ it("shows every bot's clickable owner but withholds preview from nonowners", () => {
+ const html = renderProfile({
+ identity: {
+ kind: "bot",
+ ownerProfile: { id: "owner_1", handle: "Owner#0042" },
+ ownedByViewer: false,
+ },
+ })
+
+ expect(html).toContain('data-testid="community-profile-bot-badge"')
+ expect(html).toContain(">Bot</span>")
+ expect(html).toContain('data-testid="community-profile-owner-link"')
+ expect(html).toContain(">@Owner</span>")
+ expect(html).not.toContain(">@Owner#0042</span>")
+ expect(html).toContain('aria-label="Open owner profile @Owner#0042"')
+ expect(html).not.toContain("community-bot-audit-preview")
+ })
+
+ it("mounts the fixed secondary preview only for the owning viewer", () => {
+ const html = renderProfile({
+ identity: {
+ kind: "bot",
+ ownerProfile: { id: "owner_1", handle: "Owner#0042" },
+ ownedByViewer: true,
+ },
+ })
+
+ expect(html).toContain('data-testid="community-bot-audit-preview"')
+ expect(html).toContain("h-40")
+ })
+
+ it("wraps owner metadata and exposes a full accessible label while truncating long handles", () => {
+ const handle = `${"VeryLongOwner".repeat(4)}#0042`
+ const html = renderProfile({
+ identity: {
+ kind: "bot",
+ ownerProfile: { id: "owner_1", handle },
+ ownedByViewer: false,
+ },
+ })
+
+ expect(html).toContain("flex min-w-0 flex-wrap items-center")
+ expect(html).toContain("group/owner flex h-11 min-w-0 max-w-full")
+ expect(html).toContain("sm:h-5")
+ expect(html).toContain("group-hover/owner:bg-accent")
+ expect(html).toContain("group-active/owner:bg-accent/80")
+ expect(html).toContain('<span class="min-w-0 truncate">')
+ expect(html).toContain(`>@${displayOwnerHandle(handle)}</span>`)
+ expect(html).not.toContain(`>@${handle}</span>`)
+ expect(html).toContain(`aria-label="Open owner profile @${handle}"`)
+ })
+
+ it("keeps the desktop main card at the anchor and independently docks the preview", () => {
+ const source = readFileSync(new URL("./profile-card.tsx", import.meta.url), "utf8")
+ const desktop = source.slice(source.indexOf("// desktop:"))
+ const mainCard = desktop.indexOf(`data-testid={tid.profileCard}`)
+ const independentPreview = desktop.indexOf(`data-testid={tid.botAuditPreviewDock}`)
+
+ expect(desktop).toContain(
+ `className="relative w-75 overflow-visible border-0 bg-transparent p-0 shadow-none"`,
+ )
+ expect(mainCard).toBeGreaterThan(0)
+ expect(independentPreview).toBeGreaterThan(0)
+ expect(independentPreview).toBeLessThan(mainCard)
+ expect(desktop).toContain("ref={popoverRef}")
+ expect(source).toContain('addEventListener("animationend", update)')
+ expect(source).toContain("cardElement.offsetWidth")
+ expect(source).toContain("previewElement.offsetWidth")
+ })
+})
+
+describe("resolveAuditPreviewPlacement", () => {
+ const card = {
+ top: 300,
+ right: 700,
+ bottom: 600,
+ left: 400,
+ width: 300,
+ height: 300,
+ }
+ const preview = { width: 300, height: 160 }
+
+ it("prefers the right side whenever it fits", () => {
+ expect(resolveAuditPreviewPlacement({
+ card,
+ preview,
+ viewportWidth: 1200,
+ viewportHeight: 900,
+ })).toBe("right")
+ })
+
+ it("falls back left, then above, then below according to available space", () => {
+ expect(resolveAuditPreviewPlacement({
+ card: { ...card, left: 500, right: 800 },
+ preview,
+ viewportWidth: 900,
+ viewportHeight: 900,
+ })).toBe("left")
+ expect(resolveAuditPreviewPlacement({
+ card: { ...card, left: 20, right: 320 },
+ preview,
+ viewportWidth: 620,
+ viewportHeight: 900,
+ })).toBe("top")
+ expect(resolveAuditPreviewPlacement({
+ card: { ...card, top: 40, bottom: 340, left: 20, right: 320 },
+ preview,
+ viewportWidth: 620,
+ viewportHeight: 900,
+ })).toBe("bottom")
+ })
})
describe("resolveProfileBackdropSeed", () => {
diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsx
index 19febf911..5e8104dcb 100644
--- a/src/web/src/components/community/social/profile-card.tsx
+++ b/src/web/src/components/community/social/profile-card.tsx
@@ -1,17 +1,21 @@
"use client"
-import { useState } from "react"
-import { MessagesSquare, Shield } from "lucide-react"
+import { useLayoutEffect, useRef, useState } from "react"
+import { Bot, MessagesSquare, Shield, UserRound } from "lucide-react"
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
import { Badge } from "@/components/ui/badge"
import { Avatar } from "../avatar"
import { SeededBackdrop } from "@/components/avatar"
import { resolveAvatar } from "@/lib/avatar/resolve"
import { StatusEditor, hasStatus } from "./status-editor"
-import type { Profile } from "@/components/community/social/profile-types"
+import type {
+ OwnerProfileRef,
+ Profile,
+} from "@/components/community/social/profile-types"
import type { Breakpoint } from "@/hooks/use-mobile"
import { useCommunityWsStore } from "@/stores/community/ws"
import { tid } from "@/lib/community/testids"
+import { BotAuditPreview, isBotActivityActive } from "./bot-audit-preview"
// Merge rule for the card's status pill: overlay wins over seed. The overlay
// (`useCommunityWsStore.userStatuses`) is the same live source the member
@@ -41,13 +45,152 @@ export function resolveProfileBackdropSeed(
return resolved.kind === "beam" ? resolved.seed : fallbackSeed
}
+export function displayOwnerHandle(handle: string): string {
+ return handle.replace(/#\d+$/, "")
+}
+
+export type AuditPreviewPlacement = "right" | "left" | "top" | "bottom"
+
+type RectLike = Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">
+
+export function resolveAuditPreviewPlacement({
+ card,
+ preview,
+ viewportWidth,
+ viewportHeight,
+ gap = 8,
+}: {
+ card: RectLike
+ preview: Pick<RectLike, "width" | "height">
+ viewportWidth: number
+ viewportHeight: number
+ gap?: number
+}): AuditPreviewPlacement {
+ const room = {
+ right: viewportWidth - card.right,
+ left: card.left,
+ top: card.top,
+ bottom: viewportHeight - card.bottom,
+ }
+ const sideCrossAxisFits = preview.height <= viewportHeight - gap * 2
+ const verticalCrossAxisFits = preview.width <= viewportWidth - gap * 2
+
+ if (sideCrossAxisFits && room.right >= preview.width + gap) return "right"
+ if (sideCrossAxisFits && room.left >= preview.width + gap) return "left"
+ if (verticalCrossAxisFits && room.top >= preview.height + gap) return "top"
+ if (verticalCrossAxisFits && room.bottom >= preview.height + gap) return "bottom"
+
+ return (Object.entries(room) as Array<[AuditPreviewPlacement, number]>)
+ .sort((a, b) => b[1] - a[1])[0]?.[0] ?? "right"
+}
+
+type AuditPreviewPosition = {
+ placement: AuditPreviewPlacement
+ left: number | string
+ top: number
+}
+
+function clamp(value: number, min: number, max: number): number {
+ if (min > max) return value
+ return Math.min(Math.max(value, min), max)
+}
+
+function useAuditPreviewPosition(enabled: boolean, x: number, y: number) {
+ const popoverRef = useRef<HTMLDivElement | null>(null)
+ const cardRef = useRef<HTMLDivElement | null>(null)
+ const previewRef = useRef<HTMLDivElement | null>(null)
+ const [position, setPosition] = useState<AuditPreviewPosition>({
+ placement: "right",
+ left: "calc(100% + 0.5rem)",
+ top: 0,
+ })
+
+ useLayoutEffect(() => {
+ if (!enabled) return
+
+ let frame = 0
+ const update = () => {
+ const cardElement = cardRef.current
+ const previewElement = previewRef.current
+ if (!cardElement || !previewElement) return
+ const transformedCard = cardElement.getBoundingClientRect()
+ const card = {
+ top: transformedCard.top,
+ right: transformedCard.left + cardElement.offsetWidth,
+ bottom: transformedCard.top + cardElement.offsetHeight,
+ left: transformedCard.left,
+ width: cardElement.offsetWidth,
+ height: cardElement.offsetHeight,
+ }
+ const preview = {
+ width: previewElement.offsetWidth,
+ height: previewElement.offsetHeight,
+ }
+ const gap = 8
+ const margin = 8
+ const placement = resolveAuditPreviewPlacement({
+ card,
+ preview,
+ viewportWidth: window.innerWidth,
+ viewportHeight: window.innerHeight,
+ gap,
+ })
+
+ const verticalOffset = clamp(
+ 0,
+ margin - card.top,
+ window.innerHeight - margin - preview.height - card.top,
+ )
+ const horizontalOffset = clamp(
+ card.width - preview.width,
+ margin - card.left,
+ window.innerWidth - margin - preview.width - card.left,
+ )
+ const next: AuditPreviewPosition = placement === "right"
+ ? { placement, left: card.width + gap, top: verticalOffset }
+ : placement === "left"
+ ? { placement, left: -preview.width - gap, top: verticalOffset }
+ : placement === "top"
+ ? { placement, left: horizontalOffset, top: -preview.height - gap }
+ : { placement, left: horizontalOffset, top: card.height + gap }
+
+ setPosition((current) => current.placement === next.placement
+ && current.left === next.left
+ && current.top === next.top
+ ? current
+ : next)
+ }
+
+ update()
+ frame = requestAnimationFrame(update)
+ window.addEventListener("resize", update)
+ window.addEventListener("scroll", update, true)
+ const popoverElement = popoverRef.current
+ popoverElement?.addEventListener("animationend", update)
+ popoverElement?.addEventListener("animationcancel", update)
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update)
+ if (cardRef.current) observer?.observe(cardRef.current)
+ if (previewRef.current) observer?.observe(previewRef.current)
+ return () => {
+ cancelAnimationFrame(frame)
+ window.removeEventListener("resize", update)
+ window.removeEventListener("scroll", update, true)
+ popoverElement?.removeEventListener("animationend", update)
+ popoverElement?.removeEventListener("animationcancel", update)
+ observer?.disconnect()
+ }
+ }, [enabled, x, y])
+
+ return { popoverRef, cardRef, previewRef, position }
+}
+
// Profile card β€” popover anchored at the click point on desktop, bottom sheet on mobile.
// Status (emoji + text) is read live from `useCommunityWsStore.userStatuses` β€”
// the same overlay the member list, friends list, and UserBar consume. The
// `initialStatusEmoji` / `initialStatusText` props are a first-paint seed for
// users the overlay has never seen a WS event for; once the overlay has an
// entry, it wins. See plans/profile-card-status-overlay.md.
-export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdateStatus, initialStatusEmoji, initialStatusText, embedded }: {
+export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdateStatus, onOpenOwnerProfile, onOpenBotAudit, initialStatusEmoji, initialStatusText, activityStatusEmoji, activityStatusText, embedded }: {
data: Profile
x: number
y: number
@@ -58,8 +201,12 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
// Only used when `isSelf` β€” the inline status row opens `StatusEditor` and
// calls this on a preset pick / free-text commit / emoji override / clear.
onUpdateStatus?: (emoji: string | null, text: string | null) => void
+ onOpenOwnerProfile?: (owner: OwnerProfileRef) => void
+ onOpenBotAudit?: (botId: string) => void
initialStatusEmoji?: string | null
initialStatusText?: string | null
+ activityStatusEmoji?: string | null
+ activityStatusText?: string | null
// Static card surface for contexts such as product previews. The regular
// profile interaction still uses the anchored popover / mobile sheet.
embedded?: boolean
@@ -69,6 +216,14 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
const mobile = bp === "mobile"
const liveStatus = useCommunityWsStore((s) => (data.userId ? s.userStatuses.get(data.userId) : undefined))
const { emoji: statusEmoji, text: statusText } = resolveCardStatus(liveStatus, initialStatusEmoji, initialStatusText)
+ const activityStatus = resolveCardStatus(liveStatus, activityStatusEmoji, activityStatusText)
+ const botIdentity = data.identity?.kind === "bot" ? data.identity : null
+ const showAuditPreview = Boolean(botIdentity?.ownedByViewer && data.userId)
+ const { popoverRef, cardRef, previewRef, position: previewPosition } = useAuditPreviewPosition(
+ showAuditPreview && !mobile && !embedded,
+ x,
+ y,
+ )
const backdropSeed = resolveProfileBackdropSeed(data.avatar, data.userId, data.name)
const close = () => setOpen(false)
const send = () => {
@@ -178,8 +333,35 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
(a step past DESIGN.md's 16px between-groups token) rather than
just tighter line spacing off the bio above it. */}
<p className="mt-2 text-[15px] text-muted-foreground">{data.about || "No bio yet."}</p>
- {(data.contextLabel || data.mutual > 0) && (
- <div className="mt-6 flex items-center gap-2 text-xs text-muted-foreground">
+ {(botIdentity || data.contextLabel || data.mutual > 0) && (
+ <div className="mt-6 flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">
+ {botIdentity && (
+ <>
+ <Badge
+ data-testid={tid.profileBotBadge}
+ variant="secondary"
+ className="h-5 gap-1 text-xs"
+ >
+ <Bot className="size-3 shrink-0" aria-hidden />
+ Bot
+ </Badge>
+ <button
+ type="button"
+ data-testid={tid.profileOwnerLink}
+ className="group/owner flex h-11 min-w-0 max-w-full items-center rounded-full text-xs focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:h-5"
+ onClick={() => onOpenOwnerProfile?.(botIdentity.ownerProfile)}
+ aria-label={`Open owner profile @${botIdentity.ownerProfile.handle}`}
+ >
+ <Badge
+ variant="secondary"
+ className="pointer-events-none min-w-0 max-w-full transition-colors group-hover/owner:bg-accent group-active/owner:bg-accent/80"
+ >
+ <UserRound className="size-3 shrink-0" aria-hidden />
+ <span className="min-w-0 truncate">@{displayOwnerHandle(botIdentity.ownerProfile.handle)}</span>
+ </Badge>
+ </button>
+ </>
+ )}
{data.contextLabel && (
<Badge data-testid={tid.profileContextBadge} variant="secondary" className="h-5 gap-1 text-xs">
<Shield className="size-3" /> {data.contextLabel}
@@ -214,15 +396,29 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
</>
)
+ const auditPreview = showAuditPreview && data.userId ? (
+ <BotAuditPreview
+ botId={data.userId}
+ active={isBotActivityActive(activityStatus.emoji, activityStatus.text)}
+ onOpen={() => onOpenBotAudit?.(data.userId!)}
+ />
+ ) : null
+
if (embedded)
- return <div data-testid={tid.profileCard} className="w-full overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">{card}</div>
+ return (
+ <div className="flex w-full flex-col gap-2">
+ {auditPreview}
+ <div data-testid={tid.profileCard} className="w-full overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">{card}</div>
+ </div>
+ )
// mobile: bottom sheet (intentional mobile UX, kept manual)
if (mobile)
return (
<div className="fixed inset-0 z-30 flex flex-col justify-end" onClick={onClose}>
<div className="absolute inset-0 bg-foreground/30" />
- <div className="relative p-3" onClick={(e) => e.stopPropagation()}>
+ <div className="relative flex flex-col gap-2 p-3" onClick={(e) => e.stopPropagation()}>
+ {auditPreview}
<div data-testid={tid.profileCard} className="overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">{card}</div>
</div>
</div>
@@ -237,8 +433,21 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda
className="pointer-events-none fixed size-0"
style={{ left: x, top: y }}
/>
- <PopoverContent data-testid={tid.profileCard} side="right" align="start" sideOffset={8} className="w-75 overflow-hidden p-2">
- {card}
+ <PopoverContent ref={popoverRef} side="right" align="start" sideOffset={8} className="relative w-75 overflow-visible border-0 bg-transparent p-0 shadow-none">
+ {auditPreview && (
+ <div
+ ref={previewRef}
+ data-testid={tid.botAuditPreviewDock}
+ data-placement={previewPosition.placement}
+ className="absolute w-full"
+ style={{ left: previewPosition.left, top: previewPosition.top }}
+ >
+ {auditPreview}
+ </div>
+ )}
+ <div ref={cardRef} data-testid={tid.profileCard} className="overflow-hidden rounded-xl border border-border bg-popover p-2 shadow-(--e2)">
+ {card}
+ </div>
</PopoverContent>
</Popover>
)
diff --git a/src/web/src/components/community/social/profile-lookup.ts b/src/web/src/components/community/social/profile-lookup.ts
index 67ac4976d..e9da3bd59 100644
--- a/src/web/src/components/community/social/profile-lookup.ts
+++ b/src/web/src/components/community/social/profile-lookup.ts
@@ -29,6 +29,7 @@ export function buildSelfProfile(
about: currentUser.aboutMe ?? "",
mutual: 0,
presence: resolveProfilePresence(true, undefined, onlineUserIds),
+ identity: { kind: "human" },
}
}
diff --git a/src/web/src/components/community/social/profile-types.ts b/src/web/src/components/community/social/profile-types.ts
index 73a6e2145..ce9d01e41 100644
--- a/src/web/src/components/community/social/profile-types.ts
+++ b/src/web/src/components/community/social/profile-types.ts
@@ -21,8 +21,24 @@ export type Profile = {
// member/friend match could be resolved (e.g. a stale mention). See
// `resolveProfilePresence` in shell-frame.tsx.
presence?: Presence
+ // Hydrated API identity. Seeded cards intentionally omit this so the main
+ // profile can paint before the public profile request resolves.
+ identity?: ProfileIdentity
}
+export type OwnerProfileRef = {
+ id: string
+ handle: string
+}
+
+type ProfileIdentity =
+ | { kind: "human" }
+ | {
+ kind: "bot"
+ ownerProfile: OwnerProfileRef
+ ownedByViewer: boolean
+ }
+
// Shared callback signature for opening a user's profile card at a click point.
// `userId` is the exact-match disambiguator β€” pass it whenever the caller
// already has the clicked person's userId (member rows, message authors,
diff --git a/src/web/src/hooks/community/use-bot-audit-preview.test.ts b/src/web/src/hooks/community/use-bot-audit-preview.test.ts
new file mode 100644
index 000000000..c3c384d9a
--- /dev/null
+++ b/src/web/src/hooks/community/use-bot-audit-preview.test.ts
@@ -0,0 +1,149 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { ApiError } from "@/lib/errors"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { useBotAuditPreview } from "./use-bot-audit-preview"
+
+const apiFetch = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetch(...args),
+}))
+
+type Result = ReturnType<typeof useBotAuditPreview>
+const renderers = new Set<TestRenderer.ReactTestRenderer>()
+
+function renderHook(botId: string | null) {
+ const result: { current: Result } = { current: null as never }
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ })
+ function Probe() {
+ result.current = useBotAuditPreview(botId)
+ return null
+ }
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Probe),
+ ),
+ )
+ })
+ renderers.add(renderer)
+ return { result, queryClient }
+}
+
+async function flush() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+}
+
+async function waitFor(predicate: () => boolean, tries = 200) {
+ for (let attempt = 0; attempt < tries; attempt += 1) {
+ if (predicate()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ })
+ }
+ expect(predicate()).toBe(true)
+}
+
+const event = (id: string, second: number) => ({
+ id,
+ kind: "tool_call" as const,
+ payload: { private: id },
+ sessionId: null,
+ launchId: null,
+ createdAt: `2026-01-01T00:00:${String(second).padStart(2, "0")}.000Z`,
+})
+
+describe("useBotAuditPreview", () => {
+ beforeEach(() => {
+ apiFetch.mockReset()
+ useCommunityWsStore.getState().reset()
+ })
+
+ afterEach(() => {
+ act(() => {
+ for (const renderer of renderers) renderer.unmount()
+ })
+ renderers.clear()
+ })
+
+ it("uses a separate finite limit=5 cache from the full modal", async () => {
+ apiFetch.mockResolvedValueOnce({ events: [event("e1", 1)], nextCursor: null })
+ const { result, queryClient } = renderHook("b1")
+ await waitFor(() => result.current.events.length === 1)
+
+ expect(apiFetch).toHaveBeenCalledWith(
+ "/api/community/bots/b1/audit-log?limit=5",
+ )
+ expect(result.current.events.map((item) => item.id)).toEqual(["e1"])
+ expect(queryClient.getQueryData(communityKeys.botAuditPreview("b1"))).toBeDefined()
+ expect(queryClient.getQueryData(communityKeys.botAuditLog("b1"))).toBeUndefined()
+ })
+
+ it("does no request when ownership gating passes a null bot id", async () => {
+ renderHook(null)
+ await flush()
+ expect(apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("merges live events, deduplicates by id, orders newest first, and caps five", async () => {
+ apiFetch.mockResolvedValueOnce({
+ events: [event("e1", 1), event("e2", 2), event("e3", 3), event("e4", 4)],
+ nextCursor: null,
+ })
+ const { result } = renderHook("b1")
+ await waitFor(() => result.current.events.length === 4)
+
+ act(() => {
+ useCommunityWsStore.getState().pushBotAuditEvent({
+ ...event("e2", 12),
+ botId: "b1",
+ })
+ useCommunityWsStore.getState().pushBotAuditEvent({
+ ...event("e5", 5),
+ botId: "b1",
+ })
+ useCommunityWsStore.getState().pushBotAuditEvent({
+ ...event("e6", 6),
+ botId: "b1",
+ })
+ })
+ await waitFor(() => result.current.events[0]?.id === "e2")
+
+ expect(result.current.events.map((item) => item.id)).toEqual([
+ "e2",
+ "e6",
+ "e5",
+ "e4",
+ "e3",
+ ])
+ })
+
+ it("orders equal timestamps by descending event id", async () => {
+ apiFetch.mockResolvedValueOnce({
+ events: [event("e1", 1), event("e3", 1), event("e2", 1)],
+ nextCursor: null,
+ })
+ const { result } = renderHook("b1")
+ await waitFor(() => result.current.events.length === 3)
+
+ expect(result.current.events.map((item) => item.id)).toEqual(["e3", "e2", "e1"])
+ })
+
+ it("reports authoritative 404s so a stale owned card can hide the preview", async () => {
+ apiFetch.mockRejectedValueOnce(new ApiError("not found", 404))
+ const { result } = renderHook("b1")
+ await waitFor(() => result.current.isNotFound)
+ expect(result.current.isNotFound).toBe(true)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/web/src/hooks/community/use-bot-audit-preview.ts b/src/web/src/hooks/community/use-bot-audit-preview.ts
new file mode 100644
index 000000000..1ae7325b8
--- /dev/null
+++ b/src/web/src/hooks/community/use-bot-audit-preview.ts
@@ -0,0 +1,56 @@
+"use client"
+
+import { useMemo } from "react"
+import { useQuery } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { ApiError } from "@/lib/errors"
+import { communityKeys } from "@/lib/query-keys"
+import { useBotAuditEventsForBot } from "@/stores/community/ws"
+import type { AuditEvent, AuditLogPage } from "./use-bot-audit-log"
+
+const PREVIEW_LIMIT = 5
+
+export function useBotAuditPreview(botId: string | null | undefined) {
+ const enabled = Boolean(botId)
+ const query = useQuery<AuditLogPage>({
+ enabled,
+ queryKey: botId
+ ? communityKeys.botAuditPreview(botId)
+ : ["disabled-bot-audit-preview"],
+ queryFn: () => apiFetch<AuditLogPage>(
+ `/api/community/bots/${botId}/audit-log?limit=${PREVIEW_LIMIT}`,
+ ),
+ retry: (failureCount, error) =>
+ !(error instanceof ApiError && error.status === 404) && failureCount < 1,
+ staleTime: 30_000,
+ })
+ const liveEvents = useBotAuditEventsForBot(botId)
+
+ const events = useMemo(() => {
+ const byId = new Map<string, AuditEvent>()
+ for (const event of query.data?.events ?? []) byId.set(event.id, event)
+ for (const event of liveEvents) {
+ byId.set(event.id, {
+ id: event.id,
+ kind: event.kind,
+ payload: event.payload,
+ sessionId: event.sessionId ?? null,
+ launchId: event.launchId ?? null,
+ createdAt: event.createdAt,
+ })
+ }
+ return [...byId.values()]
+ .sort((a, b) => {
+ if (a.createdAt !== b.createdAt) return a.createdAt > b.createdAt ? -1 : 1
+ return a.id > b.id ? -1 : a.id < b.id ? 1 : 0
+ })
+ .slice(0, PREVIEW_LIMIT)
+ }, [liveEvents, query.data])
+
+ return {
+ events,
+ isLoading: query.isLoading,
+ isError: query.isError,
+ isNotFound: query.error instanceof ApiError && query.error.status === 404,
+ }
+}
diff --git a/src/web/src/hooks/community/use-user-profile.ts b/src/web/src/hooks/community/use-user-profile.ts
index 8ac51cc52..dc77bb8d7 100644
--- a/src/web/src/hooks/community/use-user-profile.ts
+++ b/src/web/src/hooks/community/use-user-profile.ts
@@ -6,10 +6,11 @@ import { apiFetch } from "@/lib/api/client"
* Fetches a public user profile card (avatar, name, aboutMe, mutual-server
* count).
*
- * The route (`GET /api/community/users/:userId/profile`) already gates on
- * viewer visibility, so we can cache freely under the viewer's session.
+ * The route (`GET /api/community/users/:userId/profile`) is authenticated and
+ * returns viewer-relative bot ownership. The community query cache is cleared
+ * on logout, so this response remains scoped to the current viewer session.
*/
-export type UserProfile = {
+type UserProfileBase = {
id: string
name: string
discriminator: string
@@ -21,6 +22,15 @@ export type UserProfile = {
statusText: string | null
}
+export type UserProfile = UserProfileBase & (
+ | { kind: "human" }
+ | {
+ kind: "bot"
+ ownerProfile: { id: string; handle: string }
+ ownedByViewer: boolean
+ }
+)
+
export const userProfileQueryFn = (userId: string) => () =>
apiFetch<UserProfile>(`/api/community/users/${userId}/profile`)
diff --git a/src/web/src/lib/community/audit-event-summary.test.ts b/src/web/src/lib/community/audit-event-summary.test.ts
new file mode 100644
index 000000000..279276011
--- /dev/null
+++ b/src/web/src/lib/community/audit-event-summary.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest"
+import { summarizeAuditEvent } from "./audit-event-summary"
+import type { AuditKind } from "@/hooks/community/use-bot-audit-log"
+
+describe("summarizeAuditEvent", () => {
+ it("has bounded copy for every audit kind", () => {
+ const kinds: AuditKind[] = [
+ "cli_invocation",
+ "tool_call",
+ "thinking",
+ "wake_trigger",
+ "session_reset",
+ "nap",
+ "model_changed",
+ "provider_changed",
+ "error",
+ ]
+ const secret = "https://private.example/path?token=secret"
+
+ for (const kind of kinds) {
+ const summary = summarizeAuditEvent({ kind, payload: null })
+ expect(summary.length).toBeGreaterThan(0)
+ expect(summary).not.toContain(secret)
+ expect(summary).not.toContain("private.example")
+ }
+ })
+
+ it("shows the real short Alook command and tool name without arguments", () => {
+ expect(summarizeAuditEvent({
+ kind: "cli_invocation",
+ payload: { subcommand: "inboxPull" },
+ })).toBe("alook inbox pull")
+ expect(summarizeAuditEvent({
+ kind: "cli_invocation",
+ payload: { subcommand: "attachmentUpload" },
+ })).toBe("alook message attachment upload")
+ expect(summarizeAuditEvent({
+ kind: "cli_invocation",
+ payload: { subcommand: "customCommand" },
+ })).toBe("alook custom command")
+ expect(summarizeAuditEvent({
+ kind: "tool_call",
+ payload: { name: "Exec_Command", target: "cat /Users/gus/private.txt" },
+ })).toBe("exec_command")
+ })
+
+ it("never derives preview text from thinking, path, URL, or error payloads", () => {
+ const event = {
+ kind: "thinking" as const,
+ payload: {
+ thinking: "private chain of thought",
+ path: "/Users/gus/secret.txt",
+ url: "https://private.example",
+ error: "credential failed",
+ },
+ }
+ expect(summarizeAuditEvent(event)).toBe("Updated its reasoning")
+ expect(summarizeAuditEvent(event)).not.toMatch(/secret|private|credential|Users/)
+ })
+})
diff --git a/src/web/src/lib/community/audit-event-summary.ts b/src/web/src/lib/community/audit-event-summary.ts
new file mode 100644
index 000000000..d35172219
--- /dev/null
+++ b/src/web/src/lib/community/audit-event-summary.ts
@@ -0,0 +1,81 @@
+import type { AuditEvent, AuditKind } from "@/hooks/community/use-bot-audit-log"
+
+const SUMMARY_BY_KIND: Record<AuditKind, string> = {
+ cli_invocation: "alook command",
+ tool_call: "tool",
+ thinking: "Updated its reasoning",
+ wake_trigger: "Woke for a new message",
+ session_reset: "Session reset requested",
+ nap: "Started a fresh session",
+ model_changed: "Model changed",
+ provider_changed: "Provider changed",
+ error: "Encountered an error",
+}
+
+/**
+ * Concrete, bounded copy for the compact owner preview.
+ *
+ * Audit payloads can contain thinking text, filesystem paths, URLs, sender
+ * handles, channel refs, model ids, and raw error messages. The preview is a
+ * navigation surface rather than the full developer log, so only the safe
+ * CLI verb or tool name is surfaced. Targets, arguments, thinking, paths,
+ * URLs, and raw errors remain confined to the full audit log.
+ */
+export function summarizeAuditEvent(
+ event: Pick<AuditEvent, "kind"> & Partial<Pick<AuditEvent, "payload">>,
+): string {
+ if (event.kind === "cli_invocation") return formatAlookAuditCommand(event.payload)
+ if (event.kind === "tool_call") return formatAuditToolName(event.payload)
+ return SUMMARY_BY_KIND[event.kind]
+}
+
+const ALOOK_COMMAND_BY_SUBCOMMAND: Record<string, string> = {
+ send: "message send",
+ read: "channel history",
+ resolve: "channel history",
+ reactAdd: "message emoji",
+ markSet: "message mark set",
+ markRemove: "message mark remove",
+ markList: "message mark list",
+ channelMember: "channel member",
+ attachmentUpload: "message attachment upload",
+ attachmentDownload: "message attachment download",
+ listMembers: "server member",
+ listChannels: "channel list",
+ listFriends: "friend list",
+ friendRequest: "friend request",
+ inboxPull: "inbox pull",
+ inboxSnapshot: "inbox pull --no-ack",
+ profileBioUpdate: "setting profile",
+ profileAvatarUpdate: "setting profile",
+ nap: "nap",
+}
+
+export function formatAlookAuditCommand(payload: unknown): string {
+ const subcommand = payload && typeof payload === "object" && "subcommand" in payload
+ && typeof payload.subcommand === "string"
+ ? payload.subcommand
+ : null
+ if (!subcommand) return "alook command"
+ return `alook ${ALOOK_COMMAND_BY_SUBCOMMAND[subcommand] ?? wordsFromCamelCase(subcommand)}`
+}
+
+export function formatAuditToolName(payload: unknown): string {
+ const name = payload && typeof payload === "object" && "name" in payload
+ && typeof payload.name === "string"
+ ? payload.name.trim().toLowerCase()
+ : ""
+ return name || "tool"
+}
+
+function wordsFromCamelCase(value: string): string {
+ return value.replace(/([a-z\d])([A-Z])/g, "$1 $2").toLowerCase()
+}
+
+export function formatAuditPreviewTime(iso: string): string {
+ const date = new Date(iso)
+ return date.toLocaleTimeString(undefined, {
+ hour: "2-digit",
+ minute: "2-digit",
+ })
+}
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index 77bf42865..999d185e9 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -19,6 +19,14 @@ describe("community QA selectors", () => {
it("exposes the profile context badge independently from the card", () => {
expect(tid.profileCard).toBe("community-profile-card")
expect(tid.profileContextBadge).toBe("community-profile-context-badge")
+ expect(tid.profileBotBadge).toBe("community-profile-bot-badge")
+ expect(tid.profileOwnerLink).toBe("community-profile-owner-link")
+ expect(tid.botAuditPreview).toBe("community-bot-audit-preview")
+ expect(tid.botAuditPreviewDock).toBe("community-bot-audit-preview-dock")
+ expect(tid.botAuditPreviewActive).toBe("community-bot-audit-preview-active")
+ expect(tid.botAuditPreviewRow("event_1")).toBe(
+ "community-bot-audit-preview-row-event_1",
+ )
})
it("exposes attachment preview selectors from one canonical map", () => {
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index e0b83194f..da94a90b9 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -30,6 +30,12 @@ export const tid = {
dmBlockedNotice: "community-dm-blocked-notice",
profileCard: "community-profile-card",
profileContextBadge: "community-profile-context-badge",
+ profileBotBadge: "community-profile-bot-badge",
+ profileOwnerLink: "community-profile-owner-link",
+ botAuditPreview: "community-bot-audit-preview",
+ botAuditPreviewDock: "community-bot-audit-preview-dock",
+ botAuditPreviewActive: "community-bot-audit-preview-active",
+ botAuditPreviewRow: (id: string) => `community-bot-audit-preview-row-${id}`,
statusPill: "community-status-pill",
inviteToken: "community-invite-token",
inviteCopy: "community-invite-copy",
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index 98a7cb2ab..137d132e8 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -125,6 +125,15 @@ describe("communityKeys", () => {
"profile",
"u1",
])
+ expect(communityKeys.botAuditPreview("b1")).toEqual([
+ "community",
+ "bot",
+ "b1",
+ "audit-preview",
+ ])
+ expect(communityKeys.botAuditPreview("b1")).not.toEqual(
+ communityKeys.botAuditLog("b1"),
+ )
expect(communityKeys.message("m1")).toEqual([
"community",
"message",
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 9ca9cab5a..6fd3ffe0c 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -137,6 +137,8 @@ export const communityKeys = {
[...communityKeys.all, "bug-report", reportId] as const,
botAuditLog: (botId: string) =>
[...communityKeys.all, "bot", botId, "audit-log"] as const,
+ botAuditPreview: (botId: string) =>
+ [...communityKeys.all, "bot", botId, "audit-preview"] as const,
// ── Notification settings ───────────────────────────────────────────────
notificationSettings: () =>
diff --git a/src/web/src/test/e2e-service-definitions.test.ts b/src/web/src/test/e2e-service-definitions.test.ts
index b82cecb8f..81b59ddc4 100644
--- a/src/web/src/test/e2e-service-definitions.test.ts
+++ b/src/web/src/test/e2e-service-definitions.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest"
import { serviceDefinitions } from "./e2e-ui/_setup/services"
+import { resolveMachineWsUrl, resolveWsUrl } from "./e2e-ui/_setup/paths"
describe("UI E2E service definitions", () => {
it("uses one Wrangler runtime for web and ws-do in CI", () => {
@@ -18,4 +19,40 @@ describe("UI E2E service definitions", () => {
it("keeps the fast two-process topology for local iteration", () => {
expect(serviceDefinitions(false).map((definition) => definition.name)).toEqual(["web", "ws-do"])
})
+
+ it("uses the web URL for ws-do in the CI single-runtime topology", () => {
+ expect(resolveWsUrl({
+ webUrl: "http://localhost:3000",
+ singleRuntime: true,
+ })).toBe("http://localhost:3000")
+ })
+
+ it("keeps the local ws-do port for the split-runtime topology", () => {
+ expect(resolveWsUrl({
+ webUrl: "http://localhost:3000",
+ singleRuntime: false,
+ })).toBe("http://localhost:8789")
+ })
+
+ it("always honors an explicit ws-do URL", () => {
+ expect(resolveWsUrl({
+ webUrl: "http://localhost:3000",
+ explicitWsUrl: "http://localhost:9000",
+ singleRuntime: true,
+ })).toBe("http://localhost:9000")
+ })
+
+ it("routes machine upgrades through the web worker in the single runtime", () => {
+ expect(resolveMachineWsUrl({
+ wsUrl: "http://localhost:3000/",
+ singleRuntime: true,
+ })).toBe("http://localhost:3000/api/ws/community-machine")
+ })
+
+ it("connects machines directly to ws-do in the split runtime", () => {
+ expect(resolveMachineWsUrl({
+ wsUrl: "http://localhost:8789/",
+ singleRuntime: false,
+ })).toBe("http://localhost:8789")
+ })
})
diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
new file mode 100644
index 000000000..205a635ce
--- /dev/null
+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
@@ -0,0 +1,281 @@
+import { createRequire } from "module"
+import { resolve } from "path"
+import type { Page } from "@playwright/test"
+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { seedChannel, seedJoinServer, seedServer } from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+import { MACHINE_WS_URL, REPO_ROOT, WEB_URL } from "./_setup/paths"
+
+type UserKey = "alice" | "bob"
+
+function headersFor(key: UserKey, extra?: Record<string, string>) {
+ return {
+ Cookie: sessionCookie(key),
+ Origin: WEB_URL,
+ ...extra,
+ }
+}
+
+async function jsonRequest<T>(
+ key: UserKey,
+ path: string,
+ init?: RequestInit,
+): Promise<T> {
+ const response = await fetch(`${WEB_URL}${path}`, {
+ ...init,
+ headers: headersFor(key, {
+ ...(init?.body ? { "Content-Type": "application/json" } : {}),
+ ...(init?.headers as Record<string, string> | undefined),
+ }),
+ })
+ expect(response.status, `${init?.method ?? "GET"} ${path}`).toBeLessThan(300)
+ return response.json() as Promise<T>
+}
+
+async function pairMachine(): Promise<{ credential: string; machineId: string }> {
+ const pair = await jsonRequest<{ tokenId: string }>("alice", "/api/community/machines/pair", {
+ method: "POST",
+ })
+ const response = await fetch(`${WEB_URL}/api/community/daemon/activate`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${pair.tokenId}`,
+ "Content-Type": "application/json",
+ Origin: WEB_URL,
+ },
+ body: JSON.stringify({
+ hostname: `profile-preview-e2e-${Date.now()}`,
+ platform: "darwin",
+ arch: "arm64",
+ runtimeReport: [{ id: "codex", status: "healthy" }],
+ }),
+ })
+ expect(response.status).toBe(200)
+ return response.json() as Promise<{ credential: string; machineId: string }>
+}
+
+async function createBot(machineId: string, name: string): Promise<string> {
+ const data = await jsonRequest<{ bot: { id: string } }>("alice", "/api/community/bots", {
+ method: "POST",
+ body: JSON.stringify({ name, machineId, runtime: "codex" }),
+ })
+ return data.bot.id
+}
+
+async function enrollBot(credential: string, botId: string): Promise<string> {
+ const response = await fetch(`${WEB_URL}/api/community/daemon/enroll-agent`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${credential}`,
+ "Content-Type": "application/json",
+ Origin: WEB_URL,
+ },
+ body: JSON.stringify({ agentId: botId }),
+ })
+ expect(response.status).toBe(200)
+ const data = await response.json() as { runnerKey: string }
+ return data.runnerKey
+}
+
+async function sendBotMessage(runnerKey: string, channel: string, text: string): Promise<void> {
+ const response = await fetch(`${WEB_URL}/api/community/channels/resolve/messages`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${runnerKey}`,
+ "Content-Type": "application/json",
+ Origin: WEB_URL,
+ },
+ body: JSON.stringify({
+ channel,
+ content: { text },
+ attachments: [],
+ seenUpToSeq: 0,
+ nonce: `profile-preview:${crypto.randomUUID()}`,
+ }),
+ })
+ expect(response.status).toBe(200)
+ expect((await response.json() as { state: string }).state).toBe("sent")
+}
+
+type MachineSocket = {
+ send: (data: string) => void
+ close: () => void
+ once(event: "open", listener: () => void): void
+ once(event: "error", listener: (error: Error) => void): void
+}
+
+function connectMachine(credential: string) {
+ const requireFromDaemon = createRequire(resolve(REPO_ROOT, "src/daemon/package.json"))
+ const Ws = requireFromDaemon("ws") as {
+ WebSocket: new (url: string, options: { headers: Record<string, string> }) => MachineSocket
+ }
+ const socket = new Ws.WebSocket(MACHINE_WS_URL.replace(/^http/, "ws"), {
+ headers: { Authorization: `Bearer ${credential}` },
+ })
+ return {
+ socket,
+ opened: new Promise<void>((resolveOpen, reject) => {
+ socket.once("open", () => resolveOpen())
+ socket.once("error", reject)
+ }),
+ }
+}
+
+async function openBotProfile(page: Page, botName: string): Promise<void> {
+ await page.getByRole("button", { name: botName, exact: true }).click()
+ await expect(page.getByTestId(tid.profileCard)).toBeVisible()
+}
+
+test("owner-only bot profile preview, owner swap, and URL-owned audit modal", async ({ asUser }) => {
+ test.setTimeout(180_000)
+ const suffix = Date.now().toString(36)
+ const serverId = await seedServer("alice", `profile-preview-${suffix}`)
+ const channelName = `bots-${suffix}`
+ const channelId = await seedChannel("alice", serverId, channelName)
+ await seedJoinServer("alice", "bob", serverId)
+
+ const { credential, machineId } = await pairMachine()
+ const botName = `Preview bot ${suffix}`
+ const botId = await createBot(machineId, botName)
+ await jsonRequest("alice", `/api/community/servers/${serverId}/bots`, {
+ method: "POST",
+ body: JSON.stringify({ botId }),
+ })
+
+ const { servers } = await jsonRequest<{
+ servers: Array<{ id: string; name: string; discriminator: string }>
+ }>("alice", "/api/community/servers")
+ const server = servers.find((candidate) => candidate.id === serverId)
+ expect(server).toBeTruthy()
+ const runnerKey = await enrollBot(credential, botId)
+ await sendBotMessage(
+ runnerKey,
+ `/${server!.name}#${server!.discriminator}/${channelName}`,
+ `Open my profile ${suffix}`,
+ )
+
+ const machine = connectMachine(credential)
+ await machine.opened
+ try {
+ machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))
+ for (const index of [1, 2, 3, 4, 5, 6]) {
+ machine.socket.send(JSON.stringify({
+ type: "bot_audit_event",
+ agentId: botId,
+ sessionId: `session-${suffix}`,
+ launchId: `launch-${suffix}`,
+ event: { kind: "tool_call", payload: { name: `Tool ${index}` } },
+ }))
+ }
+
+ await expect.poll(async () => {
+ const response = await fetch(
+ `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=5`,
+ { headers: headersFor("alice") },
+ )
+ if (!response.ok) return 0
+ return ((await response.json()) as { events: unknown[] }).events.length
+ }).toBe(5)
+
+ const route = `/c/channels/${serverId}/${channelId}`
+ const alice = await asUser("alice")
+ const ownerAuditRequests: string[] = []
+ alice.page.on("request", (request) => {
+ if (new URL(request.url()).pathname === `/api/community/bots/${botId}/audit-log`) {
+ ownerAuditRequests.push(request.url())
+ }
+ })
+ await gotoAfterUserWsAuth(alice.page, route)
+ await openBotProfile(alice.page, botName)
+
+ const preview = alice.page.getByTestId(tid.botAuditPreview)
+ await expect(preview).toBeVisible()
+ await expect(preview).toContainText("Only you can see this")
+ await expect(preview).toHaveAttribute(
+ "aria-label",
+ "Bot at rest. Open full bot activity log",
+ )
+ await expect(alice.page.locator('[data-testid^="community-bot-audit-preview-row-"]'))
+ .toHaveCount(5)
+ expect(ownerAuditRequests.some((url) => new URL(url).searchParams.get("limit") === "5"))
+ .toBe(true)
+
+ machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "running" }))
+ await expect(preview).toHaveAttribute(
+ "aria-label",
+ "Bot activity in progress. Open full bot activity log",
+ )
+ const activeRow = alice.page.getByTestId(tid.botAuditPreviewActive)
+ await expect(activeRow).toBeVisible()
+ await expect(activeRow.locator("time")).toHaveAttribute("datetime", /^\d{4}-\d{2}-\d{2}T/)
+ await expect(activeRow.getByText("running", { exact: true })).toBeVisible()
+ await expect(activeRow.locator('[aria-hidden="true"]')).toHaveCount(3)
+ await expect(activeRow.locator(".bg-linear-to-r")).toHaveCount(0)
+ await expect(preview).toHaveClass(/bot-audit-active-heartbeat/)
+ await expect.poll(() => preview.evaluate((element) =>
+ getComputedStyle(element, "::before").animationName))
+ .toBe("bot-audit-heartbeat")
+ await expect(alice.page.locator('[data-testid^="community-bot-audit-preview-row-"]'))
+ .toHaveCount(4)
+
+ await alice.page.setViewportSize({ width: 375, height: 812 })
+ const ownerLink = alice.page.getByTestId(tid.profileOwnerLink)
+ await expect(alice.page.getByTestId(tid.profileBotBadge)).toContainText("Bot")
+ await expect(ownerLink).toBeVisible()
+ const ownerLinkBox = await ownerLink.boundingBox()
+ expect(ownerLinkBox?.height).toBeGreaterThanOrEqual(44)
+ const ownerHandle = await ownerLink.textContent()
+ await ownerLink.click()
+ await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(1)
+ await expect(alice.page.getByTestId(tid.profileOwnerLink)).toHaveCount(0)
+ await expect(alice.page.getByTestId(tid.profileCard))
+ .toContainText(ownerHandle!.trim().replace(/^@/, ""))
+
+ await alice.page.mouse.click(4, 4)
+ await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(0)
+ await alice.page.setViewportSize({ width: 1280, height: 900 })
+ await openBotProfile(alice.page, botName)
+ await expect(alice.page.getByTestId(tid.botAuditPreviewDock)).toHaveAttribute(
+ "data-placement",
+ /^(right|left|top|bottom)$/,
+ )
+ await alice.page.getByTestId(tid.botAuditPreview).click()
+ await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}$`))
+ await expect(alice.page.getByTestId("bot-activity-modal")).toBeVisible()
+ await alice.page.reload()
+ await expect(alice.page.getByTestId("bot-activity-modal")).toBeVisible()
+ await alice.page.goBack({ waitUntil: "commit" })
+ await expect(alice.page).toHaveURL(new RegExp(`${route}$`))
+ await alice.page.goForward({ waitUntil: "commit" })
+ await expect(alice.page.getByTestId("bot-activity-modal")).toBeVisible()
+
+ await alice.page.goto(`/c/me/bots?machineId=${machineId}&audit=${botId}`)
+ await expect(alice.page.getByTestId("bot-activity-modal")).toBeVisible()
+ await alice.page.getByRole("button", { name: "Close", exact: true }).click()
+ await expect(alice.page).toHaveURL(`/c/me/bots?machineId=${machineId}`)
+
+ const bob = await asUser("bob")
+ const bobAuditRequests: string[] = []
+ bob.page.on("request", (request) => {
+ if (new URL(request.url()).pathname === `/api/community/bots/${botId}/audit-log`) {
+ bobAuditRequests.push(request.url())
+ }
+ })
+ await gotoAfterUserWsAuth(bob.page, route)
+ await openBotProfile(bob.page, botName)
+ await expect(bob.page.getByTestId(tid.profileOwnerLink)).toBeVisible()
+ await expect(bob.page.getByTestId(tid.botAuditPreview)).toHaveCount(0)
+ expect(bobAuditRequests).toEqual([])
+ await bob.page.getByTestId(tid.profileOwnerLink).click()
+ await expect(bob.page.getByTestId(tid.profileCard)).toHaveCount(1)
+ await expect(bob.page.getByTestId(tid.profileOwnerLink)).toHaveCount(0)
+
+ await bob.page.goto(`/c/me/bots?audit=${botId}`)
+ await expect(bob.page.getByTestId("bot-activity-modal")).toHaveCount(0)
+ await expect.poll(() => new URL(bob.page.url()).searchParams.has("audit")).toBe(false)
+ expect(bobAuditRequests).toEqual([])
+ } finally {
+ machine.socket.close()
+ }
+})
diff --git a/src/web/src/test/e2e-ui/_setup/paths.ts b/src/web/src/test/e2e-ui/_setup/paths.ts
index 353983a03..fc5a60496 100644
--- a/src/web/src/test/e2e-ui/_setup/paths.ts
+++ b/src/web/src/test/e2e-ui/_setup/paths.ts
@@ -10,4 +10,38 @@ export const MANIFEST_PATH = resolve(AUTH_DIR, "manifest.json")
export const SERVICE_LOG_DIR = resolve(REPO_ROOT, "src/web/e2e-service-logs")
export const WEB_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000"
-export const WS_URL = process.env.DEV_WS_DO_URL || "http://localhost:8789"
+
+export function resolveWsUrl({
+ webUrl,
+ explicitWsUrl,
+ singleRuntime,
+}: {
+ webUrl: string
+ explicitWsUrl?: string
+ singleRuntime: boolean
+}): string {
+ if (explicitWsUrl) return explicitWsUrl
+ return singleRuntime ? webUrl : "http://localhost:8789"
+}
+
+export function resolveMachineWsUrl({
+ wsUrl,
+ singleRuntime,
+}: {
+ wsUrl: string
+ singleRuntime: boolean
+}): string {
+ const baseUrl = wsUrl.replace(/\/$/, "")
+ return singleRuntime ? `${baseUrl}/api/ws/community-machine` : baseUrl
+}
+
+export const WS_URL = resolveWsUrl({
+ webUrl: WEB_URL,
+ explicitWsUrl: process.env.DEV_WS_DO_URL,
+ singleRuntime: !!process.env.CI,
+})
+
+export const MACHINE_WS_URL = resolveMachineWsUrl({
+ wsUrl: WS_URL,
+ singleRuntime: !!process.env.CI,
+})