Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): read bot Thoughts in a ring notebook (#967)

Gustavo Yed5aee02031c3
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 1b83d0f2e..b1c5e6056 100644
--- a/src/shared/src/db/queries/community/bot-audit-log.ts
+++ b/src/shared/src/db/queries/community/bot-audit-log.ts
@@ -149,11 +149,15 @@ export async function listOwnedBotActivityEvents(
ownerUserId: string;
beforeCreatedAt?: string;
beforeId?: string;
+ kind?: string;
limit?: number;
}
): 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.kind !== undefined) {
+ eventConds.push(eq(communityBotActivityEvent.kind, opts.kind));
+ }
if (opts.beforeCreatedAt !== undefined && opts.beforeId !== undefined) {
eventConds.push(
or(
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 2a337a3c6..644a4710e 100644
--- a/src/shared/test/queries/community-bot-audit-log.test.ts
+++ b/src/shared/test/queries/community-bot-audit-log.test.ts
@@ -128,6 +128,50 @@ describe("listOwnedBotActivityEvents", () => {
expect(rows?.map((row) => row.id)).toEqual(["bae_b", "bae_a"])
})
+ it("filters kind before the page limit and keeps tied text cursors lossless", async () => {
+ const insert = sqlite.prepare(`
+ INSERT INTO community_bot_activity_event
+ (id, bot_id, kind, payload, created_at)
+ VALUES (?, 'bot_1', ?, '{}', ?)
+ `)
+ for (let i = 0; i < 100; i++) {
+ insert.run(`tool_${i}`, "tool_call", "2026-09-01T00:00:00.000Z")
+ }
+ const textIds = Array.from({ length: 12 }, (_, i) => `text_${String(i).padStart(2, "0")}`)
+ for (const id of textIds) insert.run(id, "text", "2026-08-06T00:00:00.000Z")
+
+ const first = await q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1", ownerUserId: "owner_1", kind: "text", limit: 10,
+ })
+ expect(first?.map((row) => row.id)).toEqual(textIds.slice(2).reverse())
+ expect(first?.every((row) => row.kind === "text")).toBe(true)
+
+ const last = first!.at(-1)!
+ const second = await q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1", ownerUserId: "owner_1", kind: "text", limit: 10,
+ beforeCreatedAt: last.createdAt, beforeId: last.id,
+ })
+ expect(second?.map((row) => row.id)).toEqual(textIds.slice(0, 2).reverse())
+ const mixed = await q.listOwnedBotActivityEvents(db, {
+ botId: "bot_1", ownerUserId: "owner_1", limit: 10,
+ })
+ expect(mixed).toHaveLength(10)
+ expect(mixed?.every((row) => row.kind === "tool_call")).toBe(true)
+ })
+
+ it("preserves the owned-bot sentinel when a kind has no matches", async () => {
+ for (const botId of ["bot_1", "empty_bot"]) {
+ await expect(q.listOwnedBotActivityEvents(db, {
+ botId, ownerUserId: "owner_1", kind: "text", limit: 10,
+ })).resolves.toEqual([])
+ }
+ for (const botId of ["foreign_bot", "human_1", "deleted_bot", "missing_bot"]) {
+ await expect(q.listOwnedBotActivityEvents(db, {
+ botId, ownerUserId: "owner_1", kind: "text", limit: 10,
+ })).resolves.toBeNull()
+ }
+ })
+
it("supports a timestamp-only cursor", async () => {
const rows = await q.listOwnedBotActivityEvents(db, {
botId: "bot_1",
diff --git a/src/web/AGENTS.md b/src/web/AGENTS.md
index 643577dfa..af3b7c841 100644
--- a/src/web/AGENTS.md
+++ b/src/web/AGENTS.md
@@ -1,6 +1,6 @@
<!-- BEGIN:nextjs-agent-rules -->
-# This is NOT the Next.js you know
+## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
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 cfe138844..b8e3f6862 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
@@ -195,6 +195,17 @@ describe("GET /api/community/bots/[id]/audit-log", () => {
expect(body.events[0]!.payload).toEqual({ from: "claude-opus-4-6", to: "claude-sonnet-4-6" })
})
+ it("passes kind and the composite cursor into the owner-scoped query", async () => {
+ mockListOwnedBotActivityEvents.mockResolvedValue([])
+ const res = await GET(req("?kind=text&limit=10&beforeCreatedAt=2026-08-03T00:00:00.000Z&beforeId=bae_text"), ctx("b1"))
+ expect(res.status).toBe(200)
+ expect(mockListOwnedBotActivityEvents).toHaveBeenCalledWith(expect.anything(), {
+ botId: "b1", ownerUserId: "u1", kind: "text", limit: 10,
+ beforeCreatedAt: "2026-08-03T00:00:00.000Z", beforeId: "bae_text",
+ })
+ await expect(res.json()).resolves.toEqual({ events: [], nextCursor: null })
+ })
+
it("caps limit at 100 and floors it at 1 (defends against unbounded page requests)", async () => {
mockListOwnedBotActivityEvents.mockResolvedValue([])
await GET(req("?limit=99999"), ctx("b1"))
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 da0fb4a31..d521e798e 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
@@ -27,6 +27,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const url = new URL(req.url)
const beforeCreatedAt = url.searchParams.get("beforeCreatedAt") ?? undefined
const beforeId = url.searchParams.get("beforeId") ?? undefined
+ const kind = url.searchParams.get("kind") ?? undefined
const limitRaw = url.searchParams.get("limit")
const limit = limitRaw
? Math.max(1, Math.min(MAX_LIMIT, Number.parseInt(limitRaw, 10) || DEFAULT_LIMIT))
@@ -37,6 +38,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
ownerUserId: ctx.userId,
beforeCreatedAt,
beforeId,
+ ...(kind !== undefined ? { kind } : {}),
limit,
})
if (rows === null) return writeError("bot not found", 404)
diff --git a/src/web/src/components/community/bots/bot-runtime-fields.dom.test.ts b/src/web/src/components/community/bots/bot-runtime-fields.dom.test.ts
index c5c2a85e9..10698908d 100644
--- a/src/web/src/components/community/bots/bot-runtime-fields.dom.test.ts
+++ b/src/web/src/components/community/bots/bot-runtime-fields.dom.test.ts
@@ -86,7 +86,7 @@ describe("BotRuntimeFields", () => {
options: [{ id: "antigravity", unhealthy: false }, { id: "agy", unhealthy: false }],
runtime: "antigravity",
})
- fireEvent.click(renderer.getByRole("radio", { name: "Antigravity CLI (agy)" }))
+ fireEvent.click(renderer.getByRole("radio", { name: "antigravity cli" }))
expect(onRuntimeChange).toHaveBeenCalledWith("agy")
expect(onModelChange).toHaveBeenCalledWith(null)
expect(onReasoningEffortChange).toHaveBeenCalledWith(null)
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts
index 8124c49c3..46ad8bdcd 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts
+++ b/src/web/src/components/community/bots/edit-bot-sheet.dom.test.ts
@@ -433,7 +433,7 @@ describe("EditBotSheet — provider switch AlertDialog + toast", () => {
model: null,
}),
)
- expect(toastSuccess).toHaveBeenCalledWith(`Provider switch to ${runtime === "agy" ? "Antigravity CLI (agy)" : runtime} dispatched`)
+ expect(toastSuccess).toHaveBeenCalledWith(`Provider switch to ${runtime === "agy" ? "antigravity cli" : runtime} dispatched`)
expect(toastSuccess.mock.calls.join(" ")).not.toMatch(/offline|next wake|applies when/i)
})
diff --git a/src/web/src/components/community/social/bot-audit-preview.dom.test.ts b/src/web/src/components/community/social/bot-audit-preview.dom.test.ts
index da28db083..784d25180 100644
--- a/src/web/src/components/community/social/bot-audit-preview.dom.test.ts
+++ b/src/web/src/components/community/social/bot-audit-preview.dom.test.ts
@@ -22,7 +22,7 @@ vi.mock("lucide-react", () => ({
Lock: "lock-icon",
}))
-import { BotAuditPreview } from "./bot-audit-preview"
+import { BotAuditActiveRow, BotAuditPreview } from "./bot-audit-preview"
import {
isBotActivityActive,
isBotActivityRunning,
@@ -248,4 +248,11 @@ describe("BotAuditPreview", () => {
expect(renderer.container.textContent).toContain("Activity unavailable")
renderer.unmount()
})
+ it("can omit the running timestamp for the shared notebook footer", () => {
+ const renderer = render(React.createElement(BotAuditActiveRow, { showTime: false }))
+ expect(renderer.container.textContent).toContain("running")
+ expect(renderer.container.querySelector("time")).toBeNull()
+ expect(renderer.container.querySelectorAll('[class*="rounded-full"]')).toHaveLength(3)
+ })
+
})
diff --git a/src/web/src/components/community/social/bot-audit-preview.tsx b/src/web/src/components/community/social/bot-audit-preview.tsx
index 23e971e64..fad660b0c 100644
--- a/src/web/src/components/community/social/bot-audit-preview.tsx
+++ b/src/web/src/components/community/social/bot-audit-preview.tsx
@@ -76,7 +76,7 @@ export function BotAuditPreview({
)
}
-export function BotAuditTimeline({
+function BotAuditTimeline({
events,
isLoading,
isError,
@@ -144,13 +144,16 @@ export function BotAuditTimeline({
export function BotAuditActiveRow({
latestEventAt,
tone = "default",
+ showTime = true,
}: {
latestEventAt?: string
tone?: BotAuditTone
+ showTime?: boolean
}) {
const [nowMs, setNowMs] = useMountedClock()
useEffect(() => {
+ if (!showTime) return
let timer: ReturnType<typeof globalThis.setTimeout>
const scheduleNextMinute = () => {
const delay = 60_000 - (Date.now() % 60_000)
@@ -161,7 +164,7 @@ export function BotAuditActiveRow({
}
scheduleNextMinute()
return () => globalThis.clearTimeout(timer)
- }, [setNowMs])
+ }, [setNowMs, showTime])
const latestEventMs = latestEventAt ? Date.parse(latestEventAt) : Number.NaN
const displayedAt = new Date(
@@ -171,11 +174,11 @@ export function BotAuditActiveRow({
return (
<div
data-testid={tid.botAuditPreviewActive}
- className={tone === "note"
+ className={!showTime ? "flex min-w-0 items-center text-xs" : 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"}
>
- <time
+ {showTime && <time
dateTime={displayedAt}
suppressHydrationWarning
className={tone === "note"
@@ -183,14 +186,14 @@ export function BotAuditActiveRow({
: "font-mono text-[10px] tabular-nums text-muted-foreground/70"}
>
{formatAuditPreviewTime(displayedAt)}
- </time>
+ </time>}
<span className="flex items-center gap-1" aria-label="Bot activity in progress">
- <span className={tone === "note" ? "mr-1 text-xs text-black" : "mr-1 text-xs text-primary/70"}>running</span>
+ <span className={!showTime ? "mr-1 text-xs" : tone === "note" ? "mr-1 text-xs text-black" : "mr-1 text-xs text-primary/70"}>running</span>
{[0, 1, 2].map((index) => (
<span
key={index}
aria-hidden
- className={tone === "note"
+ className={!showTime ? "size-1.5 rounded-full bg-current motion-safe:animate-pulse motion-reduce:animate-none" : 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` }}
diff --git a/src/web/src/components/community/social/bot-mark-sticker.dom.test.ts b/src/web/src/components/community/social/bot-mark-sticker.dom.test.ts
index f7962f226..2c6e3c5a9 100644
--- a/src/web/src/components/community/social/bot-mark-sticker.dom.test.ts
+++ b/src/web/src/components/community/social/bot-mark-sticker.dom.test.ts
@@ -1,5 +1,3 @@
-import { readFileSync } from "node:fs"
-import { resolve } from "node:path"
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { act, fireEvent, render as renderDom } from "@/test/react-dom-harness"
@@ -45,12 +43,6 @@ vi.mock("lucide-react", () => ({
import { BotMarkSticker } from "./bot-mark-sticker"
-const globalCss = readFileSync(resolve(
- process.cwd(),
- process.cwd().endsWith("/src/web") ? "" : "src/web",
- "src/app/globals.css",
-), "utf8")
-
const mark = (id: string, content = `Task ${id}`) => ({
id,
server: "Alook",
@@ -150,92 +142,60 @@ describe("BotMarkSticker", () => {
vi.unstubAllGlobals()
})
- it("defaults to recent activity inside a stable note shell", () => {
+ it("defaults to Thoughts and has no separate Load more control", () => {
const { renderer, props } = render()
- expect(renderer.container).not.toBeEmptyDOMElement()
expect(renderer.container.textContent).toContain("Bot log")
- expect(renderer.container.textContent).not.toContain("Bot note")
- const title = [...renderer.container.querySelectorAll("span")]
- .find((node) => node.textContent === "Bot log")!
- expect(title.className).toContain("font-bold")
- expect(title.className).toContain("font-brand")
- const activityTab = renderer.container.querySelector('[role="tab"][aria-selected="true"]')!
- const tablist = renderer.container.querySelector('[role="tablist"]')!
- expect(tablist.className).toContain("h-12")
- expect(activityTab.className).toContain("h-11")
- expect(activityTab.querySelector("activity-icon")).not.toBeNull()
- expect(renderer.container.querySelector('[aria-label="Recent activity log"]')).not.toBeNull()
+ expect(renderer.container.querySelector('[role="tab"][aria-selected="true"]')?.textContent).toBe("Thoughts")
+ expect(renderer.container.querySelector('[aria-label="Recent thoughts"]')).not.toBeNull()
+ expect(renderer.container.textContent).toContain("No recent thoughts")
expect(renderer.container.textContent).toContain("Ready when you are")
- const activityPanel = renderer.container.querySelector('[aria-label="Recent activity log"]')!
- expect(activityPanel.tagName).toBe("DIV")
- expect(activityPanel.className).not.toContain("overflow-hidden")
- expect(activityPanel.className).not.toContain("rounded-xl")
- expect(activityPanel.className).not.toContain("overflow-y-auto")
- expect(activityPanel.className).not.toContain("px-1")
- const activityScroller = activityPanel.querySelector('[class*="bot-note-scrollbar"]')!
- expect(activityScroller.className).toContain("overflow-x-hidden")
- expect(activityScroller.className).toContain("overflow-y-auto")
- const stream = renderer.container.querySelector(
- '[data-testid="community-bot-audit-preview-bottom"]',
- )!
- expect(stream.className).toContain("min-h-full")
- expect(stream.className).toContain("justify-end")
- const loadMore = renderer.container.querySelector<HTMLButtonElement>(
- '[aria-label="Load more activity in the full audit log"]',
- )!
- expect(loadMore.tagName).toBe("BUTTON")
- expect(loadMore.textContent).toContain("Load more")
- expect(loadMore.className).toContain("min-h-11")
- expect(loadMore.className).not.toContain("border")
- expect(loadMore.className).not.toContain("shadow")
- expect(loadMore.className).toContain("hover:bg-black/10")
- fireEvent.click(loadMore)
+ expect(renderer.container.textContent).not.toContain("Load more")
+ expect(props.onOpenActivity).not.toHaveBeenCalled()
+ })
+
+ it("renders literal Unicode/newlines and retention metadata; clicking the body opens the audit", () => {
+ const body = "一页正文🙂\n<b>Literal</b>"
+ mocks.activity.events = [{ id: "text", kind: "text", payload: { text: body, truncated: true, chars: 200 }, createdAt: "2026-09-04T00:00:00.000Z" }]
+ const { renderer, props } = render()
+ const row = renderer.container.querySelector('[data-testid="community-bot-audit-preview-row-text"]')!
+ expect(row.querySelector("p")?.textContent).toBe(`${body}…`)
+ expect(row.querySelector("b")).toBeNull()
+ expect(row.querySelector("button")).toHaveAccessibleName(/^一页正文🙂\s+<b>Literal<\/b>…$/u)
+ expect(row.querySelector("button")).toHaveAccessibleDescription("Open full audit log")
+ expect(row.textContent).not.toContain("Truncated")
+ expect(row.querySelector("time")?.dateTime).toBe("2026-09-04T00:00:00.000Z")
+ fireEvent.click(row.querySelector("button")!)
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
+ it("does not expose cached text after an authoritative ownership404", () => {
+ mocks.activity.events = [{ id: "stale", kind: "text", payload: { text: "private cached body", truncated: false, chars: 19 }, createdAt: "2026-09-04T00:00:00.000Z" }]
+ mocks.activity.isNotFound = true
const { renderer } = render()
- const row = renderer.container.querySelector(
- '[data-testid="community-bot-audit-preview-row-event_1"]',
- )!
- expect(row.className).toContain("min-h-5")
- expect(row.className).toContain("grid-cols-[3.25rem_minmax(0,1fr)]")
- expect(row.className).toContain("leading-5")
- expect(row.className).toContain("px-[2px]")
- expect(row.querySelector("time")?.className).toContain("text-[10px]")
- expect(row.querySelector("time")?.className).toContain("text-black")
- expect(row.querySelector("time")?.className).toContain("whitespace-nowrap")
- const content = row.querySelector("span")
- expect(content?.className).toContain("text-black")
- expect(content?.className).toContain("font-mono")
- expect(content?.className).toContain("text-xs")
- expect(content?.className).not.toContain("font-semibold")
- const earlier = renderer.container.querySelector(
- '[data-testid="community-bot-audit-preview-earlier"]',
- )!
- expect(earlier.textContent).toBe("…")
- expect(earlier.className).toContain("min-h-5")
- expect(earlier.className).toContain("leading-5")
- expect(earlier.className).toContain("px-[2px]")
+ expect(renderer.container).toBeEmptyDOMElement()
+ })
+
+ it("keeps malformed text inspectable without inserting payload markup", () => {
+ mocks.activity.events = [{ id: "bad", kind: "text", payload: { text: { html: "<script>bad</script>" } }, createdAt: "2026-09-04T00:00:00.000Z" }]
+ const { renderer, props } = render()
+ expect(renderer.container.textContent).toContain("Text unavailable")
+ expect(renderer.container.querySelector("script")).toBeNull()
+ fireEvent.click(renderer.container.querySelector('[title="Open full audit log"]')!)
+ expect(props.onOpenActivity).toHaveBeenCalledOnce()
+ })
+
+ it.each(["isLoading", "isError"] as const)("holds the Thoughts panel during %s", (state) => {
+ mocks.activity[state] = true
+ const { renderer } = render()
+ expect(renderer.container.querySelector('[aria-label="Recent thoughts"]')).not.toBeNull()
+ expect(renderer.container.textContent).toContain(state === "isLoading" ? "Loading thoughts" : "Thoughts unavailable")
})
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}` },
+ kind: "text",
+ payload: { text: `Thought ${start + index}`, truncated: false, chars: 10 },
createdAt: `2026-09-04T00:00:${String(start + index).padStart(2, "0")}.000Z`,
}))
mocks.activity.events = events(0)
@@ -245,7 +205,10 @@ describe("BotMarkSticker", () => {
expect(mocks.bottomAnchor.scrollIntoView).toHaveBeenCalledWith({ block: "end" })
expect(mocks.scrollNode.scrollTop).toBe(300)
+ const scroller = renderer.container.querySelector('[data-testid="community-bot-audit-preview-scroll"]')!
mocks.scrollNode.scrollTop = 0
+ fireEvent.scroll(scroller)
+ mocks.scrollNode.scrollHeight = 500
mocks.activity.events = events(1)
renderer.rerender(React.createElement(BotMarkSticker, props))
expect(mocks.scrollNode.scrollTop).toBe(0)
@@ -255,10 +218,12 @@ describe("BotMarkSticker", () => {
'[data-testid="community-bot-audit-preview-row-event_0"]',
)).toHaveLength(0)
- mocks.scrollNode.scrollTop = 130
+ mocks.scrollNode.scrollTop = 330
+ fireEvent.scroll(scroller)
+ mocks.scrollNode.scrollHeight = 800
mocks.activity.events = events(2)
renderer.rerender(React.createElement(BotMarkSticker, props))
- expect(mocks.scrollNode.scrollTop).toBe(300)
+ expect(mocks.scrollNode.scrollTop).toBe(800)
})
it("retries initial tail anchoring when a data update cancels the first frame", () => {
@@ -273,16 +238,16 @@ describe("BotMarkSticker", () => {
mocks.activity.events = [{
id: "event_1",
- kind: "tool_call",
- payload: { name: "Tool 1" },
+ kind: "text",
+ payload: { text: "Thought 1", truncated: false, chars: 9 },
createdAt: "2026-09-04T00:00:01.000Z",
}]
const { renderer, props } = render()
mocks.activity.events = [{
id: "event_2",
- kind: "tool_call",
- payload: { name: "Tool 2" },
+ kind: "text",
+ payload: { text: "Thought 2", truncated: false, chars: 9 },
createdAt: "2026-09-04T00:00:02.000Z",
}]
renderer.rerender(React.createElement(BotMarkSticker, props))
@@ -380,17 +345,13 @@ describe("BotMarkSticker", () => {
'[data-testid="community-bot-mark-sticker-stop"]',
)!
expect(stop.disabled).toBe(false)
- expect(stop.className).toContain("bg-[#dc2626]")
- expect(stop.className).toContain("text-white")
- expect(stop.className).toContain("min-h-7")
- const activeRow = renderer.container.querySelector(
- '[data-testid="community-bot-audit-preview-active"]',
- )!
- expect(activeRow.className).toContain("grid-cols-[3.25rem_minmax(0,1fr)]")
- expect(activeRow.className).toContain("px-[2px]")
- expect(activeRow.querySelector("time")?.className).toContain("text-black")
- expect(activeRow.querySelectorAll('[class*="bg-black"]'))
- .toHaveLength(3)
+ const footer = renderer.container.querySelector("footer")!
+ expect(footer.textContent).toContain("running")
+ expect(footer.querySelector("time")).toBeNull()
+ fireEvent.click(renderer.container.querySelectorAll('[role="tab"]')[1]!)
+ expect(renderer.container.querySelector("footer")).toBe(footer)
+ expect(footer.textContent).toContain("running")
+ expect(footer.querySelector('[data-testid="community-bot-mark-sticker-stop"]')).toBe(stop)
fireEvent.click(stop)
expect(onStop).toHaveBeenCalledOnce()
})
@@ -413,7 +374,7 @@ describe("BotMarkSticker", () => {
mocks.result.isNotFound = true
const missing = render({ showStop: true }).renderer
- expect(missing.container.querySelector('[aria-label="Recent activity log"]')).not.toBeNull()
+ expect(missing.container.querySelector('[aria-label="Recent thoughts"]')).not.toBeNull()
expect(missing.container.querySelector(
'[data-testid="community-bot-mark-sticker-stop"]',
)).not.toBeNull()
diff --git a/src/web/src/components/community/social/bot-mark-sticker.module.css b/src/web/src/components/community/social/bot-mark-sticker.module.css
new file mode 100644
index 000000000..e7d3f18f2
--- /dev/null
+++ b/src/web/src/components/community/social/bot-mark-sticker.module.css
@@ -0,0 +1,82 @@
+.notebook {
+ --note-paper: #fcf7ed;
+ --note-ink: #40382d;
+ --note-muted: #776956;
+ --note-rule: #ddd3c1;
+ --note-edge: #ded6c7;
+ --note-cover: #827f6d;
+ --note-wire: #3b403a;
+ --note-hole: #171815;
+ --note-stop: #a54d3d;
+ container: notebook / size;
+ position: relative;
+ display: flex;
+ width: 100%;
+ height: min(420px, 50dvh);
+ min-height: 0;
+ color: var(--note-ink);
+}
+:global(.dark) .notebook {
+ --note-paper: #353229;
+ --note-ink: #eee6d5;
+ --note-muted: #beb29f;
+ --note-rule: #625b4d;
+ --note-edge: #777062;
+ --note-cover: #4a5048;
+ --note-wire: #5c6158;
+ --note-stop: #e6a696;
+}
+@media (min-width: 640px) {
+ .notebook { height: 100%; }
+}
+.stack {
+ position: absolute;
+ inset: 12px 0 -2px 12px;
+ border-radius: 5px;
+ border-bottom: 1.5px solid var(--note-cover);
+ background: repeating-linear-gradient(to right, var(--note-edge) 0 1px, var(--note-rule) 1px 2px) right top / 3px calc(100% - 10px) no-repeat, repeating-linear-gradient(to bottom, var(--note-edge) 0 1px, var(--note-rule) 1px 2px);
+ filter: drop-shadow(0 8px 9px rgb(44 40 31 / 12%));
+}
+.paper {
+ position: absolute;
+ inset: 8px 3px 8px 10px;
+ border-radius: 4px;
+ background: var(--note-paper);
+}
+.binding { position: absolute; top: 50%; left: 0; width: 30px; height: 192px; transform: translateY(-50%); pointer-events: none; overflow: visible; }
+@container notebook (min-height: 320px) {
+ .binding { height: 288px; }
+}
+@container notebook (min-height: 400px) {
+ .binding { height: 384px; }
+}
+.wire { fill: none; stroke: var(--note-wire); stroke-width: 2.25px; }
+.hole { fill: var(--note-hole); }
+.content { position: relative; display: flex; flex: 1; min-width: 0; min-height: 0; flex-direction: column; padding: 16px 18px 8px 42px; }
+.header { margin-bottom: 8px; }
+.tabs { display: flex; flex-shrink: 0; gap: 16px; margin-top: 0; border-bottom: 1px solid var(--note-rule); }
+.tab { position: relative; display: flex; min-width: 44px; min-height: 28px; align-items: center; justify-content: center; gap: 6px; padding-inline: 8px; border-radius: 5px; color: var(--note-muted); font-size: 12px; font-weight: 500; }
+.tabLabel { position: relative; display: inline-flex; height: 28px; align-items: center; }
+.tab[aria-selected="true"] { color: var(--note-ink); }
+.tab[aria-selected="true"]::after { position: absolute; inset: auto 8px -1px; height: 1.5px; background: currentColor; content: ""; }
+.tab:hover, .thought:hover { background: color-mix(in srgb, var(--note-ink) 4%, transparent); }
+.tab:active, .thought:active { background: color-mix(in srgb, var(--note-ink) 8%, transparent); }
+.entry { flex-shrink: 0; }
+.entry + .entry { margin-top: 16px; }
+.thought { display: flex; width: 100%; min-height: 21px; align-items: flex-start; padding: 4px 8px; border-radius: 5px; text-align: left; font-size: 13px; line-height: 21px; cursor: pointer; user-select: text; }
+.thought p { min-width: 0; line-height: inherit; }
+.footer { display: flex; flex-shrink: 0; min-height: 45px; align-items: center; gap: 8px; margin-top: 0; border-top: 1px solid var(--note-rule); padding-top: 0; font-size: 12px; line-height: 16px; }
+.footer > div { display: flex; align-items: center; }
+.stop { display: flex; min-width: 58px; min-height: 28px; flex-shrink: 0; align-items: center; justify-content: center; gap: 6px; padding-inline: 8px; border-radius: 5px; color: var(--note-stop); font-size: 12px; line-height: 16px; }
+.stopLabel { transform: translateY(1px); }
+.stop:hover { background: color-mix(in srgb, var(--note-stop) 6%, transparent); }
+.stop:active { background: color-mix(in srgb, var(--note-stop) 10%, transparent); }
+.stop:disabled { color: var(--note-muted); cursor: wait; }
+@media (max-width: 639px) {
+ .tab, .thought, .stop { min-height: 44px; }
+ .footer { min-height: 60px; }
+}
+.tab:focus-visible, .thought:focus-visible, .stop:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
+.scrollbar { scrollbar-color: var(--note-rule) transparent; }
+.scrollbar:hover { scrollbar-color: var(--note-muted) transparent; }
+.notebook ::selection { background: color-mix(in srgb, var(--note-ink) 15%, var(--note-paper)); }
diff --git a/src/web/src/components/community/social/bot-mark-sticker.tsx b/src/web/src/components/community/social/bot-mark-sticker.tsx
index 21f0f3b0f..dd8c5b3d9 100644
--- a/src/web/src/components/community/social/bot-mark-sticker.tsx
+++ b/src/web/src/components/community/social/bot-mark-sticker.tsx
@@ -1,31 +1,41 @@
"use client"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-/* 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 } from "react"
+
+import { AuditLogTextPayloadSchema, stripInlineMarkup } from "@alook/shared"
+import { CircleStop, LoaderCircle, Lock, Square } from "lucide-react"
+import { useEffect, useId, useLayoutEffect, useRef } 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"
+import { BotAuditActiveRow } from "./bot-audit-preview"
+import styles from "./bot-mark-sticker.module.css"
const VISIBLE_MARKS = 3
-type StickerView = "activity" | "marks"
+type StickerView = "thoughts" | "marks"
-function stickerTabClass(selected: boolean): string {
- return [
- "flex h-11 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 sm:h-8 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(" ")
+function NotebookBinding({ front }: { front: boolean }) {
+ const patternId = useId()
+ return (
+ <svg aria-hidden className={styles.binding}>
+ <defs>
+ <pattern id={patternId} x="-6" width="36" height="48" patternUnits="userSpaceOnUse">
+ <g transform="translate(6 24)">
+ {front ? <>
+ <ellipse cx="23" cy="2.34" rx="3.5" ry="2.5" className={styles.hole} />
+ <path d="M23 2.34C24.44-1.75 19.78-6.12 12.6-7.41C5.42-8.7-1.56-6.43-3-2.34" className={styles.wire} />
+ </> : (
+ <path d="M-3-2.34C-4.44 1.75 .22 6.12 7.4 7.41C14.58 8.7 21.56 6.43 23 2.34" className={styles.wire} />
+ )}
+ </g>
+ </pattern>
+ </defs>
+ <rect x="-6" width="36" height="100%" fill={`url(#${patternId})`} />
+ </svg>
+ )
}
export function BotMarkSticker({
@@ -43,12 +53,13 @@ export function BotMarkSticker({
onStop: () => void
onOpenActivity: () => void
}) {
- const [view, setView] = useAtom(useCreateAtom<StickerView>("activity"))
+ const [view, setView] = useAtom(useCreateAtom<StickerView>("thoughts"))
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 nearTailRef = useRef(true)
+ const activity = useBotAuditPreview(botId, true)
const { marks, isLoading, isError } = useBotMarks(botId)
const visibleMarks = marks.slice(0, VISIBLE_MARKS)
const hasOverflow = marks.length > VISIBLE_MARKS
@@ -62,13 +73,13 @@ export function BotMarkSticker({
const latestVisibleEventId = visibleEvents.at(-1)?.id
useEffect(() => {
- if (view === "activity") return
+ if (view === "thoughts") return
didInitialTailScrollRef.current = false
latestEventIdRef.current = undefined
}, [view])
useEffect(() => {
- if (view !== "activity") return
+ if (view !== "thoughts") return
if (didInitialTailScrollRef.current) return
if (visibleEvents.length === 0) return
const anchor = activityBottomAnchorRef.current
@@ -81,6 +92,7 @@ export function BotMarkSticker({
scroller.scrollTop = scroller.scrollHeight
latestEventIdRef.current = latestVisibleEventId
didInitialTailScrollRef.current = true
+ nearTailRef.current = true
})
})
return () => {
@@ -92,102 +104,66 @@ export function BotMarkSticker({
useLayoutEffect(() => {
const previousLatestEventId = latestEventIdRef.current
latestEventIdRef.current = latestVisibleEventId
- if (view !== "activity") return
+ if (view !== "thoughts") 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
+ if (nearTailRef.current) scroller.scrollTop = scroller.scrollHeight
}, [latestVisibleEventId, view])
+ if (activity.isNotFound) return null
+
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
+ <section data-testid={tid.botMarkSticker} aria-label="Bot log" className={styles.notebook}>
+ <NotebookBinding front={false} />
+ <div aria-hidden className={styles.stack} />
+ <div aria-hidden className={styles.paper} />
+ <NotebookBinding front />
+ <div className={styles.content}>
+ <header className={`${styles.header} flex shrink-0 items-center gap-2`}>
+ <span className="font-brand text-[34px] font-bold leading-none">Bot log</span>
+ <span className="ml-auto flex items-center gap-1 whitespace-nowrap text-[10px]" style={{ color: "var(--note-muted)" }}>
+ <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-12 shrink-0 items-center gap-1 rounded-xl bg-[#e8c56f] p-0.5 shadow-[inset_0_1px_3px_rgba(98,67,11,0.14)] sm:h-9 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-0 z-10 flex min-h-11 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 sm:top-2 sm:min-h-6"
- >
- Load more
- <ChevronRight className="size-3" aria-hidden />
+ <div role="tablist" aria-label="Bot log view" className={styles.tabs}>
+ {(["thoughts", "marks"] as const).map((tab) => (
+ <button key={tab} type="button" role="tab" aria-label={tab === "thoughts" ? "Thoughts" : "Marked messages"}
+ aria-selected={view === tab} onClick={() => setView(tab)} className={styles.tab}>
+ <span className={styles.tabLabel}>{tab === "thoughts" ? "Thoughts" : "Marks"}</span>
+ {tab === "marks" && marks.length > 0 && (
+ <span data-testid={hasOverflow ? tid.botMarkStickerOverflow : undefined} role={hasOverflow ? "status" : undefined} className="text-[10px] tabular-nums">
+ {hasOverflow && <span className="sr-only">More marked work</span>}{hasOverflow ? "3+" : marks.length}
+ </span>
+ )}
</button>
- <div
- ref={activityScrollRef}
- data-testid={tid.botAuditPreviewScroll}
- className="thin-scrollbar bot-note-scrollbar mt-12 min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain sm:mt-8"
- >
- <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>
+ {view === "thoughts" ? (
+ <div role="tabpanel" aria-label="Recent thoughts" className="flex min-h-0 flex-1 flex-col pt-2">
+ <div ref={activityScrollRef} data-testid={tid.botAuditPreviewScroll}
+ onScroll={({ currentTarget }) => {
+ nearTailRef.current = currentTarget.scrollHeight - (currentTarget.scrollTop + currentTarget.clientHeight) < 80
+ }}
+ className={`thin-scrollbar ${styles.scrollbar} 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">
+ {activity.isLoading ? <StickerState label="Loading thoughts" /> : activity.isError ? <StickerState label="Thoughts unavailable" /> : visibleEvents.length === 0 ? <StickerState label="No recent thoughts" /> : visibleEvents.map((event) => {
+ const parsed = AuditLogTextPayloadSchema.safeParse(event.payload)
+ return <div key={event.id} data-testid={tid.botAuditPreviewRow(event.id)} className={styles.entry}>
+ <div className="mb-1 flex items-center gap-2 px-2 text-[10px]" style={{ color: "var(--note-muted)" }}>
+ <time dateTime={event.createdAt}>{new Date(event.createdAt).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })}</time>
+ </div>
+ <button type="button" onClick={onOpenActivity} title="Open full audit log" className={styles.thought}>
+ <p className="whitespace-pre-wrap wrap-break-word">{parsed.success ? parsed.data.text : "Text unavailable"}{parsed.success && parsed.data.truncated && "…"}</p>
+ </button>
+ </div>
+ })}
</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">
+ <div role="tabpanel" className={`thin-scrollbar ${styles.scrollbar} mt-2 min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1`}>
{isLoading ? (
<StickerState label="Loading marked messages" />
) : isError ? (
@@ -214,9 +190,9 @@ export function BotMarkSticker({
<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]"
+ 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-accent/30"
>
- <Square className="mt-1.5 size-3.5 shrink-0 text-[#9a741f]" strokeWidth={1.75} aria-hidden />
+ <Square className="mt-1.5 size-3.5 shrink-0 text-(--note-muted)" strokeWidth={1.75} aria-hidden />
<div className="min-w-0">
<div className="flex min-w-0 items-start gap-2">
<Avatar
@@ -230,12 +206,12 @@ export function BotMarkSticker({
{mark.m.authorName || "Deleted user"}
</span>
{mark.m.createdAt && (
- <time dateTime={mark.m.createdAt} className="shrink-0 whitespace-nowrap font-mono text-[9px] tabular-nums text-[#4b3712]">
+ <time dateTime={mark.m.createdAt} className="shrink-0 whitespace-nowrap font-mono text-[9px] tabular-nums text-(--note-muted)">
{formatRelativeTime(mark.m.createdAt)}
</time>
)}
</div>
- <div title={location} className="flex w-fit min-w-0 max-w-full items-center gap-1 text-[10px] leading-4 text-[#4b3712]">
+ <div title={location} className="flex w-fit min-w-0 max-w-full items-center gap-1 text-[10px] leading-4 text-(--note-muted)">
<span className={mark.serverId ? "min-w-0 truncate" : "shrink-0"}>
{locationPrefix}
</span>
@@ -260,37 +236,24 @@ export function BotMarkSticker({
</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 min-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 className={styles.footer}>
+ <div className="min-w-0 flex-1 overflow-hidden">
+ {active ? <BotAuditActiveRow showTime={false} /> : <span className="text-xs text-(--note-muted)">Ready when you are</span>}
+ </div>
+ {showStop && <button type="button" data-testid={tid.botMarkStickerStop} onClick={onStop} disabled={stopPending}
+ aria-label={stopPending ? "Stopping current agent turn" : "Stop current agent turn"} className={styles.stop}>
+ {stopPending ? <LoaderCircle className="size-3.5 animate-spin motion-reduce:animate-none" aria-hidden /> : <CircleStop className="size-3.5" aria-hidden />}
+ <span className={styles.stopLabel}>{stopPending ? "Stopping…" : "Stop"}</span>
+ </button>}
</footer>
+ </div>
</section>
)
}
function StickerState({ label }: { label: string }) {
return (
- <div className="flex h-full items-center justify-center px-4 text-xs text-[#4b3712]">
+ <div className="flex h-full items-center justify-center px-4 text-xs text-(--note-muted)">
{label}
</div>
)
diff --git a/src/web/src/hooks/community/use-bot-audit-log.ts b/src/web/src/hooks/community/use-bot-audit-log.ts
index 0139f87f7..a9af8581c 100644
--- a/src/web/src/hooks/community/use-bot-audit-log.ts
+++ b/src/web/src/hooks/community/use-bot-audit-log.ts
@@ -8,6 +8,7 @@ useQueryClient,
replaceEqualDeep,
type InfiniteData,
type QueryClient,
+type QueryKey,
} from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
@@ -54,7 +55,12 @@ function reconcileAuditLogPages(previous: unknown, incoming: unknown, unobserved
}
export function appendBotAuditEvent(queryClient: QueryClient, botId: string, row: AuditEvent) {
- const key = communityKeys.botAuditLog(botId)
+ appendAuditEventToCache(queryClient, communityKeys.botAuditLog(botId), row)
+ const previewKey = communityKeys.botAuditPreview(botId)
+ if (row.kind === "text" && queryClient.getQueryState(previewKey)) appendAuditEventToCache(queryClient, previewKey, row)
+}
+
+function appendAuditEventToCache(queryClient: QueryClient, key: QueryKey, row: AuditEvent) {
const query = queryClient.getQueryCache().find({ queryKey: key, exact: true })
const updatedAt = query?.state.dataUpdatedAt ?? 0
const unobserved = !query?.getObserversCount()
@@ -78,20 +84,22 @@ export function appendBotAuditEvent(queryClient: QueryClient, botId: string, row
}
}
-export function useBotAuditLog(botId: string | null | undefined) {
+export function useBotAuditLog(botId: string | null | undefined, textOnly = false) {
const enabled = Boolean(botId)
const qc = useQueryClient()
+ const queryKey = botId ? (textOnly ? communityKeys.botAuditPreview(botId) : communityKeys.botAuditLog(botId)) : ["disabled-bot-audit-log"]
const query = useInfiniteQuery<AuditLogPage>({
enabled,
- queryKey: botId ? communityKeys.botAuditLog(botId) : ["disabled-bot-audit-log"],
- structuralSharing: (prev, next) => reconcileAuditLogPages(prev, next, !qc.getQueryCache().find({ queryKey: communityKeys.botAuditLog(botId!), exact: true })?.getObserversCount()),
+ queryKey,
+ structuralSharing: (prev, next) => reconcileAuditLogPages(prev, next, !qc.getQueryCache().find({ queryKey, exact: true })?.getObserversCount()),
initialPageParam: null as AuditLogPage["nextCursor"],
queryFn: async ({ pageParam, signal }) => {
const token = captureCommunityLiveSnapshotToken(qc)
const cursor = pageParam as AuditLogPage["nextCursor"]
const search = new URLSearchParams()
- search.set("limit", String(PAGE_SIZE))
+ search.set("limit", String(textOnly ? 10 : PAGE_SIZE))
+ if (textOnly) search.set("kind", "text")
if (cursor) {
search.set("beforeCreatedAt", cursor.beforeCreatedAt)
search.set("beforeId", cursor.beforeId)
@@ -102,7 +110,7 @@ export function useBotAuditLog(botId: string | null | undefined) {
)
if (cursor) return page
const fetchedIds = new Set(page.events.map((event) => event.id))
- const current = qc.getQueryData<InfiniteData<AuditLogPage>>(communityKeys.botAuditLog(botId!))?.pages[0]
+ const current = qc.getQueryData<InfiniteData<AuditLogPage>>(queryKey)?.pages[0]
const liveIds = new Set(current?.liveIds)
const arrived = current?.events.filter((event) => liveIds.has(event.id) && !fetchedIds.has(event.id)) ?? []
return arrived.length ? { ...page, events: [...arrived, ...page.events], liveIds: arrived.map((event) => event.id) } : page
diff --git a/src/web/src/hooks/community/use-bot-audit-preview.dom.test.ts b/src/web/src/hooks/community/use-bot-audit-preview.dom.test.ts
index 73720ccc3..fcd27b71e 100644
--- a/src/web/src/hooks/community/use-bot-audit-preview.dom.test.ts
+++ b/src/web/src/hooks/community/use-bot-audit-preview.dom.test.ts
@@ -1,4 +1,4 @@
-import { appendBotAuditEvent } from "./use-bot-audit-log"
+import { appendBotAuditEvent, useBotAuditLog } from "./use-bot-audit-log"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient } from "@tanstack/react-query"
@@ -13,7 +13,7 @@ vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetch(...args),
}))
-function renderBotAuditPreview(botId: string | null) {
+function renderBotAuditPreview(botId: string | null, textOnly = false) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
})
@@ -23,7 +23,7 @@ function renderBotAuditPreview(botId: string | null) {
children,
)
return {
- ...renderHook(() => useBotAuditPreview(botId), { wrapper }),
+ ...renderHook(() => useBotAuditPreview(botId, textOnly), { wrapper }),
queryClient,
}
}
@@ -124,4 +124,59 @@ describe("useBotAuditPreview", () => {
await waitFor(() => expect(rendered.result.current.isNotFound).toBe(true))
expect(apiFetch).toHaveBeenCalledOnce()
})
+ it("requests the latest ten text rows separately from the full audit cache", async () => {
+ apiFetch.mockResolvedValueOnce({ events: [
+ ...Array.from({ length: 11 }, (_, i) => event(`tool-${i}`, i + 10)),
+ { ...event("text-1", 1), kind: "text", payload: { text: "An older thought", chars: 16, truncated: false } },
+ ], nextCursor: null })
+ const rendered = renderBotAuditPreview("b1", true)
+ await waitFor(() => expect(rendered.result.current.events.map((row) => row.id)).toEqual(["text-1"]))
+ expect(apiFetch).toHaveBeenCalledOnce()
+ expect(apiFetch).toHaveBeenCalledWith("/api/community/bots/b1/audit-log?limit=10&kind=text", expect.objectContaining({ assertActive: expect.any(Function) }))
+ expect(rendered.queryClient.getQueryData(communityKeys.botAuditLog("b1"))).toBeUndefined()
+ expect(rendered.queryClient.getQueryData(communityKeys.botAuditPreview("b1"))).toBeDefined()
+ })
+
+ it("ignores live commands in Thoughts and accepts live text into its filtered cache", async () => {
+ apiFetch.mockResolvedValueOnce({ events: [], nextCursor: null })
+ const rendered = renderBotAuditPreview("b1", true)
+ await waitFor(() => expect(apiFetch).toHaveBeenCalledOnce())
+ act(() => appendBotAuditEvent(rendered.queryClient, "b1", event("tool", 1)))
+ expect(rendered.result.current.events).toHaveLength(0)
+ act(() => appendBotAuditEvent(rendered.queryClient, "b1", { ...event("text", 2), kind: "text", payload: { text: "New thought", chars: 11, truncated: false } }))
+ await waitFor(() => expect(rendered.result.current.events.map((row) => row.id)).toEqual(["text"]))
+ })
+
+ it("keeps full audit and Thoughts independent while one live text updates both", async () => {
+ const text = { ...event("text", 1), kind: "text" as const, payload: { text: "Thought", chars: 7, truncated: false } }
+ apiFetch.mockImplementation(async (path: string) => ({ events: path.includes("kind=text") ? [text] : [event("tool", 2), text], nextCursor: null }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: queryClient }, children)
+ const rendered = renderHook(() => ({ full: useBotAuditLog("b1"), thoughts: useBotAuditPreview("b1", true) }), { wrapper })
+ await waitFor(() => expect(rendered.result.current.full.events).toHaveLength(2))
+ await waitFor(() => expect(rendered.result.current.thoughts.events).toHaveLength(1))
+ act(() => {
+ appendBotAuditEvent(queryClient, "b1", event("new-tool", 3))
+ appendBotAuditEvent(queryClient, "b1", { ...text, id: "new-text", createdAt: event("", 4).createdAt })
+ })
+ await waitFor(() => expect(rendered.result.current.thoughts.events.map((row) => row.id)).toEqual(["new-text", "text"]))
+ expect(rendered.result.current.full.events.map((row) => row.id)).toEqual(["new-text", "new-tool", "tool", "text"])
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ })
+
+ it("hides an authoritative text-query 404 even when full audit holds cached text", async () => {
+ apiFetch.mockRejectedValueOnce(new ApiError("not found", 404))
+ const rendered = renderBotAuditPreview("b1", true)
+ rendered.queryClient.setQueryData(communityKeys.botAuditLog("b1"), { pages: [{ events: [{ ...event("private", 1), kind: "text" }], nextCursor: null }], pageParams: [null] })
+ await waitFor(() => expect(rendered.result.current.isNotFound).toBe(true))
+ expect(rendered.result.current.events).toEqual([])
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+
+ it("does not request filtered text without an owned bot id", async () => {
+ renderBotAuditPreview(null, true)
+ await flush()
+ expect(apiFetch).not.toHaveBeenCalled()
+ })
+
})
diff --git a/src/web/src/hooks/community/use-bot-audit-preview.ts b/src/web/src/hooks/community/use-bot-audit-preview.ts
index 324652404..d1226a94c 100644
--- a/src/web/src/hooks/community/use-bot-audit-preview.ts
+++ b/src/web/src/hooks/community/use-bot-audit-preview.ts
@@ -5,11 +5,12 @@ import { useBotAuditLog } from "./use-bot-audit-log"
const PREVIEW_LIMIT = 10
-export function useBotAuditPreview(botId: string | null | undefined) {
- const query = useBotAuditLog(botId)
+export function useBotAuditPreview(botId: string | null | undefined, textOnly = false) {
+ const query = useBotAuditLog(botId, textOnly)
+ const events = textOnly ? query.events.filter((event) => event.kind === "text") : query.events
return {
- events: query.events.slice(0, PREVIEW_LIMIT),
- hasEarlierEvents: query.events.length > PREVIEW_LIMIT || Boolean(query.hasNextPage),
+ events: events.slice(0, PREVIEW_LIMIT),
+ hasEarlierEvents: events.length > PREVIEW_LIMIT || Boolean(query.hasNextPage),
isLoading: query.isLoading,
isError: query.isError,
isNotFound: query.error instanceof ApiError && query.error.status === 404,
diff --git a/src/web/src/hooks/community/use-bots.ts b/src/web/src/hooks/community/use-bots.ts
index 6418a74b6..dabbebc3b 100644
--- a/src/web/src/hooks/community/use-bots.ts
+++ b/src/web/src/hooks/community/use-bots.ts
@@ -110,7 +110,7 @@ const botSurfaceKeys = (id?: string) => [communityKeys.bots(), communityKeys.fri
const allBotSurfaceKeys = () => botSurfaceKeys()
const botIdSurfaceKeys = ({ id }: { id: string }) => botSurfaceKeys(id)
const botAvatarSurfaceKeys = ({ botId }: { botId: string }) => botSurfaceKeys(botId)
-const botAuditKeys = ({ id }: { id: string }) => [communityKeys.botAuditLog(id)]
+const botAuditKeys = ({ id }: { id: string }) => [communityKeys.botAuditLog(id), communityKeys.botAuditPreview(id)]
const noBotKeys = () => []
function useBotCommand<TInput extends BotViewInput, TResult>(kind: string, execute: (input: TInput, context: BotCommandContext) => Promise<TResult>, keys: (input: TInput) => QueryKey[]) {
diff --git a/src/web/src/lib/community/runtime-label.ts b/src/web/src/lib/community/runtime-label.ts
index e4e66463c..271ba6a1e 100644
--- a/src/web/src/lib/community/runtime-label.ts
+++ b/src/web/src/lib/community/runtime-label.ts
@@ -1,3 +1,3 @@
export function runtimeLabel(runtime: string): string {
- return runtime === "agy" ? "Antigravity CLI (agy)" : runtime
+ return runtime === "agy" ? "antigravity cli" : runtime
}
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
index 9de0051fb..581d66f3a 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
@@ -804,7 +804,7 @@ let caseJourneyFailure2Present = false
agentId: botId,
sessionId: `session-${suffix}`,
launchId: `launch-${suffix}`,
- event: { kind: "tool_call", payload: { name: `Open activity log ${index}` } },
+ event: { kind: "text", payload: { text: `Open activity log ${index}`, truncated: false, chars: `Open activity log ${index}`.length } },
}))
}
@@ -847,17 +847,16 @@ let caseJourneyFailure2Present = false
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 activityTab = sticker.getByRole("tab", { name: "Thoughts" })
const marksTab = sticker.getByRole("tab", { name: /Marked messages/ })
const auditRows = alice.page.locator(
`[data-testid^="${tid.botAuditPreviewRow("")}"]`,
)
const activityScroller = sticker
- .getByRole("tabpanel", { name: "Recent activity log" })
- .locator(".bot-note-scrollbar")
+ .getByRole("tabpanel", { name: "Recent thoughts" })
+ .getByTestId(tid.botAuditPreviewScroll)
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))
@@ -880,7 +879,7 @@ let caseJourneyFailure2Present = false
agentId: botId,
sessionId: `session-${suffix}`,
launchId: `launch-${suffix}`,
- event: { kind: "tool_call", payload: { name: "Open activity log 11" } },
+ event: { kind: "text", payload: { text: "Open activity log 11", truncated: false, chars: "Open activity log 11".length } },
}))
await expect.poll(() => liveEventAcknowledged, {
message: `machine receives bot_audit_event_ack for ${liveEventId}`,
@@ -898,8 +897,7 @@ let caseJourneyFailure2Present = 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 expect(sticker.getByRole("button", { name: /Load more activity/ })).toHaveCount(0)
await marksTab.click()
await expect(marksTab).toHaveAttribute("aria-selected", "true")
await expect(alice.page.locator(`[data-testid^="${tid.botMarkStickerRow("")}"]`))
@@ -919,8 +917,7 @@ let caseJourneyFailure2Present = false
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(sticker.getByRole("button", { name: /Load more activity/ })).toHaveCount(0)
await expect(stop).toBeVisible()
await attachPageScreenshot(testInfo, "bot-work-sticker-activity-running-desktop", alice.page)
await marksTab.click()
@@ -956,13 +953,20 @@ let caseJourneyFailure2Present = false
}))
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 expect(sticker.getByLabel("Loading thoughts")).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)
+ await sticker.getByRole("tab", { name: "Thoughts" }).click()
+ await sticker.getByRole("button", { name: "Open activity log 11", exact: true }).click()
+ await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}`))
+ await gotoAfterUserWsAuth(alice.page, route)
+ await openBotProfile(alice.page, botName)
+ const footer = sticker.locator("footer")
+ await expect(footer.locator("time")).toHaveCount(0)
const ownerLink = alice.page.getByTestId(tid.profileOwnerLink)
await expect(alice.page.getByTestId(tid.profileBotBadge)).toContainText("Bot")
await expect(ownerLink).toBeVisible()
@@ -984,8 +988,9 @@ let caseJourneyFailure2Present = false
"data-placement",
/^(right|left|top|bottom)$/,
)
- const openActivity = alice.page.getByRole("button", {
- name: "Load more activity in the full audit log",
+ const openActivity = sticker.getByRole("button", {
+ name: "Open activity log 11",
+ exact: true,
})
await openActivity.focus()
await expect(openActivity).toBeFocused()