Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
Show bot marks in profile note (#706)
Gustavo Ye23bd363631a2
diff --git a/src/web/src/app/api/community/bots/[id]/marks/route.test.ts b/src/web/src/app/api/community/bots/[id]/marks/route.test.tsnew file mode 100644index 000000000..a927a1b77--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/marks/route.test.ts@@ -0,0 +1,219 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"++const getBotOwnedBy = vi.fn()+const listMarksForUser = vi.fn()+const getChannelsByIds = vi.fn()+const getServersByIds = vi.fn()++vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ communityBot: { getBotOwnedBy: (...args: unknown[]) => getBotOwnedBy(...args) },+ communityMessageMark: {+ listMarksForUser: (...args: unknown[]) => listMarksForUser(...args),+ },+ communityChannel: {+ getChannelsByIds: (...args: unknown[]) => getChannelsByIds(...args),+ },+ communityServer: {+ getServersByIds: (...args: unknown[]) => getServersByIds(...args),+ },+ },+ }+})++let isAuthed = true+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: any) => async (req: any, ctx?: any) => {+ if (!isAuthed) {+ const { NextResponse } = require("next/server")+ return NextResponse.json({ error: "unauthorized" }, { status: 401 })+ }+ return handler(req, {+ env: { DB: {} },+ userId: "owner_1",+ params: await ctx?.params,+ })+ },+}))+vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server")+ return {+ writeJSON: (data: unknown) => NextResponse.json(data),+ writeError: (message: string, status: number) =>+ NextResponse.json({ error: message }, { status }),+ }+})++import { GET } from "./route"++const request = () => new NextRequest("http://localhost/api/community/bots/bot_1/marks")+const context = () => ({ params: Promise.resolve({ id: "bot_1" }) }) as any++describe("GET /api/community/bots/[id]/marks", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ isAuthed = true+ getBotOwnedBy.mockResolvedValue({ id: "bot_1", ownerUserId: "owner_1" })+ listMarksForUser.mockResolvedValue([])+ getChannelsByIds.mockResolvedValue([])+ getServersByIds.mockResolvedValue([])+ })++ it("returns 401 before reading bot ownership or marks", async () => {+ isAuthed = false+ const response = await GET(request(), context())++ expect(response.status).toBe(401)+ expect(getBotOwnedBy).not.toHaveBeenCalled()+ expect(listMarksForUser).not.toHaveBeenCalled()+ })++ it("returns owner-scoped 404 before reading another bot's marks", async () => {+ getBotOwnedBy.mockResolvedValue(null)+ const response = await GET(request(), context())++ expect(response.status).toBe(404)+ expect(getBotOwnedBy).toHaveBeenCalledWith(expect.anything(), "bot_1", "owner_1")+ expect(listMarksForUser).not.toHaveBeenCalled()+ })++ it("returns an empty queue without resolving channel or server metadata", async () => {+ const response = await GET(request(), context())++ expect(response.status).toBe(200)+ expect(getChannelsByIds).not.toHaveBeenCalled()+ expect(getServersByIds).not.toHaveBeenCalled()+ await expect(response.json()).resolves.toEqual({ marked: [] })+ })++ it("returns the bot's direct mark queue with a four-row preview limit", async () => {+ listMarksForUser.mockResolvedValue([+ {+ mark: { id: "mark_1", channelId: "channel_1" },+ message: {+ id: "message_1",+ content: "Ship the sticker",+ seq: 42,+ createdAt: "2026-09-04T00:00:00.000Z",+ },+ author: {+ id: "author_1",+ name: "Gus",+ image: null,+ avatarVersion: 0,+ },+ },+ ])+ getChannelsByIds.mockResolvedValue([+ { id: "channel_1", name: "ship-room", serverId: "server_1", parentChannelId: null },+ ])+ getServersByIds.mockResolvedValue([{ id: "server_1", name: "Alook" }])+ const response = await GET(request(), context())++ expect(response.status).toBe(200)+ expect(listMarksForUser).toHaveBeenCalledWith(expect.anything(), "bot_1", { limit: 4 })+ expect(getChannelsByIds).toHaveBeenCalledWith(expect.anything(), ["channel_1"])+ expect(getServersByIds).toHaveBeenCalledWith(expect.anything(), ["server_1"])+ await expect(response.json()).resolves.toEqual({+ marked: [{+ id: "mark_1",+ server: "Alook",+ serverId: "server_1",+ channel: "ship-room",+ channelId: "channel_1",+ parentChannelId: null,+ m: {+ id: "message_1",+ authorId: "author_1",+ authorName: "Gus",+ authorAvatar: "G",+ authorAvatarVersion: 0,+ content: "Ship the sticker",+ seq: 42,+ createdAt: "2026-09-04T00:00:00.000Z",+ },+ }],+ })+ })++ it("returns an empty location suffix for a DM without a channel name", async () => {+ listMarksForUser.mockResolvedValue([{+ mark: { id: "dm_mark", channelId: "dm_channel" },+ message: {+ id: "dm_message",+ content: "Follow up in DM",+ seq: 3,+ createdAt: "2026-09-04T00:00:00.000Z",+ },+ author: {+ id: "author_1",+ name: "Gus",+ image: null,+ avatarVersion: 0,+ },+ }])+ getChannelsByIds.mockResolvedValue([{+ id: "dm_channel",+ name: null,+ serverId: null,+ parentChannelId: null,+ }])++ const response = await GET(request(), context())++ expect(response.status).toBe(200)+ expect(getServersByIds).not.toHaveBeenCalled()+ await expect(response.json()).resolves.toMatchObject({+ marked: [{+ id: "dm_mark",+ server: "",+ serverId: null,+ channel: "",+ channelId: "dm_channel",+ }],+ })+ })++ it("keeps a persisted mark after the bot loses channel access", async () => {+ listMarksForUser.mockResolvedValue([{+ mark: { id: "stale_mark", channelId: "former_channel" },+ message: {+ id: "stale_message",+ content: "Follow up after leaving",+ seq: 7,+ createdAt: "2026-09-03T00:00:00.000Z",+ },+ author: {+ id: "author_2",+ name: "Former teammate",+ image: null,+ avatarVersion: 0,+ },+ }])+ getChannelsByIds.mockResolvedValue([{+ id: "former_channel",+ name: "private-history",+ serverId: "former_server",+ parentChannelId: null,+ }])+ getServersByIds.mockResolvedValue([{ id: "former_server", name: "Past room" }])++ const response = await GET(request(), context())++ expect(response.status).toBe(200)+ expect(listMarksForUser).toHaveBeenCalledWith(expect.anything(), "bot_1", { limit: 4 })+ await expect(response.json()).resolves.toMatchObject({+ marked: [{+ id: "stale_mark",+ server: "Past room",+ channel: "private-history",+ m: { content: "Follow up after leaving" },+ }],+ })+ })+})diff --git a/src/web/src/app/api/community/bots/[id]/marks/route.ts b/src/web/src/app/api/community/bots/[id]/marks/route.tsnew file mode 100644index 000000000..5dc26a13f--- /dev/null+++ b/src/web/src/app/api/community/bots/[id]/marks/route.ts@@ -0,0 +1,57 @@+import type { NextRequest } from "next/server"+import { queries } from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAuth } from "@/lib/middleware/auth"+import { writeError, writeJSON } from "@/lib/middleware/helpers"+import { avatarInitial } from "@/lib/community/avatar"+import { canonicalUserImage } from "@/lib/community/storage"++const PREVIEW_LIMIT = 4++export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const botId = ctx.params?.id as string+ const db = getDb(ctx.env.DB)+ const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)+ if (!bot) return writeError("bot not found", 404)++ const rows = await queries.communityMessageMark.listMarksForUser(db, botId, {+ limit: PREVIEW_LIMIT,+ })+ const channelIds = [...new Set(rows.map(({ mark }) => mark.channelId))]+ const channels = channelIds.length > 0+ ? await queries.communityChannel.getChannelsByIds(db, channelIds)+ : []+ const serverIds = [...new Set(channels.flatMap((channel) =>+ channel.serverId ? [channel.serverId] : []))]+ const servers = serverIds.length > 0+ ? await queries.communityServer.getServersByIds(db, serverIds)+ : []+ const channelsById = new Map(channels.map((channel) => [channel.id, channel]))+ const serversById = new Map(servers.map((server) => [server.id, server]))++ return writeJSON({+ marked: rows.map(({ mark, message, author }) => {+ const channel = channelsById.get(mark.channelId)+ const server = channel ? serversById.get(channel.serverId) : undefined+ return {+ id: mark.id,+ server: server?.name ?? "",+ serverId: channel?.serverId ?? null,+ channel: channel?.name ?? "",+ channelId: mark.channelId,+ parentChannelId: channel?.parentChannelId ?? null,+ m: {+ id: message.id,+ authorId: author.id,+ authorName: author.name,+ authorAvatar: canonicalUserImage(author.id, author.image, author.avatarVersion)+ ?? avatarInitial(author.name),+ authorAvatarVersion: author.avatarVersion,+ content: message.content,+ seq: message.seq,+ createdAt: message.createdAt,+ },+ }+ }),+ })+})diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 49f4a1387..93c770724 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -1726,6 +1726,24 @@ body.community-onboarding-active.driver-active :is(background: var(--muted-foreground);}+/* The yellow bot note owns its ink palette; app theme borders read muddy here. */+.bot-note-scrollbar {+ scrollbar-color: #8a6116 transparent;+}++.bot-note-scrollbar:hover {+ scrollbar-color: #5f410c transparent;+}++.bot-note-scrollbar::-webkit-scrollbar-thumb {+ background: #8a6116;+}++.bot-note-scrollbar:hover::-webkit-scrollbar-thumb,+.bot-note-scrollbar::-webkit-scrollbar-thumb:hover {+ background: #5f410c;+}+.scrollbar-none::-webkit-scrollbar {display: none;}diff --git a/src/web/src/components/community/social/bot-audit-preview.tsx b/src/web/src/components/community/social/bot-audit-preview.tsxindex 1467689f7..baad7291a 100644--- a/src/web/src/components/community/social/bot-audit-preview.tsx+++ b/src/web/src/components/community/social/bot-audit-preview.tsx@@ -9,6 +9,7 @@ import {import { Activity, ChevronRight, Lock } from "lucide-react"import { useEffect, useState } from "react"import { useBotAuditPreview } from "@/hooks/community/use-bot-audit-preview"+import type { AuditEvent } from "@/hooks/community/use-bot-audit-log"import {formatAuditPreviewTime,summarizeAuditEvent,@@ -16,6 +17,10 @@ import {import { tid } from "@/lib/community/testids"type StatusPair = { emoji: string; text: string }+type BotAuditTone = "default" | "note"++const BOT_NOTE_ROW_CLASS = "grid min-h-5 shrink-0 grid-cols-[3.25rem_minmax(0,1fr)] items-center gap-2 px-[2px] text-xs leading-5"+const BOT_NOTE_TIME_CLASS = "whitespace-nowrap font-mono text-[10px] tabular-nums text-black"function matchesStatus(emoji: string | null | undefined,@@ -89,39 +94,88 @@ export function BotAuditPreview({</span><ChevronRight className="size-3.5 shrink-0 text-muted-foreground" aria-hidden /></div>- <div className="flex flex-col py-1">- {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>+ <BotAuditTimeline+ events={visibleEvents}+ isLoading={isLoading}+ isError={isError}+ active={active}+ /></button>)}-function ActiveRow({ latestEventAt }: { latestEventAt?: string }) {+export function BotAuditTimeline({+ events,+ isLoading,+ isError,+ active,+ tone = "default",+ showEarlier = false,+}: {+ events: Array<Pick<AuditEvent, "id" | "kind" | "payload" | "createdAt">>+ isLoading: boolean+ isError: boolean+ active: boolean+ tone?: BotAuditTone+ showEarlier?: boolean+}) {+ return (+ <div className={tone === "note" ? "flex flex-col pt-1" : "flex flex-col py-1"}>+ {showEarlier && (+ <div+ data-testid={tid.botAuditPreviewEarlier}+ aria-label="Earlier activity omitted"+ className={tone === "note"+ ? "flex min-h-5 shrink-0 items-center px-[2px] text-left text-sm font-semibold leading-5 text-black"+ : "flex min-h-5 shrink-0 items-center px-3 text-left text-sm font-semibold leading-5 text-black"}+ >+ …+ </div>+ )}+ {isLoading ? (+ <PreviewSkeleton />+ ) : isError ? (+ <PreviewStateRow label="Activity unavailable" tone={tone} />+ ) : events.length > 0 ? (+ events.map((event) => (+ <div+ key={event.id}+ data-testid={tid.botAuditPreviewRow(event.id)}+ className={tone === "note"+ ? BOT_NOTE_ROW_CLASS+ : "grid h-6 grid-cols-[3.25rem_minmax(0,1fr)] items-center gap-2 px-3 text-xs"}+ >+ <time+ dateTime={event.createdAt}+ className={tone === "note"+ ? BOT_NOTE_TIME_CLASS+ : "font-mono text-[10px] tabular-nums text-muted-foreground/70"}+ >+ {formatAuditPreviewTime(event.createdAt)}+ </time>+ <span className={tone === "note"+ ? "truncate font-mono text-xs leading-5 text-black"+ : "truncate text-muted-foreground"}+ >+ {summarizeAuditEvent(event)}+ </span>+ </div>+ ))+ ) : (+ <PreviewStateRow label="No recent activity" tone={tone} />+ )}+ {active && <BotAuditActiveRow latestEventAt={events.at(-1)?.createdAt} tone={tone} />}+ </div>+ )+}++export function BotAuditActiveRow({+ latestEventAt,+ tone = "default",+}: {+ latestEventAt?: string+ tone?: BotAuditTone+}) {const [nowMs, setNowMs] = useState(Date.now)useEffect(() => {@@ -145,22 +199,28 @@ function ActiveRow({ latestEventAt }: { latestEventAt?: string }) {return (<divdata-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"+ className={tone === "note"+ ? `${BOT_NOTE_ROW_CLASS} motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 motion-safe:duration-200 motion-reduce:animate-none`+ : "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"}><timedateTime={displayedAt}suppressHydrationWarning- className="font-mono text-[10px] tabular-nums text-muted-foreground/70"+ className={tone === "note"+ ? BOT_NOTE_TIME_CLASS+ : "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>+ <span className={tone === "note" ? "mr-1 text-xs text-black" : "mr-1 text-xs text-primary/70"}>running</span>{[0, 1, 2].map((index) => (<spankey={index}aria-hidden- className="size-1.5 rounded-full bg-primary motion-safe:animate-pulse motion-reduce:animate-none"+ className={tone === "note"+ ? "size-1.5 rounded-full bg-black motion-safe:animate-pulse motion-reduce:animate-none"+ : "size-1.5 rounded-full bg-primary motion-safe:animate-pulse motion-reduce:animate-none"}style={{ animationDelay: `${index * 160}ms` }}/>))}@@ -182,9 +242,12 @@ function PreviewSkeleton() {)}-function PreviewStateRow({ label }: { label: string }) {+function PreviewStateRow({ label, tone }: { label: string; tone: BotAuditTone }) {return (- <div className="flex min-h-0 flex-1 items-center justify-center px-4 text-xs text-muted-foreground">+ <div className={tone === "note"+ ? "flex min-h-0 flex-1 items-center justify-center px-4 text-xs text-black"+ : "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/bot-mark-sticker.test.ts b/src/web/src/components/community/social/bot-mark-sticker.test.tsnew file mode 100644index 000000000..3287bb8a0--- /dev/null+++ b/src/web/src/components/community/social/bot-mark-sticker.test.ts@@ -0,0 +1,379 @@+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: {+ marks: [] as Array<any>,+ isLoading: false,+ isError: false,+ isNotFound: false,+ },+ activity: {+ events: [] as Array<any>,+ isLoading: false,+ isError: false,+ isNotFound: false,+ hasEarlierEvents: false,+ },+ scrollNode: { scrollHeight: 300, scrollTop: 0, clientHeight: 100 },+ bottomAnchor: { scrollIntoView: vi.fn() },+}))++vi.mock("@/hooks/community/use-bot-marks", () => ({+ useBotMarks: () => mocks.result,+}))+vi.mock("@/hooks/community/use-bot-audit-preview", () => ({+ useBotAuditPreview: () => mocks.activity,+}))+vi.mock("../avatar", () => ({+ Avatar: ({ label }: { label: string }) => React.createElement("avatar", { label }),+}))+vi.mock("lucide-react", () => ({+ Activity: "activity-icon",+ ChevronRight: "chevron-icon",+ CircleStop: "stop-icon",+ ListTodo: "list-icon",+ LoaderCircle: "loader-icon",+ Lock: "lock-icon",+ Square: "square-icon",+}))++import { BotMarkSticker } from "./bot-mark-sticker"++const globalCss = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")++const mark = (id: string, content = `Task ${id}`) => ({+ id,+ server: "Alook",+ serverId: "server_1",+ channel: "planning",+ channelId: "channel_1",+ m: {+ id: `message_${id}`,+ authorId: "author_1",+ authorName: "Gus",+ authorAvatar: "G",+ content,+ createdAt: "2026-09-04T00:00:00.000Z",+ },+})++function render(overrides: Partial<React.ComponentProps<typeof BotMarkSticker>> = {}) {+ let renderer!: TestRenderer.ReactTestRenderer+ const props = {+ botId: "bot_1",+ active: false,+ showStop: false,+ stopPending: false,+ onStop: vi.fn(),+ onOpenActivity: vi.fn(),+ ...overrides,+ }+ act(() => {+ renderer = TestRenderer.create(React.createElement(BotMarkSticker, props), {+ createNodeMock: (element) => {+ if (element.props["data-testid"] === "community-bot-audit-preview-scroll") {+ return mocks.scrollNode+ }+ if (element.props["data-testid"] === "community-bot-audit-preview-bottom") {+ return mocks.bottomAnchor+ }+ return null+ },+ })+ })+ return { renderer, props }+}++describe("BotMarkSticker", () => {+ beforeEach(() => {+ mocks.result = { marks: [], isLoading: false, isError: false, isNotFound: false }+ mocks.activity = {+ events: [],+ isLoading: false,+ isError: false,+ isNotFound: false,+ hasEarlierEvents: false,+ }+ mocks.scrollNode.scrollHeight = 300+ mocks.scrollNode.scrollTop = 0+ mocks.scrollNode.clientHeight = 100+ mocks.bottomAnchor.scrollIntoView.mockReset()+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ callback(0)+ return 1+ })+ vi.stubGlobal("cancelAnimationFrame", vi.fn())+ })++ afterEach(() => vi.unstubAllGlobals())++ it("defaults to recent activity inside a stable note shell", () => {+ const { renderer, props } = render()+ expect(renderer.toJSON()).not.toBeNull()+ expect(JSON.stringify(renderer.toJSON())).toContain("Bot log")+ expect(JSON.stringify(renderer.toJSON())).not.toContain("Bot note")+ const title = renderer.root.find((node) => node.children.includes("Bot log"))+ expect(title.props.className).toContain("font-bold")+ expect(title.props.className).toContain("font-brand")+ const activityTab = renderer.root.findByProps({ role: "tab", "aria-selected": true })+ expect(activityTab.children).toContainEqual(expect.objectContaining({ type: "activity-icon" }))+ expect(JSON.stringify(renderer.toJSON())).toContain("Recent activity")+ expect(JSON.stringify(renderer.toJSON())).toContain("Ready when you are")+ const activityPanel = renderer.root.findByProps({+ "aria-label": "Recent activity log",+ })+ expect(activityPanel.type).toBe("div")+ expect(activityPanel.props.onClick).toBeUndefined()+ expect(activityPanel.props.className).not.toContain("overflow-hidden")+ expect(activityPanel.props.className).not.toContain("rounded-xl")+ expect(activityPanel.props.className).not.toContain("overflow-y-auto")+ expect(activityPanel.props.className).not.toContain("px-1")+ const activityScroller = activityPanel.find((node) =>+ node.props.className?.includes("bot-note-scrollbar"))+ expect(activityScroller.props.className).toContain("overflow-x-hidden")+ expect(activityScroller.props.className).toContain("overflow-y-auto")+ const stream = renderer.root.findByProps({+ "data-testid": "community-bot-audit-preview-bottom",+ })+ expect(stream.props.className).toContain("min-h-full")+ expect(stream.props.className).toContain("justify-end")+ const loadMore = renderer.root.findByProps({+ "aria-label": "Load more activity in the full audit log",+ })+ expect(loadMore.type).toBe("button")+ expect(loadMore.children).toContain("Load more")+ expect(loadMore.props.className).not.toContain("border")+ expect(loadMore.props.className).not.toContain("shadow")+ expect(loadMore.props.className).toContain("hover:bg-black/10")+ act(() => loadMore.props.onClick())+ expect(props.onOpenActivity).toHaveBeenCalledOnce()+ expect(globalCss).toContain(".bot-note-scrollbar")+ expect(globalCss).toContain("scrollbar-color: #8a6116 transparent")+ expect(globalCss).toMatch(+ /\.bot-note-scrollbar:hover\s*\{\s*scrollbar-color: #5f410c transparent;/,+ )+ })++ it("uses regular black ink for activity log content", () => {+ mocks.activity.events = [{+ id: "event_1",+ kind: "cli_invocation",+ payload: { subcommand: "inboxPull" },+ createdAt: "2026-09-04T00:00:00.000Z",+ }]+ mocks.activity.hasEarlierEvents = true+ const { renderer } = render()+ const row = renderer.root.findByProps({+ "data-testid": "community-bot-audit-preview-row-event_1",+ })+ expect(row.props.className).toContain("min-h-5")+ expect(row.props.className).toContain("grid-cols-[3.25rem_minmax(0,1fr)]")+ expect(row.props.className).toContain("leading-5")+ expect(row.props.className).toContain("px-[2px]")+ expect(row.findByType("time").props.className).toContain("text-[10px]")+ expect(row.findByType("time").props.className).toContain("text-black")+ expect(row.findByType("time").props.className).toContain("whitespace-nowrap")+ const content = row.findByType("span")+ expect(content?.props.className).toContain("text-black")+ expect(content?.props.className).toContain("font-mono")+ expect(content?.props.className).toContain("text-xs")+ expect(content?.props.className).not.toContain("font-semibold")+ const earlier = renderer.root.findByProps({+ "data-testid": "community-bot-audit-preview-earlier",+ })+ expect(earlier.children).toEqual(["…"])+ expect(earlier.props.className).toContain("min-h-5")+ expect(earlier.props.className).toContain("leading-5")+ expect(earlier.props.className).toContain("px-[2px]")+ })++ it("anchors initial rows at the tail and only follows live rows when already near it", () => {+ const events = (start: number) => Array.from({ length: 10 }, (_, index) => ({+ id: `event_${start + index}`,+ kind: "tool_call",+ payload: { name: `Tool ${start + index}` },+ createdAt: `2026-09-04T00:00:${String(start + index).padStart(2, "0")}.000Z`,+ }))+ mocks.activity.events = events(0)+ mocks.activity.hasEarlierEvents = true+ const { renderer, props } = render()++ expect(mocks.bottomAnchor.scrollIntoView).toHaveBeenCalledWith({ block: "end" })+ expect(mocks.scrollNode.scrollTop).toBe(300)++ mocks.scrollNode.scrollTop = 0+ mocks.activity.events = events(1)+ act(() => renderer.update(React.createElement(BotMarkSticker, props)))+ expect(mocks.scrollNode.scrollTop).toBe(0)+ expect(renderer.root.findAll((node) =>+ node.props["data-testid"]?.startsWith("community-bot-audit-preview-row-")))+ .toHaveLength(10)+ expect(renderer.root.findAllByProps({+ "data-testid": "community-bot-audit-preview-row-event_0",+ })).toHaveLength(0)++ mocks.scrollNode.scrollTop = 130+ mocks.activity.events = events(2)+ act(() => renderer.update(React.createElement(BotMarkSticker, props)))+ expect(mocks.scrollNode.scrollTop).toBe(300)+ })++ it("retries initial tail anchoring when a data update cancels the first frame", () => {+ let frameId = 0+ const frames = new Map<number, FrameRequestCallback>()+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ frameId += 1+ frames.set(frameId, callback)+ return frameId+ })+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id))++ mocks.activity.events = [{+ id: "event_1",+ kind: "tool_call",+ payload: { name: "Tool 1" },+ createdAt: "2026-09-04T00:00:01.000Z",+ }]+ const { renderer, props } = render()++ mocks.activity.events = [{+ id: "event_2",+ kind: "tool_call",+ payload: { name: "Tool 2" },+ createdAt: "2026-09-04T00:00:02.000Z",+ }]+ act(() => renderer.update(React.createElement(BotMarkSticker, props)))++ const flushFrames = () => {+ const pending = [...frames.entries()]+ frames.clear()+ pending.forEach(([, callback]) => callback(0))+ }+ act(flushFrames)+ act(flushFrames)++ expect(mocks.bottomAnchor.scrollIntoView).toHaveBeenCalledOnce()+ expect(mocks.scrollNode.scrollTop).toBe(300)+ })++ it("shows up to three rich todo rows and a quiet overflow indicator", () => {+ mocks.result.marks = [+ mark("1", "**First** task"),+ mark("2"),+ mark("3"),+ mark("4"),+ ]+ const { renderer } = render()+ const marksTab = renderer.root.findAllByProps({ role: "tab" })[1]!+ act(() => marksTab.props.onClick())+ const rows = renderer.root.findAll((node) =>+ typeof node.props["data-testid"] === "string"+ && node.props["data-testid"].startsWith("community-bot-mark-sticker-row-"))++ expect(rows).toHaveLength(3)+ expect(JSON.stringify(renderer.toJSON())).toContain("First")+ expect(JSON.stringify(renderer.toJSON())).not.toContain("**First**")+ expect(JSON.stringify(renderer.toJSON())).toContain("Alook · #planning")+ expect(JSON.stringify(renderer.toJSON())).toContain("Gus")+ const messageContent = renderer.root.findAllByType("p")[0]!+ expect(messageContent.props.className).toContain("text-xs")+ expect(messageContent.props.className).toContain("leading-4")+ const overflow = renderer.root.findByProps({+ "data-testid": "community-bot-mark-sticker-overflow",+ })+ expect(overflow.props.role).toBe("status")+ expect(overflow.findByProps({ className: "sr-only" }).children).toEqual(["More marked work"])+ expect(renderer.root.findAllByType("square-icon")).toHaveLength(3)+ const location = renderer.root.findAllByProps({ title: "Alook · #planning" })[0]!+ const locationParts = location.findAllByType("span")+ expect(locationParts[0]?.props.className).toContain("flex-1")+ expect(locationParts[0]?.props.className).toContain("truncate")+ expect(locationParts[1]?.props.className).toBe("shrink-0")+ expect(locationParts[2]?.props.className).toContain("flex-1")+ expect(locationParts[2]?.props.className).toContain("truncate")+ })++ it("keeps the DM label fixed while truncating its channel independently", () => {+ mocks.result.marks = [{+ ...mark("dm"),+ server: "",+ serverId: null,+ channel: "a-very-long-direct-message-channel",+ }]+ const { renderer } = render()+ act(() => renderer.root.findAllByProps({ role: "tab" })[1]!.props.onClick())+ const location = renderer.root.findByProps({+ title: "DM · a-very-long-direct-message-channel",+ })+ const parts = location.findAllByType("span")+ expect(parts[0]?.props.className).toBe("shrink-0")+ expect(parts[2]?.props.className).toContain("flex-1")+ expect(parts[2]?.props.className).toContain("truncate")+ })++ it("shows only DM when the direct-message location has no suffix", () => {+ mocks.result.marks = [{+ ...mark("dm-empty"),+ server: "",+ serverId: null,+ channel: "Unknown",+ }]+ const { renderer } = render()+ act(() => renderer.root.findAllByProps({ role: "tab" })[1]!.props.onClick())+ const location = renderer.root.findByProps({ title: "DM" })+ const parts = location.findAllByType("span")+ expect(parts).toHaveLength(1)+ expect(parts[0]?.children).toEqual(["DM"])+ expect(JSON.stringify(renderer.toJSON())).not.toContain("Unknown")+ expect(JSON.stringify(renderer.toJSON())).not.toContain("·")+ })++ it("keeps only the Stop footer visible while running with no marks", () => {+ const onStop = vi.fn()+ const { renderer } = render({ active: true, showStop: true, onStop })+ expect(JSON.stringify(renderer.toJSON())).not.toContain("Marked work")+ const stop = renderer.root.findByProps({+ "data-testid": "community-bot-mark-sticker-stop",+ })+ expect(stop.props.disabled).toBe(false)+ expect(stop.props.className).toContain("bg-[#dc2626]")+ expect(stop.props.className).toContain("text-white")+ const activeRow = renderer.root.findByProps({+ "data-testid": "community-bot-audit-preview-active",+ })+ expect(activeRow.props.className).toContain("grid-cols-[3.25rem_minmax(0,1fr)]")+ expect(activeRow.props.className).toContain("px-[2px]")+ expect(activeRow.findByType("time").props.className).toContain("text-black")+ expect(activeRow.findAll((node) => node.props.className?.includes("bg-black")))+ .toHaveLength(3)+ act(() => stop.props.onClick())+ expect(onStop).toHaveBeenCalledOnce()+ })++ it("preserves only Stop during loading and disables it while pending", () => {+ mocks.result.isLoading = true+ const { renderer } = render({ showStop: true, stopPending: true })+ expect(JSON.stringify(renderer.toJSON())).not.toContain("Loading marked work")+ const stop = renderer.root.findByProps({+ "data-testid": "community-bot-mark-sticker-stop",+ })+ expect(stop.props.disabled).toBe(true)+ expect(stop.props["aria-label"]).toBe("Stopping current agent turn")+ expect(JSON.stringify(renderer.toJSON())).toContain("Stopping…")+ })++ it("keeps the shell stable across mark errors and preserves Stop", () => {+ mocks.result.isError = true+ expect(render().renderer.toJSON()).not.toBeNull()++ mocks.result.isNotFound = true+ const missing = render({ showStop: true }).renderer+ expect(JSON.stringify(missing.toJSON())).toContain("Recent activity")+ expect(missing.root.findByProps({+ "data-testid": "community-bot-mark-sticker-stop",+ })).toBeDefined()+ })+})diff --git a/src/web/src/components/community/social/bot-mark-sticker.tsx b/src/web/src/components/community/social/bot-mark-sticker.tsxnew file mode 100644index 000000000..fc06d5daa--- /dev/null+++ b/src/web/src/components/community/social/bot-mark-sticker.tsx@@ -0,0 +1,296 @@+"use client"++/* Hallmark · component: secondary-card · genre: playful · theme: Alook locked system+ * states: default · hover · focus · active · disabled · loading · error · success+ * contrast: verified in light and dark browser QA+ */++import { stripInlineMarkup } from "@alook/shared"+import { Activity, ChevronRight, CircleStop, ListTodo, LoaderCircle, Lock, Square } from "lucide-react"+import { useEffect, useLayoutEffect, useRef, useState } from "react"+import { useBotAuditPreview } from "@/hooks/community/use-bot-audit-preview"+import { useBotMarks } from "@/hooks/community/use-bot-marks"+import { formatRelativeTime } from "@/lib/community/format-time"+import { tid } from "@/lib/community/testids"+import { Avatar } from "../avatar"+import { BotAuditActiveRow, BotAuditTimeline } from "./bot-audit-preview"++const VISIBLE_MARKS = 3+type StickerView = "activity" | "marks"++function stickerTabClass(selected: boolean): string {+ return [+ "flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-[10px] px-2 text-xs font-medium text-[#4b3712] hover:text-black active:bg-[#dfb95d] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none dark:active:bg-[#b18432]",+ selected+ ? "bg-[#dfb75b] text-[#342a18] shadow-[inset_0_2px_4px_rgba(91,60,10,0.2),inset_0_-1px_0_#f3d989] dark:bg-[#b2822a]"+ : "",+ ].join(" ")+}++export function BotMarkSticker({+ botId,+ active,+ showStop,+ stopPending,+ onStop,+ onOpenActivity,+}: {+ botId: string+ active: boolean+ showStop: boolean+ stopPending: boolean+ onStop: () => void+ onOpenActivity: () => void+}) {+ const [view, setView] = useState<StickerView>("activity")+ const activityScrollRef = useRef<HTMLDivElement>(null)+ const activityBottomAnchorRef = useRef<HTMLDivElement>(null)+ const latestEventIdRef = useRef<string | undefined>(undefined)+ const didInitialTailScrollRef = useRef(false)+ const activity = useBotAuditPreview(botId)+ const { marks, isLoading, isError } = useBotMarks(botId)+ const visibleMarks = marks.slice(0, VISIBLE_MARKS)+ const hasOverflow = marks.length > VISIBLE_MARKS+ const visibleEvents = [...activity.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, 10)+ .reverse()+ const latestVisibleEventId = visibleEvents.at(-1)?.id++ useEffect(() => {+ if (view === "activity") return+ didInitialTailScrollRef.current = false+ latestEventIdRef.current = undefined+ }, [view])++ useEffect(() => {+ if (view !== "activity") return+ if (didInitialTailScrollRef.current) return+ if (visibleEvents.length === 0) return+ const anchor = activityBottomAnchorRef.current+ const scroller = activityScrollRef.current+ if (!anchor || !scroller) return+ let secondFrame = 0+ const firstFrame = requestAnimationFrame(() => {+ secondFrame = requestAnimationFrame(() => {+ anchor.scrollIntoView({ block: "end" })+ scroller.scrollTop = scroller.scrollHeight+ latestEventIdRef.current = latestVisibleEventId+ didInitialTailScrollRef.current = true+ })+ })+ return () => {+ cancelAnimationFrame(firstFrame)+ if (secondFrame) cancelAnimationFrame(secondFrame)+ }+ }, [activity.isLoading, latestVisibleEventId, view, visibleEvents.length])++ useLayoutEffect(() => {+ const previousLatestEventId = latestEventIdRef.current+ latestEventIdRef.current = latestVisibleEventId+ if (view !== "activity") return+ if (!didInitialTailScrollRef.current) return+ if (!latestVisibleEventId || latestVisibleEventId === previousLatestEventId) return+ const scroller = activityScrollRef.current+ if (!scroller) return+ const nearTail = scroller.scrollHeight - (scroller.scrollTop + scroller.clientHeight) < 80+ if (nearTail) scroller.scrollTop = scroller.scrollHeight+ }, [latestVisibleEventId, view])++ return (+ <section+ data-testid={tid.botMarkSticker}+ aria-label="Bot log"+ className="relative flex h-84 min-h-0 w-full flex-col overflow-hidden rounded-2xl border border-[#d3aa4c] bg-[#f6dc92] text-[#342a18] shadow-[0_16px_34px_rgba(76,54,15,0.18),3px_3px_0_#d5ac50,inset_0_1px_0_rgba(255,255,255,0.72)] sm:h-full dark:border-[#a77b26] dark:bg-[#d2a64b] dark:shadow-[0_18px_38px_rgba(0,0,0,0.38),3px_3px_0_#946b20,inset_0_1px_0_rgba(255,244,194,0.5)]"+ >+ <header className="flex shrink-0 items-center gap-2 px-4 pb-2 pt-3">+ <span className="font-brand text-2xl font-bold leading-none tracking-wide">Bot log</span>+ <span className="ml-auto flex items-center gap-1 whitespace-nowrap text-[10px] text-[#4b3712]">+ <Lock className="size-3" aria-hidden />+ Only you+ </span>+ </header>++ <div role="tablist" aria-label="Bot log view" className="mx-3 mb-1 flex h-9 shrink-0 items-center gap-1 rounded-xl bg-[#e8c56f] p-0.5 shadow-[inset_0_1px_3px_rgba(98,67,11,0.14)] dark:bg-[#bd913b]">+ <button+ type="button"+ role="tab"+ aria-label="Recent activity"+ aria-selected={view === "activity"}+ onClick={() => setView("activity")}+ className={stickerTabClass(view === "activity")}+ >+ <Activity className="size-3.5 shrink-0" aria-hidden />+ <span className="truncate">Activity</span>+ </button>+ <button+ type="button"+ role="tab"+ aria-label="Marked messages"+ aria-selected={view === "marks"}+ onClick={() => setView("marks")}+ className={stickerTabClass(view === "marks")}+ >+ <ListTodo className="size-3.5 shrink-0" aria-hidden />+ <span className="truncate">Marks</span>+ {marks.length > 0 && (+ <span+ data-testid={hasOverflow ? tid.botMarkStickerOverflow : undefined}+ role={hasOverflow ? "status" : undefined}+ className="font-mono text-[10px] tabular-nums"+ >+ {hasOverflow && <span className="sr-only">More marked work</span>}+ {hasOverflow ? "3+" : marks.length}+ </span>+ )}+ </button>+ </div>++ {view === "activity" ? (+ <div+ role="tabpanel"+ aria-label="Recent activity log"+ className="relative mx-3 mb-1 flex min-h-0 flex-1 flex-col pt-2 text-left"+ >+ <button+ type="button"+ onClick={onOpenActivity}+ aria-label="Load more activity in the full audit log"+ className="absolute right-2 top-2 z-10 flex h-6 items-center gap-0.5 rounded-lg px-2 text-[10px] font-semibold text-[#342a18] transition-colors hover:bg-black/10 active:bg-black/15 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"+ >+ Load more+ <ChevronRight className="size-3" aria-hidden />+ </button>+ <div+ ref={activityScrollRef}+ data-testid={tid.botAuditPreviewScroll}+ className="thin-scrollbar bot-note-scrollbar mt-8 min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain"+ >+ <div+ ref={activityBottomAnchorRef}+ data-testid={tid.botAuditPreviewBottom}+ className="flex min-h-full flex-col justify-end"+ >+ <BotAuditTimeline+ events={visibleEvents}+ isLoading={activity.isLoading}+ isError={activity.isError || activity.isNotFound}+ active={false}+ tone="note"+ showEarlier={activity.hasEarlierEvents}+ />+ </div>+ </div>+ </div>+ ) : (+ <div role="tabpanel" className="thin-scrollbar bot-note-scrollbar mx-3 mb-1 min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1">+ {isLoading ? (+ <StickerState label="Loading marked messages" />+ ) : isError ? (+ <StickerState label="Marked messages unavailable" />+ ) : visibleMarks.length === 0 ? (+ <StickerState label="No marked messages" />+ ) : (+ <div className="space-y-1 py-1">+ {visibleMarks.map((mark) => {+ const locationPrefix = mark.serverId ? mark.server : "DM"+ const normalizedLocationChannel = mark.channel.trim()+ const rawLocationChannel = !mark.serverId+ && normalizedLocationChannel.toLowerCase() === "unknown"+ ? ""+ : normalizedLocationChannel+ const locationChannel = rawLocationChannel+ ? (mark.serverId ? `#${rawLocationChannel}` : rawLocationChannel)+ : ""+ const location = locationChannel+ ? `${locationPrefix} · ${locationChannel}`+ : locationPrefix+ const content = stripInlineMarkup(mark.m.content ?? "").trim() || "Empty message"+ return (+ <div+ key={mark.id}+ data-testid={tid.botMarkStickerRow(mark.id)}+ className="grid min-h-20 grid-cols-[0.875rem_minmax(0,1fr)] items-start gap-2 rounded-xl px-2 py-2 transition-colors hover:bg-[#f9e7ad] dark:hover:bg-[#dcba63]"+ >+ <Square className="mt-1.5 size-3.5 shrink-0 text-[#9a741f]" strokeWidth={1.75} aria-hidden />+ <div className="min-w-0">+ <div className="flex min-w-0 items-start gap-2">+ <Avatar+ label={mark.m.authorAvatar || mark.m.authorName || "?"}+ seed={mark.m.authorId}+ size={28}+ />+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2 text-xs leading-4">+ <span className="min-w-0 flex-1 truncate font-semibold">+ {mark.m.authorName || "Unknown"}+ </span>+ {mark.m.createdAt && (+ <time dateTime={mark.m.createdAt} className="shrink-0 whitespace-nowrap font-mono text-[9px] tabular-nums text-[#4b3712]">+ {formatRelativeTime(mark.m.createdAt)}+ </time>+ )}+ </div>+ <div title={location} className="flex min-w-0 items-center gap-1 text-[10px] leading-4 text-[#4b3712]">+ <span className={mark.serverId ? "min-w-0 flex-1 truncate" : "shrink-0"}>+ {locationPrefix}+ </span>+ {locationChannel && (+ <>+ <span className="shrink-0" aria-hidden>·</span>+ <span className="min-w-0 flex-1 truncate">{locationChannel}</span>+ </>+ )}+ </div>+ </div>+ </div>+ <p className="mt-1 line-clamp-2 text-xs leading-4">+ {content}+ </p>+ </div>+ </div>+ )+ })}+ </div>+ )}+ </div>+ )}++ <footer className="flex h-9 shrink-0 items-center gap-1 px-3 py-1">+ {active ? (+ <div className="min-w-0 flex-1 overflow-hidden">+ <BotAuditActiveRow latestEventAt={visibleEvents.at(-1)?.createdAt} tone="note" />+ </div>+ ) : (+ <span className="min-w-0 flex-1 truncate px-1 font-brand text-base text-[#4b3712]">Ready when you are</span>+ )}+ {showStop && (+ <button+ type="button"+ data-testid={tid.botMarkStickerStop}+ onClick={onStop}+ disabled={stopPending}+ aria-label={stopPending ? "Stopping current agent turn" : "Stop current agent turn"}+ className="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-[#dc2626] px-2.5 text-xs font-semibold text-white shadow-[0_2px_5px_rgba(127,29,29,0.28)] transition-colors hover:bg-[#b91c1c] active:bg-[#991b1b] focus-visible:ring-2 focus-visible:ring-[#7f1d1d] focus-visible:ring-offset-1 focus-visible:outline-none disabled:cursor-wait disabled:bg-[#b91c1c] disabled:text-white/85"+ >+ {stopPending+ ? <LoaderCircle className="size-3.5 animate-spin motion-reduce:animate-none" aria-hidden />+ : <CircleStop className="size-3.5" aria-hidden />}+ {stopPending ? "Stopping…" : "Stop"}+ </button>+ )}+ </footer>+ </section>+ )+}++function StickerState({ label }: { label: string }) {+ return (+ <div className="flex h-full items-center justify-center px-4 text-xs text-[#4b3712]">+ {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.tsindex 9cdbd19ab..3db5727a4 100644--- a/src/web/src/components/community/social/profile-card.test.ts+++ b/src/web/src/components/community/social/profile-card.test.ts@@ -31,6 +31,31 @@ vi.mock("@/hooks/community/use-community-ws", () => ({communityWsInterruptAgent: mocks.interruptAgent,}))+vi.mock("./bot-mark-sticker", () => ({+ BotMarkSticker: ({+ showStop,+ stopPending,+ onStop,+ }: {+ showStop: boolean+ stopPending: boolean+ onStop: () => void+ }) => createElement(+ "section",+ { "data-testid": "community-bot-mark-sticker" },+ showStop+ ? createElement("button", {+ type: "button",+ onClick: onStop,+ disabled: stopPending,+ "aria-label": stopPending+ ? "Stopping current agent turn"+ : "Stop current agent turn",+ }, stopPending ? "Stopping…" : "Stop")+ : null,+ ),+}))+afterEach(() => {vi.useRealTimers()mocks.interruptAgent.mockReset()@@ -146,10 +171,10 @@ describe("ProfileCard contextual metadata", () => {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")+ expect(html).not.toContain("community-bot-mark-sticker")})- it("mounts the content-sized secondary preview only for the owning viewer", () => {+ it("mounts the mark sticker only for the owning viewer", () => {const html = renderProfile({identity: {kind: "bot",@@ -158,8 +183,7 @@ describe("ProfileCard contextual metadata", () => {},})- expect(html).toContain('data-testid="community-bot-audit-preview"')- expect(html).not.toContain("h-40")+ expect(html).toContain('data-testid="community-bot-mark-sticker"')})it("shows Stop only for the owner while the bot is truly running", () => {@@ -286,7 +310,9 @@ describe("ProfileCard contextual metadata", () => {expect(source).toContain('addEventListener("animationend", update)')expect(source).toContain("cardElement.offsetWidth")expect(source).toContain("previewElement.offsetWidth")- expect(source).toContain("onClick={interruptAgent}")+ expect(source).toContain("<BotMarkSticker")+ expect(source).toContain("onOpenActivity={() => onOpenBotAudit?.(data.userId!)}")+ expect(source).toContain("onStop={interruptAgent}")expect(source).toContain("communityWsInterruptAgent(data.userId)")})})diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsxindex d2b1b98b5..38742ac52 100644--- a/src/web/src/components/community/social/profile-card.tsx+++ b/src/web/src/components/community/social/profile-card.tsx@@ -1,7 +1,7 @@"use client"import { useEffect, useLayoutEffect, useRef, useState } from "react"-import { Bot, CircleStop, LoaderCircle, MessagesSquare, Shield, UserRound } from "lucide-react"+import { Bot, MessagesSquare, Shield, UserRound } from "lucide-react"import { BOT_ACTIVITY_PRESETS } from "@alook/shared"import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"import { Sheet, SheetClose, SheetContent, SheetTitle } from "@/components/ui/sheet"@@ -19,7 +19,8 @@ import { useCommunityProfile } from "@/stores/community/ws"import { avatarInitial } from "@/lib/community/avatar"import { tid } from "@/lib/community/testids"import { communityWsInterruptAgent } from "@/hooks/community/use-community-ws"-import { BotAuditPreview, isBotActivityActive, isBotActivityRunning } from "./bot-audit-preview"+import { isBotActivityActive, isBotActivityRunning } from "./bot-audit-preview"+import { BotMarkSticker } from "./bot-mark-sticker"// Live cards resolve status from the global profile map. Seed props are used// only by static, id-less showcase cards.@@ -93,6 +94,7 @@ type AuditPreviewPosition = {placement: AuditPreviewPlacementleft: number | stringtop: number+ height?: number}function clamp(value: number, min: number, max: number): number {@@ -152,16 +154,17 @@ function useAuditPreviewPosition(enabled: boolean, x: number, y: number) {window.innerWidth - margin - preview.width - card.left,)const next: AuditPreviewPosition = placement === "right"- ? { placement, left: card.width + gap, top: verticalOffset }+ ? { placement, left: card.width + gap, top: verticalOffset, height: card.height }: placement === "left"- ? { placement, left: -preview.width - gap, top: verticalOffset }+ ? { placement, left: -preview.width - gap, top: verticalOffset, height: card.height }: placement === "top"- ? { placement, left: horizontalOffset, top: -preview.height - gap }- : { placement, left: horizontalOffset, top: card.height + gap }+ ? { placement, left: horizontalOffset, top: -preview.height - gap, height: card.height }+ : { placement, left: horizontalOffset, top: card.height + gap, height: card.height }setPosition((current) => current.placement === next.placement&& current.left === next.left&& current.top === next.top+ && current.height === next.height? current: next)}@@ -246,9 +249,9 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdaconst presence = data.userId ? (globalProfile?.presence ?? "offline") : data.presenceconst mutual = data.mutual ?? 0const botIdentity = data.identity?.kind === "bot" ? data.identity : null- const showAuditPreview = Boolean(botIdentity?.ownedByViewer && data.userId)+ const showOwnedBotCard = Boolean(botIdentity?.ownedByViewer && data.userId)const { popoverRef, cardRef, previewRef, position: previewPosition } = useAuditPreviewPosition(- showAuditPreview && !mobile && !embedded,+ showOwnedBotCard && !mobile && !embedded,x,y,)@@ -429,29 +432,16 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpda</>)- const secondaryCards = showAuditPreview && data.userId ? (- <div className="flex w-full flex-col gap-2">- <BotAuditPreview- botId={data.userId}- active={isBotActivityActive(activityStatus.emoji, activityStatus.text)}- onOpen={() => onOpenBotAudit?.(data.userId!)}- />- {(isBotActivityRunning(activityStatus.emoji, activityStatus.text)- || (interruptPending && !activityIdle)) && (- <button- type="button"- onClick={interruptAgent}- disabled={interruptPending}- aria-label={interruptPending ? "Stopping current agent turn" : "Stop current agent turn"}- className="flex h-11 w-full items-center justify-center gap-2 rounded-xl border border-destructive/40 bg-card px-3 text-sm font-medium text-destructive shadow-(--e1) transition-colors hover:bg-destructive/10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-wait disabled:bg-destructive/5 disabled:text-destructive/70"- >- {interruptPending- ? <LoaderCircle className="size-4 animate-spin motion-reduce:animate-none" aria-hidden />- : <CircleStop className="size-4" aria-hidden />}- {interruptPending ? "Stopping…" : "Stop"}- </button>- )}- </div>+ const secondaryCards = showOwnedBotCard && data.userId ? (+ <BotMarkSticker+ botId={data.userId}+ active={isBotActivityActive(activityStatus.emoji, activityStatus.text)}+ showStop={isBotActivityRunning(activityStatus.emoji, activityStatus.text)+ || (interruptPending && !activityIdle)}+ stopPending={interruptPending}+ onStop={interruptAgent}+ onOpenActivity={() => onOpenBotAudit?.(data.userId!)}+ />) : nullif (embedded)@@ -504,7 +494,11 @@ export function ProfileCard({ data, x, y, bp, onClose, onMessage, isSelf, onUpdadata-testid={tid.botAuditPreviewDock}data-placement={previewPosition.placement}className="absolute w-full"- style={{ left: previewPosition.left, top: previewPosition.top }}+ style={{+ left: previewPosition.left,+ top: previewPosition.top,+ height: previewPosition.height,+ }}>{secondaryCards}</div>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.tsindex c3c384d9a..8ba9c9651 100644--- a/src/web/src/hooks/community/use-bot-audit-preview.test.ts+++ b/src/web/src/hooks/community/use-bot-audit-preview.test.ts@@ -76,15 +76,16 @@ describe("useBotAuditPreview", () => {renderers.clear()})- it("uses a separate finite limit=5 cache from the full modal", async () => {+ it("uses a separate finite limit=10 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",+ "/api/community/bots/b1/audit-log?limit=10",)expect(result.current.events.map((item) => item.id)).toEqual(["e1"])+ expect(result.current.hasEarlierEvents).toBe(false)expect(queryClient.getQueryData(communityKeys.botAuditPreview("b1"))).toBeDefined()expect(queryClient.getQueryData(communityKeys.botAuditLog("b1"))).toBeUndefined()})@@ -95,13 +96,13 @@ describe("useBotAuditPreview", () => {expect(apiFetch).not.toHaveBeenCalled()})- it("merges live events, deduplicates by id, orders newest first, and caps five", async () => {+ it("merges live events, deduplicates by id, orders newest first, and caps ten", async () => {apiFetch.mockResolvedValueOnce({- events: [event("e1", 1), event("e2", 2), event("e3", 3), event("e4", 4)],+ events: Array.from({ length: 9 }, (_, index) => event(`e${index + 1}`, index + 1)),nextCursor: null,})const { result } = renderHook("b1")- await waitFor(() => result.current.events.length === 4)+ await waitFor(() => result.current.events.length === 9)act(() => {useCommunityWsStore.getState().pushBotAuditEvent({@@ -109,11 +110,11 @@ describe("useBotAuditPreview", () => {botId: "b1",})useCommunityWsStore.getState().pushBotAuditEvent({- ...event("e5", 5),+ ...event("e10", 10),botId: "b1",})useCommunityWsStore.getState().pushBotAuditEvent({- ...event("e6", 6),+ ...event("e11", 11),botId: "b1",})})@@ -121,11 +122,27 @@ describe("useBotAuditPreview", () => {expect(result.current.events.map((item) => item.id)).toEqual(["e2",+ "e11",+ "e10",+ "e9",+ "e8",+ "e7","e6","e5","e4","e3",])+ expect(result.current.hasEarlierEvents).toBe(true)+ })++ it("reports a server cursor as earlier omitted activity", async () => {+ apiFetch.mockResolvedValueOnce({+ events: [event("e1", 1)],+ nextCursor: { beforeCreatedAt: "2026-01-01T00:00:01.000Z", beforeId: "e1" },+ })+ const { result } = renderHook("b1")+ await waitFor(() => result.current.events.length === 1)+ expect(result.current.hasEarlierEvents).toBe(true)})it("orders equal timestamps by descending event id", async () => {diff --git a/src/web/src/hooks/community/use-bot-audit-preview.ts b/src/web/src/hooks/community/use-bot-audit-preview.tsindex 1ae7325b8..c2770b494 100644--- a/src/web/src/hooks/community/use-bot-audit-preview.ts+++ b/src/web/src/hooks/community/use-bot-audit-preview.ts@@ -8,7 +8,7 @@ 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+const PREVIEW_LIMIT = 10export function useBotAuditPreview(botId: string | null | undefined) {const enabled = Boolean(botId)@@ -26,7 +26,7 @@ export function useBotAuditPreview(botId: string | null | undefined) {})const liveEvents = useBotAuditEventsForBot(botId)- const events = useMemo(() => {+ const preview = useMemo(() => {const byId = new Map<string, AuditEvent>()for (const event of query.data?.events ?? []) byId.set(event.id, event)for (const event of liveEvents) {@@ -39,16 +39,19 @@ export function useBotAuditPreview(botId: string | null | undefined) {createdAt: event.createdAt,})}- return [...byId.values()]+ const merged = [...byId.values()].sort((a, b) => {if (a.createdAt !== b.createdAt) return a.createdAt > b.createdAt ? -1 : 1return a.id > b.id ? -1 : a.id < b.id ? 1 : 0})- .slice(0, PREVIEW_LIMIT)+ return {+ events: merged.slice(0, PREVIEW_LIMIT),+ hasEarlierEvents: Boolean(query.data?.nextCursor) || merged.length > PREVIEW_LIMIT,+ }}, [liveEvents, query.data])return {- events,+ ...preview,isLoading: query.isLoading,isError: query.isError,isNotFound: query.error instanceof ApiError && query.error.status === 404,diff --git a/src/web/src/hooks/community/use-bot-marks.test.ts b/src/web/src/hooks/community/use-bot-marks.test.tsnew file mode 100644index 000000000..04fc1ea5b--- /dev/null+++ b/src/web/src/hooks/community/use-bot-marks.test.ts@@ -0,0 +1,97 @@+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 { useBotMarks } from "./use-bot-marks"++const apiFetch = vi.fn()+vi.mock("@/lib/api/client", () => ({+ apiFetch: (...args: unknown[]) => apiFetch(...args),+}))++type Result = ReturnType<typeof useBotMarks>+const renderers = new Set<TestRenderer.ReactTestRenderer>()++function createQueryClient() {+ return new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ })+}++function renderHook(botId: string | null, queryClient = createQueryClient()) {+ const result: { current: Result } = { current: null as never }+ function Probe() {+ result.current = useBotMarks(botId)+ return null+ }+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Probe),+ ),+ )+ })+ renderers.add(renderer)+ return { queryClient, renderer, result }+}++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)+}++describe("useBotMarks", () => {+ beforeEach(() => {+ apiFetch.mockReset()+ })++ afterEach(() => {+ act(() => {+ for (const renderer of renderers) renderer.unmount()+ })+ renderers.clear()+ })++ it("fetches the owned bot's mark queue and stays disabled without a bot id", async () => {+ apiFetch.mockResolvedValueOnce({+ marked: [{ id: "mark_1", m: { id: "message_1", content: "Ship it" } }],+ })+ const { result } = renderHook("bot_1")+ await waitFor(() => result.current.marks.length === 1)++ expect(apiFetch).toHaveBeenCalledWith("/api/community/bots/bot_1/marks")+ renderHook(null)+ expect(apiFetch).toHaveBeenCalledTimes(1)+ })++ it("reports owner-gate 404s without retrying", async () => {+ apiFetch.mockRejectedValueOnce(new ApiError("not found", 404))+ const { result } = renderHook("bot_1")+ await waitFor(() => result.current.isNotFound)++ expect(apiFetch).toHaveBeenCalledTimes(1)+ })++ it("refetches the authoritative queue whenever the profile remounts", async () => {+ apiFetch.mockResolvedValue({ marked: [] })+ const queryClient = createQueryClient()+ const first = renderHook("bot_1", queryClient)+ await waitFor(() => apiFetch.mock.calls.length === 1 && !first.result.current.isLoading)++ act(() => first.renderer.unmount())+ renderers.delete(first.renderer)+ renderHook("bot_1", queryClient)+ await waitFor(() => apiFetch.mock.calls.length === 2)++ expect(apiFetch).toHaveBeenNthCalledWith(2, "/api/community/bots/bot_1/marks")+ })+})diff --git a/src/web/src/hooks/community/use-bot-marks.ts b/src/web/src/hooks/community/use-bot-marks.tsnew file mode 100644index 000000000..2777db3c4--- /dev/null+++ b/src/web/src/hooks/community/use-bot-marks.ts@@ -0,0 +1,29 @@+"use client"++import { useQuery } from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"+import { ApiError } from "@/lib/errors"+import { communityKeys } from "@/lib/query-keys"+import type { Marked } from "@/lib/community/models/inbox"++type BotMarksResponse = { marked: Marked[] }++export function useBotMarks(botId: string | null | undefined) {+ const enabled = Boolean(botId)++ const query = useQuery<BotMarksResponse>({+ enabled,+ queryKey: botId ? communityKeys.botMarks(botId) : ["disabled-bot-marks"],+ queryFn: () => apiFetch<BotMarksResponse>(`/api/community/bots/${botId}/marks`),+ retry: (failureCount, error) =>+ !(error instanceof ApiError && error.status === 404) && failureCount < 1,+ refetchOnMount: "always",+ })++ return {+ marks: query.data?.marked ?? [],+ isLoading: query.isLoading,+ isError: query.isError,+ isNotFound: query.error instanceof ApiError && query.error.status === 404,+ }+}diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.tsindex e5dc29fd4..eaf1f19ed 100644--- a/src/web/src/lib/community/testids.test.ts+++ b/src/web/src/lib/community/testids.test.ts@@ -45,6 +45,10 @@ describe("community QA selectors", () => {expect(tid.botAuditPreviewRow("event_1")).toBe("community-bot-audit-preview-row-event_1",)+ expect(tid.botMarkSticker).toBe("community-bot-mark-sticker")+ expect(tid.botMarkStickerRow("mark_1")).toBe("community-bot-mark-sticker-row-mark_1")+ expect(tid.botMarkStickerOverflow).toBe("community-bot-mark-sticker-overflow")+ expect(tid.botMarkStickerStop).toBe("community-bot-mark-sticker-stop")})it("exposes stable composer and message-list surfaces", () => {diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex beab28b98..6819d2870 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -52,8 +52,15 @@ export const tid = {botAuditPreview: "community-bot-audit-preview",botAuditPreviewDock: "community-bot-audit-preview-dock",botAuditPreviewActive: "community-bot-audit-preview-active",+ botAuditPreviewEarlier: "community-bot-audit-preview-earlier",+ botAuditPreviewScroll: "community-bot-audit-preview-scroll",+ botAuditPreviewBottom: "community-bot-audit-preview-bottom",botActivityModal: "bot-activity-modal",botAuditPreviewRow: (id: string) => `community-bot-audit-preview-row-${id}`,+ botMarkSticker: "community-bot-mark-sticker",+ botMarkStickerRow: (id: string) => `community-bot-mark-sticker-row-${id}`,+ botMarkStickerOverflow: "community-bot-mark-sticker-overflow",+ botMarkStickerStop: "community-bot-mark-sticker-stop",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.tsindex 48b7d3072..a1bd3d7cd 100644--- a/src/web/src/lib/query-keys.test.ts+++ b/src/web/src/lib/query-keys.test.ts@@ -135,6 +135,12 @@ describe("communityKeys", () => {expect(communityKeys.botAuditPreview("b1")).not.toEqual(communityKeys.botAuditLog("b1"),)+ expect(communityKeys.botMarks("b1")).toEqual([+ "community",+ "bot",+ "b1",+ "marks",+ ])expect(communityKeys.message("m1")).toEqual(["community","message",diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex 48b7bfd5a..c602b2b5e 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -147,6 +147,8 @@ export const communityKeys = {[...communityKeys.all, "bot", botId, "audit-log"] as const,botAuditPreview: (botId: string) =>[...communityKeys.all, "bot", botId, "audit-preview"] as const,+ botMarks: (botId: string) =>+ [...communityKeys.all, "bot", botId, "marks"] as const,// ── Notification settings ───────────────────────────────────────────────notificationSettings: () =>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.tsindex 05bf70535..2bbaaba5c 100644--- 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@@ -197,7 +197,12 @@ async function enrollBot(credential: string, botId: string): Promise<string> {return data.runnerKey}-async function sendBotMessage(runnerKey: string, channel: string, text: string): Promise<void> {+async function sendBotMessage(+ runnerKey: string,+ channel: string,+ text: string,+ seenUpToSeq = 0,+): Promise<{ seq: number }> {const response = await fetch(`${WEB_URL}/api/community/channels/resolve/messages`, {method: "POST",headers: {@@ -209,12 +214,38 @@ async function sendBotMessage(runnerKey: string, channel: string, text: string):channel,content: { text },attachments: [],- seenUpToSeq: 0,+ seenUpToSeq,nonce: `profile-preview:${crypto.randomUUID()}`,}),})expect(response.status).toBe(200)- expect((await response.json() as { state: string }).state).toBe("sent")+ const data = await response.json() as { state: string; message: { seq: string } }+ expect(data.state).toBe("sent")+ const seq = Number(data.message.seq.replace(/^#/, ""))+ expect(Number.isInteger(seq) && seq > 0).toBe(true)+ return { seq }+}++async function setBotMark(+ runnerKey: string,+ channel: string,+ seq: number,+): Promise<void> {+ const response = await fetch(`${WEB_URL}/api/community/messages/resolve/properties`, {+ method: "PUT",+ headers: {+ Authorization: `Bearer ${runnerKey}`,+ "Content-Type": "application/json",+ Origin: WEB_URL,+ },+ body: JSON.stringify({+ channel,+ seq,+ property: { type: "mark", value: true },+ }),+ })+ expect(response.status).toBe(200)+ await expect(response.json()).resolves.toMatchObject({ type: "mark", value: true })}type MachineSocket = {@@ -222,6 +253,7 @@ type MachineSocket = {close: () => voidonce(event: "open", listener: () => void): voidonce(event: "error", listener: (error: Error) => void): void+ once(event: "message", listener: (data: unknown) => void): void}function connectMachine(credential: string) {@@ -246,99 +278,231 @@ async function openBotProfile(page: Page, botName: string): Promise<void> {await expect(page.getByTestId(tid.profileCard)).toBeVisible()}-test("owner-only bot profile preview, owner swap, and URL-owned audit modal", async ({ asUser }, testInfo) => {+test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audit modal", async ({ asUser }, testInfo) => {test.setTimeout(180_000)const suffix = Date.now().toString(36)- const serverId = await seedServer("alice", `profile-preview-${suffix}`)- const channelName = `bots-${suffix}`+ const serverId = await seedServer("alice", `profile-preview-server-with-a-long-name-${suffix}`)+ const channelName = `bots-with-a-long-channel-name-${suffix}`const channelId = await seedChannel("alice", serverId, channelName)+ const staleServerId = await seedServer("alice", `stale-mark-server-${suffix}`)+ const staleChannelName = `former-private-work-${suffix}`+ const staleChannelId = await seedChannel("alice", staleServerId, staleChannelName)await seedJoinServer("alice", "bob", serverId)const { credential, machineId } = await pairMachine()- const botName = `Preview bot ${suffix}`+ const botName = `Preview bot ${suffix} long-name`const botId = await createBot(machineId, botName)await jsonRequest("alice", `/api/community/servers/${serverId}/bots`, {method: "POST",body: JSON.stringify({ botId }),})+ await jsonRequest("alice", `/api/community/servers/${staleServerId}/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)+ const staleServer = servers.find((candidate) => candidate.id === staleServerId)expect(server).toBeTruthy()+ expect(staleServer).toBeTruthy()const runnerKey = await enrollBot(credential, botId)- await sendBotMessage(+ const channelRef = `/${server!.name}#${server!.discriminator}/${channelName}`+ let latestSeq = 0+ for (const index of [1, 2, 3]) {+ const created = await jsonRequest<{ message: { seq: number } }>(+ "alice",+ `/api/community/channels/${channelId}/messages`,+ {+ method: "POST",+ body: JSON.stringify({ content: `Marked task ${index} ${suffix}` }),+ },+ )+ latestSeq = created.message.seq+ await setBotMark(runnerKey, channelRef, latestSeq)+ }+ const longBotMessage = await sendBotMessage(runnerKey,- `/${server!.name}#${server!.discriminator}/${channelName}`,- `Open my profile ${suffix}`,+ channelRef,+ `**Long marked task ${suffix}** ${"with enough detail to require a second line ".repeat(5)}`,+ latestSeq,+ )+ await setBotMark(runnerKey, channelRef, longBotMessage.seq)++ const staleMessage = await jsonRequest<{ message: { seq: number } }>(+ "alice",+ `/api/community/channels/${staleChannelId}/messages`,+ {+ method: "POST",+ body: JSON.stringify({ content: `Persisted stale mark ${suffix}` }),+ },)+ const staleChannelRef = `/${staleServer!.name}#${staleServer!.discriminator}/${staleChannelName}`+ await setBotMark(runnerKey, staleChannelRef, staleMessage.message.seq)+ const staleMembers = await jsonRequest<{+ members: Array<{ id: string; userId: string }>+ }>("alice", `/api/community/servers/${staleServerId}/members`)+ const staleBotMember = staleMembers.members.find((member) => member.userId === botId)+ expect(staleBotMember).toBeTruthy()+ const removeStaleBot = await fetch(+ `${WEB_URL}/api/community/servers/${staleServerId}/members/${staleBotMember!.id}`,+ { method: "DELETE", headers: headersFor("alice") },+ )+ expect(removeStaleBot.status).toBe(204)const machine = connectMachine(credential)await machine.openedtry {machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))- for (const index of [1, 2, 3, 4, 5, 6]) {+ for (let index = 0; index < 11; index += 1) {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}` } },+ event: { kind: "tool_call", payload: { name: `Open activity log ${index}` } },}))}await expect.poll(async () => {const response = await fetch(- `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=5`,+ `${WEB_URL}/api/community/bots/${botId}/audit-log?limit=10`,{ headers: headersFor("alice") },)if (!response.ok) return 0return ((await response.json()) as { events: unknown[] }).events.length- }).toBe(5)+ }).toBe(10)++ const authoritativeMarks = await jsonRequest<{+ marked: Array<{+ id: string+ server: string+ channel: string+ m: { authorName: string; content: string; createdAt: string }+ }>+ }>("alice", `/api/community/bots/${botId}/marks`)+ expect(authoritativeMarks.marked).toHaveLength(4)+ expect(authoritativeMarks.marked.some((mark) => mark.m.authorName === botName)).toBe(true)+ expect(authoritativeMarks.marked).toContainEqual(expect.objectContaining({+ server: staleServer!.name,+ channel: staleChannelName,+ m: expect.objectContaining({ content: `Persisted stale mark ${suffix}` }),+ }))const route = `/c/channels/${serverId}/${channelId}`const alice = await asUser("alice")- const ownerAuditRequests: string[] = []+ const ownerMarkRequests: string[] = []alice.page.on("request", (request) => {- if (new URL(request.url()).pathname === `/api/community/bots/${botId}/audit-log`) {- ownerAuditRequests.push(request.url())+ if (new URL(request.url()).pathname === `/api/community/bots/${botId}/marks`) {+ ownerMarkRequests.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",+ const sticker = alice.page.getByTestId(tid.botMarkSticker)+ await expect(sticker).toBeVisible()+ await expect(sticker).toHaveAttribute("aria-label", "Bot log")+ const activityTab = sticker.getByRole("tab", { name: "Recent activity" })+ const marksTab = sticker.getByRole("tab", { name: /Marked messages/ })+ const auditRows = alice.page.locator(+ `[data-testid^="${tid.botAuditPreviewRow("")}"]`,)- await expect(alice.page.locator(`[data-testid^="${tid.botAuditPreviewRow("")}"]`))- .toHaveCount(5)- expect(ownerAuditRequests.some((url) => new URL(url).searchParams.get("limit") === "5"))+ const activityScroller = sticker+ .getByRole("tabpanel", { name: "Recent activity log" })+ .locator(".bot-note-scrollbar")+ await expect(activityTab).toHaveAttribute("aria-selected", "true")+ await expect(auditRows).toHaveCount(10)+ await expect(alice.page.getByTestId(tid.botAuditPreviewEarlier)).toHaveText("…")+ await expect(activityScroller).toHaveCSS("overflow-y", "auto")+ await expect.poll(async () => activityScroller.evaluate((element) =>+ element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true)-+ expect((await auditRows.allTextContents()).some((text) =>+ /open activity log 0$/i.test(text))).toBe(false)+ machine.socket.send(JSON.stringify({+ type: "bot_audit_event",+ agentId: botId,+ sessionId: `session-${suffix}`,+ launchId: `launch-${suffix}`,+ event: { kind: "tool_call", payload: { name: "Open activity log 11" } },+ }))+ await expect.poll(async () =>+ (await auditRows.allTextContents()).join(" ").toLowerCase())+ .toContain("open activity log 11")+ await expect(auditRows).toHaveCount(10)+ expect((await auditRows.allTextContents()).some((text) =>+ /open activity log 1$/i.test(text))).toBe(false)+ await expect.poll(async () => activityScroller.evaluate((element) =>+ element.scrollTop + element.clientHeight >= element.scrollHeight - 1))+ .toBe(true)+ await expect(sticker.getByRole("button", { name: /Load more activity/ }))+ .toBeVisible()+ await marksTab.click()+ await expect(marksTab).toHaveAttribute("aria-selected", "true")+ await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))+ .toHaveCount(3)+ await expect(alice.page.getByTestId(tid.botMarkStickerOverflow)).toBeVisible()+ await expect(sticker.getByTitle(`${server!.name} · #${channelName}`).first()).toBeVisible()+ await expect(sticker).toContainText(botName)+ await expect(sticker).toContainText(`Long marked task ${suffix}`)+ await expect(sticker).not.toContainText("**Long marked task")+ await expect(sticker.locator("time")).toHaveCount(3)+ await expect(sticker.locator("p").filter({ hasText: `Long marked task ${suffix}` }))+ .toHaveCSS("-webkit-line-clamp", "2")+ expect(ownerMarkRequests.length).toBeGreaterThan(0)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^="${tid.botAuditPreviewRow("")}"]`))- .toHaveCount(4)+ const stop = alice.page.getByTestId(tid.botMarkStickerStop)+ await expect(stop).toBeVisible()+ await attachPageScreenshot(testInfo, "bot-work-sticker-marked-running-desktop", alice.page)+ await activityTab.click()+ await expect(activityTab).toHaveAttribute("aria-selected", "true")+ await expect(sticker.getByRole("button", { name: /Load more activity/ }))+ .toBeVisible()+ await expect(stop).toBeVisible()+ await attachPageScreenshot(testInfo, "bot-work-sticker-activity-running-desktop", alice.page)+ await marksTab.click()+ const interruptFrame = new Promise<unknown>((resolveFrame) => {+ machine.socket.once("message", (data) => resolveFrame(JSON.parse(String(data))))+ })+ await stop.click()+ await expect(stop).toContainText("Stopping…")+ await expect(stop).toBeDisabled()+ await expect(interruptFrame).resolves.toEqual({ type: "agent:interrupt", agentId: botId })+ machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "idle" }))+ await expect.poll(async () => {+ const profile = await jsonRequest<{ statusText: string | null }>(+ "alice",+ `/api/community/users/${botId}/profile`,+ )+ return profile.statusText+ }).toBe("Idle")+ await gotoAfterUserWsAuth(alice.page, route)+ await openBotProfile(alice.page, botName)+ await expect(alice.page.getByTestId(tid.botMarkStickerStop))+ .toHaveCount(0)+ await expect(sticker).toBeVisible()await alice.page.setViewportSize({ width: 375, height: 812 })+ await alice.page.emulateMedia({ colorScheme: "dark" })+ await expect(alice.page.locator("html")).toHaveClass(/dark/)+ await expect(sticker).toBeVisible()+ const mobileStickerGeometry = await sticker.evaluate((element) => ({+ clientWidth: element.clientWidth,+ scrollWidth: element.scrollWidth,+ right: element.getBoundingClientRect().right,+ }))+ expect(mobileStickerGeometry.scrollWidth).toBeLessThanOrEqual(mobileStickerGeometry.clientWidth)+ expect(mobileStickerGeometry.right).toBeLessThanOrEqual(375)+ await expect(sticker.getByLabel("Loading recent activity")).toHaveCount(0)+ await expect(sticker.getByText("open activity log 11", { exact: true })).toBeVisible()+ await attachPageScreenshot(testInfo, "bot-mark-sticker-activity-mobile-dark", alice.page)+ await sticker.getByRole("tab", { name: "Marked messages" }).click()+ await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))+ .toHaveCount(3)+ await attachPageScreenshot(testInfo, "bot-mark-sticker-marks-mobile-dark", alice.page)const ownerLink = alice.page.getByTestId(tid.profileOwnerLink)await expect(alice.page.getByTestId(tid.profileBotBadge)).toContainText("Bot")await expect(ownerLink).toBeVisible()@@ -354,12 +518,18 @@ test("owner-only bot profile preview, owner swap, and URL-owned audit modal", asawait alice.page.mouse.click(4, 4)await expect(alice.page.getByTestId(tid.profileCard)).toHaveCount(0)await alice.page.setViewportSize({ width: 1280, height: 900 })+ await alice.page.emulateMedia({ colorScheme: "light" })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()+ const openActivity = alice.page.getByRole("button", {+ name: "Load more activity in the full audit log",+ })+ await openActivity.focus()+ await expect(openActivity).toBeFocused()+ await openActivity.press("Enter")await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}$`))await expect(alice.page.getByTestId(tid.botActivityModal)).toBeVisible()await expectActivityHeader(alice.page, testInfo, 1280)@@ -378,17 +548,21 @@ test("owner-only bot profile preview, owner swap, and URL-owned audit modal", asawait expect(alice.page).toHaveURL(`/c/me/bots?machineId=${machineId}`)const bob = await asUser("bob")- const bobAuditRequests: string[] = []+ const bobDirectMarks = await fetch(`${WEB_URL}/api/community/bots/${botId}/marks`, {+ headers: headersFor("bob"),+ })+ expect(bobDirectMarks.status).toBe(404)+ const bobMarkRequests: string[] = []bob.page.on("request", (request) => {- if (new URL(request.url()).pathname === `/api/community/bots/${botId}/audit-log`) {- bobAuditRequests.push(request.url())+ if (new URL(request.url()).pathname === `/api/community/bots/${botId}/marks`) {+ bobMarkRequests.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 expect(bob.page.getByTestId(tid.botMarkSticker)).toHaveCount(0)+ expect(bobMarkRequests).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)@@ -396,7 +570,7 @@ test("owner-only bot profile preview, owner swap, and URL-owned audit modal", asawait bob.page.goto(`/c/me/bots?audit=${botId}`)await expect(bob.page.getByTestId(tid.botActivityModal)).toHaveCount(0)await expect.poll(() => new URL(bob.page.url()).searchParams.has("audit")).toBe(false)- expect(bobAuditRequests).toEqual([])+ expect(bobMarkRequests).toEqual([])} finally {machine.socket.close()}