From ccdecd4730a2a09215c89a463d11cb514d24b826 Mon Sep 17 00:00:00 2001 From: Leonhard Breuer Date: Mon, 23 Nov 2026 11:57:12 +0100 Subject: [PATCH 1/2] feat(server): report each bot's status and let bots mark questions GET /v1/agents returns a status for each bot, and /v1/events sends bot-status events on connect and on change: blocked, question, failed, thinking, working, or idle. Request stores and jobs register what they wait for through BotNeeds. The mark_question tool flags a reply as a question that stays open until the owner's next message. --- GLOSSARY.md | 8 + apps/server/src/app/core-layer.ts | 8 +- apps/server/src/app/job-wiring.ts | 35 + apps/server/src/app/tenant.ts | 5 +- apps/server/src/bot-desktop/desktop-jobs.ts | 1 + apps/server/src/bot-desktop/held-actions.ts | 30 +- apps/server/src/bot-ports/bot-extensions.ts | 1 + apps/server/src/bot-ports/bot-needs.ts | 79 ++ apps/server/src/bot-requests/bot-requests.ts | 24 + .../src/bot-secrets/bot-secret-requests.ts | 19 + apps/server/src/bots/agents-api.ts | 6 +- apps/server/src/bots/bot-activity-api.ts | 17 + apps/server/src/bots/bot-status.test.ts | 835 ++++++++++++++++++ apps/server/src/bots/bots-context.ts | 6 + apps/server/src/bots/bots-notifications.ts | 7 +- apps/server/src/bots/bots-service.ts | 19 +- apps/server/src/bots/bots-status.ts | 200 +++++ apps/server/src/bots/bots-test-support.ts | 2 + apps/server/src/bots/bots.ts | 8 +- apps/server/src/bots/mark-question.ts | 34 + apps/server/src/bots/runtime.ts | 13 + apps/server/src/contract/api-contract.ts | 3 +- apps/server/src/contract/api-responses.ts | 20 +- apps/server/src/contract/bot-status.ts | 10 + apps/server/src/contract/tools.ts | 1 + apps/server/src/jobs/coding.ts | 1 + apps/server/src/jobs/jobs.ts | 136 ++- .../message-gateway/message-gateway.test.ts | 2 + apps/server/src/plugins/plugins.ts | 1 + .../src/transcript/chat-question.test.ts | 140 +++ apps/server/src/transcript/chat-question.ts | 48 + .../server/src/voice-gateway/call-requests.ts | 20 +- .../bot-requests/bot-request-card.tsx | 2 +- .../skills/bulk-skill-actions.test.ts | 1 + apps/web/test/agent-fixture.ts | 1 + openapi/bot-status-event.schema.json | 25 + openapi/openapi.json | 47 +- 37 files changed, 1761 insertions(+), 54 deletions(-) create mode 100644 apps/server/src/bot-ports/bot-needs.ts create mode 100644 apps/server/src/bots/bot-status.test.ts create mode 100644 apps/server/src/bots/bots-status.ts create mode 100644 apps/server/src/bots/mark-question.ts create mode 100644 apps/server/src/contract/bot-status.ts create mode 100644 apps/server/src/transcript/chat-question.test.ts create mode 100644 apps/server/src/transcript/chat-question.ts create mode 100644 openapi/bot-status-event.schema.json diff --git a/GLOSSARY.md b/GLOSSARY.md index 58105f94..87d8e782 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -18,6 +18,14 @@ _Avoid_: Bot creation request The continuous direct-message exchange between a bot and its owner, including work the bot performs in the background. _Avoid_: Conversation session, new chat +**Chat question**: +A bot's reply that it marked as a question it needs the owner to answer before it can go on. It stays open until the owner's next message in the bot chat. +_Avoid_: Job question, prompt, notification + +**Bot status**: +What a bot is doing (idle, thinking, or working) or that its latest turn failed, unless it needs the owner: it has a question (a job question or a chat question), or it is blocked by a request or held action that waits for the owner's decision. A retry is working, not blocked. +_Avoid_: Presence, online status + **Bot chat delivery**: The progress of an owner's message from sending to confirmation in the bot chat's transcript, including failed sends and retries. _Avoid_: Message execution, completed bot work diff --git a/apps/server/src/app/core-layer.ts b/apps/server/src/app/core-layer.ts index 1f50a406..964319c0 100644 --- a/apps/server/src/app/core-layer.ts +++ b/apps/server/src/app/core-layer.ts @@ -4,6 +4,7 @@ import { PushDatabase } from "../push/push-database"; import { DesktopControl } from "../bot-desktop/desktop-control"; import { HeldActions } from "../bot-desktop/held-actions"; import { BotDeletion } from "../bot-ports/bot-deletion"; +import { BotNeeds } from "../bot-ports/bot-needs"; import { BotNotices } from "../bot-ports/bot-notices"; import { CallNotes } from "../bot-ports/call-notes"; import { CredentialAuthorities } from "../credentials/credential-authority"; @@ -53,7 +54,12 @@ export const coreLayer = (dataDir: string) => Layer.mergeAll(BotSecretRequests.layer, BotSecretUses.layer), ), Layer.provideMerge( - Layer.mergeAll(BotNotices.layer, BotDeletion.layer, CallNotes.layer), + Layer.mergeAll( + BotNotices.layer, + BotDeletion.layer, + CallNotes.layer, + BotNeeds.layer, + ), ), Layer.provideMerge(secretsLayer(passwordManagers)), Layer.provideMerge(PushDatabase.layer(dataDir)), diff --git a/apps/server/src/app/job-wiring.ts b/apps/server/src/app/job-wiring.ts index b9fd0f6b..2bf30e19 100644 --- a/apps/server/src/app/job-wiring.ts +++ b/apps/server/src/app/job-wiring.ts @@ -1,6 +1,10 @@ import { Effect, Layer } from "effect"; import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; +import { BotNeeds } from "../bot-ports/bot-needs"; +import { AgentRepository } from "../bot-store/agent-repository"; +import { ConversationRepository } from "../bot-store/conversation-repository"; import { Bots } from "../bots/bots"; +import { BotRuntime } from "../bots/runtime"; import { BotMessaging } from "../bot-messaging/bot-messaging"; import { jobExtensions, pluginJobKinds, Plugins } from "../plugins/plugins"; @@ -24,6 +28,37 @@ export const jobTools = Layer.effectDiscard( }), ); +export const jobNeeds = Layer.effectDiscard( + Effect.gen(function* () { + const needs = yield* BotNeeds; + const agents = yield* AgentRepository; + const conversations = yield* ConversationRepository; + const runtime = yield* BotRuntime; + const jobKinds = pluginJobKinds(yield* Plugins); + + yield* needs.provide( + Effect.fnUntraced(function* (agentId) { + const agent = yield* agents.get(agentId); + + if (!agent || !(yield* conversations.list(agentId, true)).length) { + return undefined; + } + + return yield* Effect.promise(() => runtime.jobNeed(agent)); + }), + ); + + yield* whileOpen(() => + jobKinds.flatMap( + (kind) => + kind.onChange?.( + (agentId) => void Effect.runPromise(needs.changed(agentId)), + ) ?? [], + ), + ); + }), +); + export const jobAnswers = Layer.effectDiscard( Effect.gen(function* () { const bots = yield* Bots; diff --git a/apps/server/src/app/tenant.ts b/apps/server/src/app/tenant.ts index 43a744b4..9ebd76fe 100644 --- a/apps/server/src/app/tenant.ts +++ b/apps/server/src/app/tenant.ts @@ -9,6 +9,7 @@ import { BotMessaging } from "../bot-messaging/bot-messaging"; import { BotActivity } from "../bots/bot-activity"; import { reviewConversations } from "../learning/review-kind"; import { BotExtensions } from "../bot-ports/bot-extensions"; +import { markQuestionTools } from "../bots/mark-question"; import { reactionTools } from "../bots/reaction"; import { codemodeTools } from "../integrations/codemode"; import { configuredWebSearchTools } from "../web-search/web-search-tools"; @@ -57,7 +58,7 @@ import type { CoreServices } from "./core-layer"; import { runnerOf } from "../shared/runner"; import { builtinPlugins, builtinVendors } from "./builtin-plugins"; import { heldActionNotices } from "../bot-desktop/held-action-notices"; -import { jobAnswers, jobQuestions, jobTools } from "./job-wiring"; +import { jobAnswers, jobNeeds, jobQuestions, jobTools } from "./job-wiring"; import { conversationEnv, jobExtensions, @@ -294,6 +295,7 @@ function accountLayer(options: TenantOptions, dataDir: string) { curation, skillUpdateChecks, jobAnswers, + jobNeeds, jobQuestions, heldActionNotices, jobTools, @@ -329,6 +331,7 @@ function accountLayer(options: TenantOptions, dataDir: string) { displayTools, configuredWebSearchTools, reactionTools, + markQuestionTools, ); const signIns = Layer.mergeAll(ProviderSignIns.layer, integrations); diff --git a/apps/server/src/bot-desktop/desktop-jobs.ts b/apps/server/src/bot-desktop/desktop-jobs.ts index 656b9a3f..8db16133 100644 --- a/apps/server/src/bot-desktop/desktop-jobs.ts +++ b/apps/server/src/bot-desktop/desktop-jobs.ts @@ -135,6 +135,7 @@ export const desktopPlugin = ( env: (agentId, target, context) => desktop.env(workspaces, agentId, target, context), onAnswer: desktop.onAnswer, + onChange: desktop.onChange, }, ] : [], diff --git a/apps/server/src/bot-desktop/held-actions.ts b/apps/server/src/bot-desktop/held-actions.ts index a9095b3b..e1a61d01 100644 --- a/apps/server/src/bot-desktop/held-actions.ts +++ b/apps/server/src/bot-desktop/held-actions.ts @@ -3,6 +3,7 @@ import { and, desc, eq } from "drizzle-orm"; import { Context, Deferred, Effect, Layer } from "effect"; import { z } from "zod"; import type { OwnerMessage } from "../jobs/owner-request"; +import { BotNeeds, needWhen } from "../bot-ports/bot-needs"; import { Conflict, NotFound } from "../shared/errors"; import { ProductDatabase } from "../shared/product-database"; import { HELD_ACTION_STATUSES, OWNER_MESSAGE_SOURCES } from "../shared/domain"; @@ -109,6 +110,7 @@ export class HeldActions extends Context.Service< HeldActions, Effect.gen(function* () { const db = yield* ProductDatabase; + const needs = yield* BotNeeds; const listeners = keyedListeners(); const heldListeners = new Set< @@ -131,6 +133,25 @@ export class HeldActions extends Context.Service< return found; }); + yield* needs.provide( + needWhen("blocked", (agentId) => + db + .select({ id: heldActions.id }) + .from(heldActions) + .where( + and( + eq(heldActions.agentId, agentId), + eq(heldActions.status, "pending"), + ), + ) + .limit(1) + .pipe( + Effect.orDie, + Effect.map((rows) => rows.length > 0), + ), + ), + ); + const hold = Effect.fn("HeldActions.hold")(function* (input: HoldInput) { const values = { ...input, @@ -143,6 +164,7 @@ export class HeldActions extends Context.Service< }; yield* db.insert(heldActions).values(values).pipe(Effect.orDie); + yield* needs.changed(input.agentId); return heldOf(values); }); @@ -186,6 +208,7 @@ export class HeldActions extends Context.Service< if (decided) { listeners.notify(id, decision); + yield* needs.changed(agentId); return heldOf(decided); } @@ -204,11 +227,14 @@ export class HeldActions extends Context.Service< .update(heldActions) .set({ status: "expired", decidedAt: yield* nowIso }) .where(and(eq(heldActions.id, id), eq(heldActions.status, "pending"))) - .returning({ id: heldActions.id }) + .returning({ id: heldActions.id, agentId: heldActions.agentId }) .pipe(Effect.orDie); - if (changed.length) { + const [expired] = changed; + + if (expired) { listeners.notify(id, { status: "expired" }); + yield* needs.changed(expired.agentId); } }); diff --git a/apps/server/src/bot-ports/bot-extensions.ts b/apps/server/src/bot-ports/bot-extensions.ts index 68727f01..ad76f98c 100644 --- a/apps/server/src/bot-ports/bot-extensions.ts +++ b/apps/server/src/bot-ports/bot-extensions.ts @@ -60,6 +60,7 @@ export const ExtensionPosition = { desktopScreenshot: 62, webSearch: 65, reaction: 70, + markQuestion: 72, voice: 75, callRequests: 76, jobs: 80, diff --git a/apps/server/src/bot-ports/bot-needs.ts b/apps/server/src/bot-ports/bot-needs.ts new file mode 100644 index 00000000..b5543bcc --- /dev/null +++ b/apps/server/src/bot-ports/bot-needs.ts @@ -0,0 +1,79 @@ +import { Context, Effect, Layer, Ref } from "effect"; +import type { Scope } from "effect"; + +export type BotNeed = "blocked" | "question" | "working"; + +const STRENGTH: Record = { + blocked: 3, + question: 2, + working: 1, +}; + +export type NeedSource = ( + agentId: string, +) => Effect.Effect; + +export const strongest = ( + needs: ReadonlyArray, +): BotNeed | undefined => + needs.reduce( + (best, need) => + need && (!best || STRENGTH[need] > STRENGTH[best]) ? need : best, + undefined, + ); + +export const needWhen = + (need: BotNeed, pending: (agentId: string) => Effect.Effect) => + (agentId: string) => + Effect.map(pending(agentId), (found) => (found ? need : undefined)); + +export class BotNeeds extends Context.Service< + BotNeeds, + { + readonly provide: ( + source: NeedSource, + ) => Effect.Effect; + readonly current: (agentId: string) => Effect.Effect; + readonly changed: (agentId: string) => Effect.Effect; + readonly onChanged: (listener: (agentId: string) => void) => () => void; + } +>()("crumble/bot-ports/BotNeeds") { + static readonly layer = Layer.effect( + BotNeeds, + Effect.gen(function* () { + const sources = yield* Ref.make>([]); + const listeners = new Set<(agentId: string) => void>(); + + return BotNeeds.of({ + provide: (source) => + Effect.acquireRelease( + Ref.update(sources, (current) => [...current, source]), + () => + Ref.update(sources, (current) => + current.filter((each) => each !== source), + ), + ), + current: (agentId) => + Effect.flatMap(Ref.get(sources), (current) => + Effect.map( + Effect.forEach(current, (source) => source(agentId), { + concurrency: "unbounded", + }), + strongest, + ), + ), + changed: (agentId) => + Effect.sync(() => { + for (const listener of listeners) { + listener(agentId); + } + }), + onChanged: (listener) => { + listeners.add(listener); + + return () => void listeners.delete(listener); + }, + }); + }), + ); +} diff --git a/apps/server/src/bot-requests/bot-requests.ts b/apps/server/src/bot-requests/bot-requests.ts index f548a974..04fef7bf 100644 --- a/apps/server/src/bot-requests/bot-requests.ts +++ b/apps/server/src/bot-requests/bot-requests.ts @@ -11,6 +11,7 @@ import { ProductDatabase } from "../shared/product-database"; import { nowIso } from "../shared/time"; import { AgentRepository } from "../bot-store/agent-repository"; import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; +import { BotNeeds, needWhen } from "../bot-ports/bot-needs"; import { BotNotices, loggedNotices } from "../bot-ports/bot-notices"; import { Conflict, NotFound } from "../shared/errors"; import type { AppError } from "../shared/errors"; @@ -78,6 +79,26 @@ export class BotRequests extends Context.Service< const db = yield* ProductDatabase; const agents = yield* AgentRepository; const notices = yield* BotNotices; + const needs = yield* BotNeeds; + + yield* needs.provide( + needWhen("blocked", (agentId) => + db + .select({ id: botRequests.id }) + .from(botRequests) + .where( + and( + eq(botRequests.agentId, agentId), + eq(botRequests.status, "pending"), + ), + ) + .limit(1) + .pipe( + Effect.orDie, + Effect.map((rows) => rows.length > 0), + ), + ), + ); const notify = loggedNotices(notices, "Bot request notice failed"); @@ -208,6 +229,7 @@ export class BotRequests extends Context.Service< ), ); const row = yield* getRow(agentId, id); + yield* needs.changed(agentId); return row ? requestOf(row) @@ -265,6 +287,7 @@ export class BotRequests extends Context.Service< ) .pipe(Effect.catchTag("SqlError", (error) => Effect.die(error))); + yield* needs.changed(agentId); yield* notify( agentId, `The owner approved your request for bot ${agent.name}.`, @@ -285,6 +308,7 @@ export class BotRequests extends Context.Service< return yield* alreadyDecided(agentId, requestId); } + yield* needs.changed(agentId); const updated = yield* getRow(agentId, requestId); if (!updated) { diff --git a/apps/server/src/bot-secrets/bot-secret-requests.ts b/apps/server/src/bot-secrets/bot-secret-requests.ts index 1dbda418..e650b4ec 100644 --- a/apps/server/src/bot-secrets/bot-secret-requests.ts +++ b/apps/server/src/bot-secrets/bot-secret-requests.ts @@ -1,5 +1,6 @@ import { and, asc, eq } from "drizzle-orm"; import { Context, Effect, Layer } from "effect"; +import { BotNeeds, needWhen } from "../bot-ports/bot-needs"; import { BotNotices, requestAnswers } from "../bot-ports/bot-notices"; import { ProductDatabase } from "../shared/product-database"; import { required } from "../shared/required"; @@ -75,6 +76,21 @@ export class BotSecretRequests extends Context.Service< Effect.gen(function* () { const db = yield* ProductDatabase; const notices = yield* BotNotices; + const needs = yield* BotNeeds; + + yield* needs.provide( + needWhen("blocked", (agentId) => + db + .select({ name: botSecretRequests.name }) + .from(botSecretRequests) + .where(eq(botSecretRequests.agentId, agentId)) + .limit(1) + .pipe( + Effect.orDie, + Effect.map((rows) => rows.length > 0), + ), + ), + ); const get = Effect.fn("BotSecretRequests.get")(function* ( agentId: string, @@ -105,6 +121,8 @@ export class BotSecretRequests extends Context.Service< return false; } + yield* needs.changed(agentId); + yield* requestAnswers(notices, kind)(agentId, name, text); return true; @@ -147,6 +165,7 @@ export class BotSecretRequests extends Context.Service< set: row, }) .pipe(Effect.orDie); + yield* needs.changed(agentId); return required( yield* get(agentId, kind, input.name), diff --git a/apps/server/src/bots/agents-api.ts b/apps/server/src/bots/agents-api.ts index 4701f91b..672f51c3 100644 --- a/apps/server/src/bots/agents-api.ts +++ b/apps/server/src/bots/agents-api.ts @@ -28,8 +28,10 @@ const registerAgentDefinitionRoutes = (options: AgentRoutesOptions) => { register.plain(routes.listAgents, async (c) => c.json( - (await service.agentPreviews()).map(({ agent, lastMessage }) => { - return lastMessage ? { ...agent, lastMessage } : agent; + (await service.agentPreviews()).map(({ agent, lastMessage, status }) => { + return lastMessage + ? { ...agent, lastMessage, status } + : { ...agent, status }; }), 200, ), diff --git a/apps/server/src/bots/bot-activity-api.ts b/apps/server/src/bots/bot-activity-api.ts index 3fef6cdd..cd407b7c 100644 --- a/apps/server/src/bots/bot-activity-api.ts +++ b/apps/server/src/bots/bot-activity-api.ts @@ -42,7 +42,22 @@ export function registerBotActivityRoutes(options: { streamEvents(c, async ({ stream, close, onClose }) => { const send = activitySender(serverId, stream, close); + const sentStatuses = new Map(); + + const sendStatus = (event: { agentId: string; status: string }) => { + if ( + sentStatuses.get(event.agentId) !== event.status && + !stream.aborted + ) { + sentStatuses.set(event.agentId, event.status); + stream + .writeSSE({ event: "bot-status", data: JSON.stringify(event) }) + .catch(close); + } + }; + onClose(service.onActivity(send)); + onClose(service.onBotStatus(sendStatus)); for (const { agent, lastMessage } of await service.agentPreviews()) { send({ @@ -52,6 +67,8 @@ export function registerBotActivityRoutes(options: { lastMessage, }); } + + await service.requestStatuses(); }), ); } diff --git a/apps/server/src/bots/bot-status.test.ts b/apps/server/src/bots/bot-status.test.ts new file mode 100644 index 00000000..b468b248 --- /dev/null +++ b/apps/server/src/bots/bot-status.test.ts @@ -0,0 +1,835 @@ +import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createModels } from "@earendil-works/pi-ai"; +import type { Message } from "@earendil-works/pi-ai"; +import type { Extension } from "@earendil-works/pi-durable"; +import { + fauxAssistantMessage, + fauxProvider, + fauxText, + fauxToolCall, +} from "@earendil-works/pi-ai/providers/faux"; +import type { FauxResponseStep } from "@earendil-works/pi-ai/providers/faux"; +import { Context, Effect, Layer, Scope } from "effect"; +import { inertCredentials } from "../../test/support/job-wiring"; +import { DirectoryWorkspaces } from "../../test/support/jobs"; +import { testAPI, testVoiceGateway } from "../../test/support/api"; +import { codingPlugin } from "../jobs/coding"; +import { jobNeeds } from "../app/job-wiring"; +import { conversationEnv, jobExtensions, Plugins } from "../plugins/plugins"; +import { CallRequests } from "../voice-gateway/call-requests"; +import { VoiceGateway } from "../voice-gateway/voice-gateway"; +import { startServer } from "../app/server"; +import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; +import { Store } from "../../test/support/store"; +import type { Runner } from "../shared/runner"; +import { until } from "../../test/support/until"; +import { ScheduleRepository } from "../automations/schedule-repository"; +import { HeldActions } from "../bot-desktop/held-actions"; +import { BotRequests } from "../bot-requests/bot-requests"; +import { BotSecretRequests } from "../bot-secrets/bot-secret-requests"; +import { agentInput } from "../contract/agents"; +import { scheduleInput } from "../contract/schedules"; +import { MARK_QUESTION_TOOL_NAME } from "../contract/tools"; +import { scheduleRequest } from "../shared/request-ids"; +import { standaloneBots } from "./bots-test-support"; +import { markQuestionExtension } from "./mark-question"; +import { AgentRuntime } from "./runtime"; +import type { FauxResponseFactory } from "@earendil-works/pi-ai/providers/faux"; + +setDefaultTimeout(30_000); + +const token = "t".repeat(40); +const dirs: Array = []; +const closers: Array<() => Promise> = []; + +afterEach(async () => { + while (closers.length) { + await closers.pop()!(); + } + + while (dirs.length) { + rmSync(dirs.pop()!, { recursive: true, force: true }); + } +}); + +type CoreNeeds = Store["runtime"] extends Runner ? R : never; + +type StatusFrame = { agentId: string; status: string }; + +type SetupOptions = { + extensions?: Array; + jobs?: boolean; + tokensPerSecond?: number; +}; + +function setup(responses: Array, options: SetupOptions = {}) { + const dir = mkdtempSync(join(tmpdir(), "bot-status-")); + dirs.push(dir); + + const faux = fauxProvider({ + provider: "faux", + models: [{ id: "chat", input: ["text"] }], + ...(options.tokensPerSecond && { + tokensPerSecond: options.tokensPerSecond, + }), + }); + + faux.setResponses(responses); + const models = createModels(); + models.setProvider(faux.provider); + + const store = new Store(dir); + mkdirSync(join(dir, "workspace")); + + const plugin = codingPlugin( + new DirectoryWorkspaces(join(dir, "workspace")), + () => 900_000, + inertCredentials, + ); + + const kinds = options.jobs ? (plugin.jobKinds ?? []) : []; + + const service = standaloneBots( + store, + new AgentRuntime( + dir, + runtimeCallbacks({ + models, + extensions: (agent) => [ + markQuestionExtension(), + ...(options.extensions ?? []), + ...jobExtensions(kinds, agent).chat, + ], + jobExtensions: (agent) => jobExtensions(kinds, agent).job, + env: (agent, target, context) => + conversationEnv(kinds, agent, target, context), + }), + ), + ); + + if (options.jobs) { + service.effects.runSync( + Layer.buildWithScope( + jobNeeds.pipe(Layer.provide(Layer.succeed(Plugins, [plugin]))), + Scope.makeUnsafe(), + ), + ); + } + + const callRequests = () => + service.effects.runSync( + Layer.buildWithScope( + CallRequests.layer.pipe( + Layer.provide( + Layer.succeed(VoiceGateway, testVoiceGateway(store.runtime)), + ), + ), + Scope.makeUnsafe(), + ).pipe(Effect.map(Context.get(CallRequests))), + ); + + closers.push(() => service.close()); + + const app = testAPI(service, token); + + const bot = (name: string, tools: Array = []) => + store.createAgent({ + name, + description: "", + instructions: "Answer", + provider: "faux", + model: "chat", + enabled: true, + tools, + skills: [], + mcpServers: [], + delegates: [], + }); + + const request = (path: string, init: RequestInit = {}) => + app.request(path, { + ...init, + headers: { + authorization: `Bearer ${token}`, + "content-type": "application/json", + }, + }); + + const say = (agentId: string, content: string) => + request(`/v1/agents/${agentId}/messages`, { + method: "POST", + body: JSON.stringify({ content, requestId: crypto.randomUUID() }), + }); + + const statusOf = async (agentId: string) => { + const listed: Array<{ id: string; status: string }> = await ( + await request("/v1/agents") + ).json(); + + return listed.find((each) => each.id === agentId)?.status; + }; + + const core = store.runtime; + + const built = ( + layer: Layer.Layer, + key: Context.Key, + ): S => + core.runSync( + Layer.buildWithScope(layer, Scope.makeUnsafe()).pipe( + Effect.map(Context.get(key)), + ), + ); + + return { + app, + bot, + request, + say, + statusOf, + service, + store, + core, + built, + callRequests, + }; +} + +async function watch(app: { + request: (path: string, init: RequestInit) => any; +}) { + const response: Response = await app.request("/v1/events", { + headers: { authorization: `Bearer ${token}` }, + }); + + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + const frames: Array = []; + let buffer = ""; + + const reading = (async () => { + for (;;) { + const { value, done } = await reader.read(); + + if (done) { + return; + } + buffer += decoder.decode(value, { stream: true }); + const parts = buffer.split("\n\n"); + buffer = parts.pop() ?? ""; + + for (const part of parts) { + const [event, data] = part.split("\n"); + + if (event === "event: bot-status" && data) { + frames.push(JSON.parse(data.slice("data: ".length))); + } + } + } + })(); + + closers.push(async () => { + await reader.cancel(); + await reading; + }); + + const of = (agentId: string) => + frames.filter((frame) => frame.agentId === agentId).map((f) => f.status); + + return { frames, of }; +} + +const noRepeats = (statuses: Array) => + statuses.every((status, index) => status !== statuses[index - 1]); + +const toolCall = (name: string) => + fauxAssistantMessage([fauxToolCall(name, {})], { stopReason: "toolUse" }); + +describe("bot status over HTTP", () => { + test("lists a status for every bot and replays it when the stream connects", async () => { + const { app, bot, statusOf } = setup([]); + const first = bot("First"); + const second = bot("Second"); + + expect(await statusOf(first.id)).toBe("idle"); + expect(await statusOf(second.id)).toBe("idle"); + + const events = await watch(app); + await until( + () => events.of(first.id).length > 0 && events.of(second.id).length > 0, + ); + + expect(events.of(first.id)).toEqual(["idle"]); + expect(events.of(second.id)).toEqual(["idle"]); + }); + + test("a chat question turns the bot to question until the owner answers", async () => { + const { app, bot, say, statusOf, service, store } = setup([ + toolCall(MARK_QUESTION_TOOL_NAME), + fauxAssistantMessage("Which database should I use?"), + fauxAssistantMessage("Inbox is empty."), + fauxAssistantMessage("Postgres it is."), + ]); + + const agent = bot("Asker"); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + expect((await say(agent.id, "Set up storage")).status).toBeLessThan(300); + await until(() => events.of(agent.id).includes("question")); + expect(await statusOf(agent.id)).toBe("question"); + + const schedule = store.runtime.runSync( + Effect.gen(function* () { + return yield* (yield* ScheduleRepository).create( + scheduleInput.parse({ + agentId: agent.id, + name: "Inbox check", + prompt: "Check the inbox", + cron: "0 * * * *", + }), + null, + ); + }), + ); + + const settledAt = events.of(agent.id).length; + + const run = await service.dispatch( + agent.id, + schedule.prompt, + scheduleRequest(schedule.id, "2026-11-14T08:00:00.000Z"), + schedule.id, + ); + + await until(() => { + const status = store.getExecution(run.id)?.status; + + return status !== "pending" && status !== "running"; + }); + expect(await statusOf(agent.id)).toBe("question"); + await Bun.sleep(300); + expect(events.of(agent.id).slice(settledAt)).toEqual([]); + + expect((await say(agent.id, "Postgres")).status).toBeLessThan(300); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + + const seen = events.of(agent.id); + expect(seen.indexOf("question")).toBeGreaterThan(0); + expect(seen.filter((status) => status === "question")).toHaveLength(1); + expect(noRepeats(seen)).toBe(true); + }); + + test("a bot request blocks the bot until the owner answers", async () => { + const { app, bot, statusOf, built, core } = setup([ + fauxAssistantMessage("Thanks, noted."), + ]); + + const agent = bot("Requester"); + const requests = built(BotRequests.layer, BotRequests); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + const asked = await core.runPromise( + requests.request(agent.id, { + proposal: agentInput.parse({ name: "Helper" }), + reason: "I need help", + }), + ); + + await until(() => events.of(agent.id).includes("blocked")); + expect(await statusOf(agent.id)).toBe("blocked"); + + await core.runPromise(requests.decline(agent.id, asked.id)); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + + expect(events.of(agent.id)[0]).toBe("idle"); + expect(events.of(agent.id)).toContain("blocked"); + expect(noRepeats(events.of(agent.id))).toBe(true); + }); + + test("a credential request and a held action block the bot, each ending when answered", async () => { + const { app, bot, statusOf, core } = setup([ + fauxAssistantMessage("Thanks, noted."), + ]); + + const agent = bot("Waiting"); + const other = bot("Bystander"); + const secrets = core.runSync( + Effect.flatMap(BotSecretRequests, Effect.succeed), + ); + const held = core.runSync(Effect.flatMap(HeldActions, Effect.succeed)); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + const action = await core.runPromise( + held.hold({ + agentId: agent.id, + job: "desk", + action: "Click buy", + page: null, + ownerMessages: [], + reason: "Spends money", + }), + ); + + await until(() => events.of(agent.id).includes("blocked")); + expect(await statusOf(agent.id)).toBe("blocked"); + + await core.runPromise( + secrets.ask(agent.id, "credential", { + name: "api", + hosts: ["example.com"], + reason: "Needs the API", + }), + ); + await core.runPromise( + held.decide(agent.id, action.id, { status: "approved" }), + ); + expect(await statusOf(agent.id)).toBe("blocked"); + + await core.runPromise(secrets.decline(agent.id, "credential", "api")); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + + expect(noRepeats(events.of(agent.id))).toBe(true); + expect(events.of(other.id)).toEqual(["idle"]); + }); + + test("a failed turn shows as failed until the next turn succeeds", async () => { + const { app, bot, say, statusOf } = setup([ + fauxAssistantMessage("", { stopReason: "error", errorMessage: "boom" }), + fauxAssistantMessage("Back again."), + ]); + + const agent = bot("Flaky"); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Try something"); + await until(async () => (await statusOf(agent.id)) === "failed"); + await until(() => events.of(agent.id).at(-1) === "failed"); + + await say(agent.id, "Try again"); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + + expect(events.of(agent.id)).toContain("failed"); + expect(noRepeats(events.of(agent.id))).toBe(true); + }); +}); + +const messageText = (message: Message) => + (Array.isArray(message.content) + ? message.content + : [{ type: "text" as const, text: message.content }] + ) + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join(""); + +const call = (name: string, args: Record) => + fauxAssistantMessage(fauxToolCall(name, args), { stopReason: "toolUse" }); + +function gate() { + let open!: () => void; + + const opened = new Promise((resolve) => { + open = resolve; + }); + + return { opened, open }; +} + +function jobScript(work: Promise): Array { + const step: FauxResponseFactory = async (context) => { + const tools = context.messages.flatMap((message) => + message.role === "system" + ? (message.toolsAdded ?? []).map((tool) => tool.name) + : [], + ); + + const last = context.messages.findLast( + (message) => message.role !== "system", + )!; + + const text = messageText(last); + + if (tools.includes("ask_owner")) { + if (last.role === "user" && text.includes("answered")) { + return fauxAssistantMessage([fauxText("Used the answer.")]); + } + + if (text === "ask") { + return call("ask_owner", { question: "Which color?" }); + } + await work; + + return fauxAssistantMessage([fauxText("Worked.")]); + } + + if (text.startsWith("[coding job")) { + return fauxAssistantMessage([fauxText("The job is finished.")]); + } + + if (text.includes("Start work") || text.includes("Start asking")) { + return call("coding", { + action: "start", + name: "builder", + message: text.includes("Start work") ? "work" : "ask", + }); + } + + if (text.includes("Stop it")) { + return call("coding", { action: "stop", name: "builder" }); + } + + return fauxAssistantMessage([fauxText("Okay.")]); + }; + + return Array.from({ length: 40 }, () => step); +} + +const askedQuestion = async ( + request: (path: string, init?: RequestInit) => Promise | Response, + agentId: string, +) => { + const listed = (await ( + await request(`/v1/agents/${agentId}/coding-jobs`) + ).json()) as { jobs: Array<{ name: string; question?: { id: string } }> }; + + return listed.jobs[0]?.question; +}; + +const answer = ( + request: (path: string, init?: RequestInit) => Promise | Response, + agentId: string, + questionId: string, +) => + request(`/v1/agents/${agentId}/coding-jobs/builder/answer`, { + method: "POST", + body: JSON.stringify({ questionId, text: "blue" }), + }); + +describe("bot status from jobs, calls and polling", () => { + test("a working job keeps the bot working until it reports", async () => { + const work = gate(); + const { app, bot, say, statusOf } = setup(jobScript(work.opened), { + jobs: true, + }); + const agent = bot("Builder", ["coding"]); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Start work"); + await until(() => events.of(agent.id).includes("working")); + await Bun.sleep(1500); + expect(await statusOf(agent.id)).toBe("working"); + expect(events.of(agent.id).at(-1)).toBe("working"); + + work.open(); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + expect(noRepeats(events.of(agent.id))).toBe(true); + }); + + test("a job's question turns the bot to question until it is answered", async () => { + const work = gate(); + + const { app, bot, say, statusOf, request } = setup(jobScript(work.opened), { + jobs: true, + }); + const agent = bot("Builder", ["coding"]); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Start asking"); + await until(() => events.of(agent.id).at(-1) === "question"); + await Bun.sleep(1200); + expect(await statusOf(agent.id)).toBe("question"); + const question = await askedQuestion(request, agent.id); + expect(question).toBeDefined(); + + expect((await answer(request, agent.id, question!.id)).status).toBe(204); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + expect(noRepeats(events.of(agent.id))).toBe(true); + }); + + test("a job stopped with a pending question still lists it and can still be answered", async () => { + const work = gate(); + + const { app, bot, say, statusOf, request, store } = setup( + jobScript(work.opened), + { jobs: true }, + ); + const agent = bot("Builder", ["coding"]); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Start asking"); + await until(() => events.of(agent.id).at(-1) === "question"); + const question = await askedQuestion(request, agent.id); + + const stopping = await (await say(agent.id, "Stop it")).json(); + await until(() => { + const status = store.getExecution(stopping.id)?.status; + + return status === "done" || status === "failed"; + }); + await Bun.sleep(500); + + expect(await askedQuestion(request, agent.id)).toEqual(question); + expect(await statusOf(agent.id)).toBe("question"); + + expect((await answer(request, agent.id, question!.id)).status).toBe(204); + await until(async () => (await statusOf(agent.id)) === "idle"); + }); + + test("a pending call request blocks the bot until the owner answers", async () => { + const { app, bot, statusOf, callRequests, core } = setup([ + fauxAssistantMessage("Understood."), + ]); + const agent = bot("Caller"); + const calls = callRequests(); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + const asked = await core.runPromise( + calls.request(agent.id, { + number: "+49307654321", + callee: "Dentist", + goal: "Book a visit", + opening: "Hello", + }), + ); + + await until(() => events.of(agent.id).includes("blocked")); + expect(await statusOf(agent.id)).toBe("blocked"); + + await core.runPromise(calls.decline(agent.id, asked.id)); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + expect(noRepeats(events.of(agent.id))).toBe(true); + }); + + test("the poll moves a running turn from thinking to working", async () => { + const thought = gate(); + + const { app, bot, say, statusOf } = setup( + [ + async () => { + await thought.opened; + + return fauxAssistantMessage( + Array.from({ length: 24 }, (_, index) => `word${index}`).join(" "), + ); + }, + ], + { tokensPerSecond: 10 }, + ); + + const agent = bot("Thinker"); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Go"); + await until(() => events.of(agent.id).includes("thinking")); + expect(events.of(agent.id)).not.toContain("working"); + + thought.open(); + await until(() => events.of(agent.id).at(-1) === "working"); + expect(await statusOf(agent.id)).toBe("working"); + + await until(() => events.of(agent.id).at(-1) === "idle"); + expect(events.of(agent.id)).toEqual([ + "idle", + "thinking", + "working", + "idle", + ]); + }); + + test("a question written in the message that marks it counts", async () => { + const { app, bot, say, statusOf } = setup([ + fauxAssistantMessage( + [ + fauxText("Which database?"), + fauxToolCall(MARK_QUESTION_TOOL_NAME, {}), + ], + { stopReason: "toolUse" }, + ), + fauxAssistantMessage(""), + ]); + + const agent = bot("Asker"); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Set up storage"); + await until(() => events.of(agent.id).at(-1) === "question"); + expect(await statusOf(agent.id)).toBe("question"); + }); +}); + +describe("bot status ordering", () => { + test("a slow computation never overwrites a newer status", async () => { + const { app, bot, say, statusOf, service, core } = setup([ + fauxAssistantMessage("Hello."), + ]); + + const agent = bot("Slow"); + const held = core.runSync(Effect.flatMap(HeldActions, Effect.succeed)); + const events = await watch(app); + await until(() => events.of(agent.id).length > 0); + + await say(agent.id, "Hi"); + await until(async () => (await statusOf(agent.id)) === "idle"); + await until(() => events.of(agent.id).at(-1) === "idle"); + + const hold = () => + core.runPromise( + held.hold({ + agentId: agent.id, + job: "desk", + action: "Click", + page: null, + ownerMessages: [], + reason: "Spends money", + }), + ); + + const first = await hold(); + await until(() => events.of(agent.id).at(-1) === "blocked"); + + const real = service.runtime.snapshot.bind(service.runtime); + let slow = true; + + service.runtime.snapshot = async (...args) => { + const read = await real(...args); + + if (slow) { + slow = false; + await Bun.sleep(600); + } + + return read; + }; + + await core.runPromise( + held.decide(agent.id, first.id, { status: "approved" }), + ); + await until(() => !slow); + await hold(); + + await Bun.sleep(1200); + expect(await statusOf(agent.id)).toBe("blocked"); + expect(events.of(agent.id).at(-1)).toBe("blocked"); + expect(noRepeats(events.of(agent.id))).toBe(true); + }); +}); + +describe("bot status across accounts", () => { + test("another account's stream never sees a bot's status", async () => { + const dataDir = mkdtempSync(join(tmpdir(), "bot-status-accounts-")); + dirs.push(dataDir); + const running = await startServer({ dataDir, port: 0 }); + closers.push(() => running.close()); + + const signUp = async (suffix: string) => { + const response = await fetch( + new URL("/api/auth/sign-up/email", running.server.url), + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + name: `Test ${suffix}`, + email: `${suffix}@example.test`, + password: "correct horse battery staple", + }), + }, + ); + + const body = (await response.json()) as { token: string }; + + return { authorization: `Bearer ${body.token}` }; + }; + + const first = await signUp(`first-${crypto.randomUUID()}`); + const second = await signUp(`second-${crypto.randomUUID()}`); + + const json = (headers: Record) => ({ + ...headers, + "content-type": "application/json", + }); + + const url = (path: string) => new URL(path, running.server.url); + + const created = await fetch(url("/v1/agents"), { + method: "POST", + headers: json(first), + body: JSON.stringify({ name: "Private bot" }), + }); + + const agent = (await created.json()) as { id: string }; + + const streams = await Promise.all( + [first, second].map(async (headers) => { + const frames: Array = []; + const response = await fetch(url("/v1/events"), { headers }); + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + + const reading = (async () => { + let buffer = ""; + + for (;;) { + const { value, done } = await reader.read(); + + if (done) { + return; + } + buffer += decoder.decode(value, { stream: true }); + + for (const match of buffer.matchAll( + /event: bot-status\ndata: (.*)\n\n/g, + )) { + frames.push(JSON.parse(match[1]!)); + } + buffer = buffer.slice(buffer.lastIndexOf("\n\n") + 2); + } + })(); + + closers.push(async () => { + await reader.cancel(); + await reading; + }); + + return frames; + }), + ); + + const [owned, foreign] = streams; + await until(() => owned!.some((frame) => frame.agentId === agent.id)); + + await fetch(url(`/v1/agents/${agent.id}/messages`), { + method: "POST", + headers: json(first), + body: JSON.stringify({ + content: "hello", + requestId: crypto.randomUUID(), + }), + }); + await until(() => owned!.some((frame) => frame.status !== "idle")); + await Bun.sleep(300); + + expect(foreign).toEqual([]); + + const secondList = await fetch(url("/v1/agents"), { headers: second }); + expect(await secondList.json()).toEqual([]); + }); +}); diff --git a/apps/server/src/bots/bots-context.ts b/apps/server/src/bots/bots-context.ts index bb10863d..89b94c9e 100644 --- a/apps/server/src/bots/bots-context.ts +++ b/apps/server/src/bots/bots-context.ts @@ -11,7 +11,9 @@ import { EventRepository } from "../event-sources/event-repository"; import { AgentRepository } from "../bot-store/agent-repository"; import type { Activity } from "./bots"; import { BotDeletion } from "../bot-ports/bot-deletion"; +import { BotNeeds } from "../bot-ports/bot-needs"; import { BotNotices } from "../bot-ports/bot-notices"; +import type { BotStatusChange } from "./bots-status"; import { CallNotes } from "../bot-ports/call-notes"; import { ConversationRepository } from "../bot-store/conversation-repository"; import { ExecutionRepository } from "../bot-store/execution-repository"; @@ -35,12 +37,14 @@ export type BotsContext = { readonly events: EventRepository["Service"]; readonly runtime: BotRuntime["Service"]; readonly library: Library["Service"]; + readonly needs: BotNeeds["Service"]; readonly notices: BotNotices["Service"]; readonly callNotes: CallNotes["Service"]; readonly deletion: BotDeletion["Service"]; readonly scope: Scope.Scope; readonly listeners: KeyedListeners; readonly activityListeners: Set<(event: Activity) => void>; + readonly statusListeners: Set<(event: BotStatusChange) => void>; readonly settledListeners: Set< (execution: Execution) => void | Promise >; @@ -60,12 +64,14 @@ export const botsContext = Effect.gen(function* () { events: yield* EventRepository, runtime: yield* BotRuntime, library: yield* Library, + needs: yield* BotNeeds, notices: yield* BotNotices, callNotes: yield* CallNotes, deletion: yield* BotDeletion, scope: yield* Effect.scope, listeners: keyedListeners(), activityListeners: new Set<(event: Activity) => void>(), + statusListeners: new Set<(event: BotStatusChange) => void>(), settledListeners: new Set<(execution: Execution) => void | Promise>(), chatOpenings: keyedLocks(), monitors: yield* FiberMap.make(), diff --git a/apps/server/src/bots/bots-notifications.ts b/apps/server/src/bots/bots-notifications.ts index 0e84fead..1eb242db 100644 --- a/apps/server/src/bots/bots-notifications.ts +++ b/apps/server/src/bots/bots-notifications.ts @@ -7,10 +7,11 @@ import { formatEntryId, formatMessageId } from "../shared/entry-ids"; import { nowIso } from "../shared/time"; import type { Activity } from "./bots"; import type { BotsContext } from "./bots-context"; +import type { BotsStatus } from "./bots-status"; export type BotsNotifications = ReturnType; -export const botsNotifications = (context: BotsContext) => { +export const botsNotifications = (context: BotsContext, status: BotsStatus) => { const { activityListeners, agents, executions, listeners, scope } = context; const { settledListeners } = context; @@ -36,7 +37,9 @@ export const botsNotifications = (context: BotsContext) => { }; const changed = (conversationId: string) => - Effect.sync(() => listeners.notify(conversationId)); + Effect.sync(() => listeners.notify(conversationId)).pipe( + Effect.andThen(status.conversationChanged(conversationId)), + ); const emit = (event: Activity) => Effect.sync(() => { diff --git a/apps/server/src/bots/bots-service.ts b/apps/server/src/bots/bots-service.ts index 3f76e596..9457d49b 100644 --- a/apps/server/src/bots/bots-service.ts +++ b/apps/server/src/bots/bots-service.ts @@ -1,3 +1,4 @@ +import { Effect } from "effect"; import type { Bots } from "./bots"; import { botsAdmission } from "./bots-admission"; import { botsAnnouncements } from "./bots-announcements"; @@ -8,12 +9,14 @@ import { botsLookup } from "./bots-lookup"; import { botsNotifications } from "./bots-notifications"; import { botsMonitor } from "./bots-outcomes"; import { botsReads } from "./bots-reads"; +import { botsStatus } from "./bots-status"; import { botsSubmissions } from "./bots-submissions"; export const botsService = (context: BotsContext): Bots["Service"] => { const lookup = botsLookup(context); - const notifications = botsNotifications(context); const reads = botsReads(context, lookup); + const status = botsStatus(context, { snapshot: reads.snapshot }); + const notifications = botsNotifications(context, status); const announcements = botsAnnouncements(context, { notifications, @@ -57,7 +60,19 @@ export const botsService = (context: BotsContext): Bots["Service"] => { onActivity: notifications.onActivity, changed: notifications.changed, onSettled: notifications.onSettled, - agentPreviews: reads.agentPreviews, + onBotStatus: status.onBotStatus, + requestStatuses: status.requestStatuses, + agentPreviews: Effect.gen(function* () { + return yield* Effect.forEach( + yield* reads.agentPreviews, + (preview) => + Effect.map(status.statusOf(preview.agent.id), (current) => ({ + ...preview, + status: current, + })), + { concurrency: "unbounded" }, + ); + }), usage: reads.usage, announceJobAnswer: notifications.announceJobAnswer, announce: notifications.emit, diff --git a/apps/server/src/bots/bots-status.ts b/apps/server/src/bots/bots-status.ts new file mode 100644 index 00000000..071a9d43 --- /dev/null +++ b/apps/server/src/bots/bots-status.ts @@ -0,0 +1,200 @@ +import { Effect } from "effect"; +import type { BotStatus } from "../contract/bot-status"; +import { logged } from "../shared/app-errors"; +import { activeExecution } from "../shared/domain"; +import { chatQuestionOpen } from "../transcript/chat-question"; +import { turnSource } from "../transcript/origins"; +import type { AppError } from "../shared/errors"; +import type { ChatSnapshot } from "./bots"; +import type { BotsContext } from "./bots-context"; + +export type BotStatusChange = { agentId: string; status: BotStatus }; + +type StatusDeps = { + snapshot: ( + conversationId: string, + options?: { + limit?: number | undefined; + partial?: boolean | undefined; + }, + ) => Effect.Effect; +}; + +export type BotsStatus = ReturnType; + +const COALESCE = "50 millis"; +const POLL = "1 second"; +const CHAT_WINDOW = 200; + +export const botsStatus = (context: BotsContext, deps: StatusDeps) => { + const { agents, conversations, executions, needs, scope, statusListeners } = + context; + + const inflight = new Map(); + const polling = new Set(); + let stopNeeds: (() => void) | undefined; + + const answeringOwner = Effect.fnUntraced(function* (conversationId: string) { + const latest = yield* executions.latestIn(conversationId); + + return ( + latest !== null && + activeExecution(latest) && + turnSource(latest).kind === "owner" + ); + }); + + const compute = Effect.fnUntraced(function* ( + agentId: string, + ): Effect.fn.Return<{ status: BotStatus; running: boolean }> { + const need = yield* needs.current(agentId); + + if (need === "blocked" || need === "question") { + return { status: need, running: false }; + } + const [chat] = yield* conversations.list(agentId, true); + + const snapshot = chat + ? yield* deps + .snapshot(chat.id, { limit: CHAT_WINDOW, partial: true }) + .pipe(Effect.catch(() => Effect.succeed(undefined))) + : undefined; + + if (!chat || !snapshot) { + return { + status: need === "working" ? "working" : "idle", + running: false, + }; + } + const { working, error, messages } = snapshot; + const running = working !== "idle" && working !== "failed"; + + if (chatQuestionOpen(messages, yield* answeringOwner(chat.id))) { + return { status: "question", running }; + } + + if (working === "failed" || error !== null) { + return { status: "failed", running }; + } + + if (working === "thinking") { + return { status: "thinking", running }; + } + + return { + status: running || need === "working" ? "working" : "idle", + running, + }; + }); + + const statusOf = (agentId: string): Effect.Effect => + Effect.map(compute(agentId), ({ status }) => status); + + const announce = Effect.fnUntraced(function* (agentId: string) { + if (!statusListeners.size || !(yield* agents.get(agentId))) { + return; + } + const { status, running } = yield* compute(agentId); + + for (const listener of statusListeners) { + listener({ agentId, status }); + } + + if (running) { + yield* poll(agentId); + } + }); + + const release = (agentId: string) => { + if (inflight.get(agentId)) { + inflight.set(agentId, false); + + return true; + } + inflight.delete(agentId); + + return false; + }; + + const settle = (agentId: string): Effect.Effect => + Effect.sleep(COALESCE).pipe( + Effect.andThen(Effect.sync(() => inflight.set(agentId, false))), + Effect.andThen(announce(agentId)), + logged("Bot status announcement failed", agentId), + Effect.andThen( + Effect.suspend(() => + release(agentId) ? settle(agentId) : Effect.void, + ), + ), + Effect.onInterrupt(() => Effect.sync(() => inflight.delete(agentId))), + ); + + const refresh = (agentId: string): Effect.Effect => + Effect.suspend(() => { + if (!statusListeners.size) { + return Effect.void; + } + + if (inflight.has(agentId)) { + inflight.set(agentId, true); + + return Effect.void; + } + inflight.set(agentId, false); + + return settle(agentId).pipe(Effect.forkIn(scope), Effect.asVoid); + }); + + const poll = (agentId: string): Effect.Effect => + Effect.suspend(() => { + if (polling.has(agentId)) { + return Effect.void; + } + polling.add(agentId); + + return Effect.sleep(POLL).pipe( + Effect.ensuring(Effect.sync(() => polling.delete(agentId))), + Effect.andThen(refresh(agentId)), + Effect.forkIn(scope), + Effect.asVoid, + ); + }); + + const conversationChanged = Effect.fnUntraced(function* ( + conversationId: string, + ) { + if (!statusListeners.size) { + return; + } + const found = yield* conversations.get(conversationId); + + if (found) { + yield* refresh(found.agentId); + } + }); + + const onBotStatus = (callback: (event: BotStatusChange) => void) => { + statusListeners.add(callback); + + if (!stopNeeds) { + stopNeeds = needs.onChanged((agentId) => + Effect.runFork(refresh(agentId)), + ); + } + + return () => { + statusListeners.delete(callback); + + if (!statusListeners.size) { + stopNeeds?.(); + stopNeeds = undefined; + } + }; + }; + + const requestStatuses = Effect.flatMap(agents.list, (listed) => + Effect.forEach(listed, (each) => refresh(each.id), { discard: true }), + ); + + return { statusOf, requestStatuses, conversationChanged, onBotStatus }; +}; diff --git a/apps/server/src/bots/bots-test-support.ts b/apps/server/src/bots/bots-test-support.ts index 97f3fa2e..c45e5b30 100644 --- a/apps/server/src/bots/bots-test-support.ts +++ b/apps/server/src/bots/bots-test-support.ts @@ -9,6 +9,7 @@ import type { AgentRepository } from "../bot-store/agent-repository"; import { Bots, botsAccess } from "./bots"; import type { BotsAccess } from "./bots"; import type { BotDeletion } from "../bot-ports/bot-deletion"; +import type { BotNeeds } from "../bot-ports/bot-needs"; import type { BotNotices } from "../bot-ports/bot-notices"; import type { CallNotes } from "../bot-ports/call-notes"; import type { ConversationRepository } from "../bot-store/conversation-repository"; @@ -28,6 +29,7 @@ type StandaloneServices = | ScheduleRepository | ScriptRunRepository | EventRepository + | BotNeeds | BotNotices | CallNotes | BotDeletion diff --git a/apps/server/src/bots/bots.ts b/apps/server/src/bots/bots.ts index e67ff473..8513ae6c 100644 --- a/apps/server/src/bots/bots.ts +++ b/apps/server/src/bots/bots.ts @@ -1,4 +1,6 @@ import type { Working } from "./working"; +import type { BotStatus } from "../contract/bot-status"; +import type { BotStatusChange } from "./bots-status"; import { Context, Effect, Layer } from "effect"; import type { JobAnswer } from "../jobs/jobs"; import type { JobKindName } from "../shared/job-kinds"; @@ -96,8 +98,12 @@ export class Bots extends Context.Service< readonly onSettled: ( callback: (execution: Execution) => void | Promise, ) => () => void; + readonly onBotStatus: ( + callback: (event: BotStatusChange) => void, + ) => () => void; + readonly requestStatuses: Effect.Effect; readonly agentPreviews: Effect.Effect< - Array<{ agent: Agent; lastMessage: string }> + Array<{ agent: Agent; lastMessage: string; status: BotStatus }> >; readonly usage: Effect.Effect, AppError>; readonly announceJobAnswer: ( diff --git a/apps/server/src/bots/mark-question.ts b/apps/server/src/bots/mark-question.ts new file mode 100644 index 00000000..f1011d47 --- /dev/null +++ b/apps/server/src/bots/mark-question.ts @@ -0,0 +1,34 @@ +import { Type } from "@earendil-works/pi-ai"; +import { defineExtension, defineTool } from "@earendil-works/pi-durable"; +import { Effect, Layer } from "effect"; +import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; +import { MARK_QUESTION_TOOL_NAME } from "../contract/tools"; + +export function markQuestionExtension() { + const markQuestion = defineTool({ + name: MARK_QUESTION_TOOL_NAME, + description: + 'Call this right before you end your turn with a question that you need the owner to answer before you can go on. Then write the question in plain text as your reply. Do not call it for rhetorical or courtesy questions, such as "Anything else?".', + parameters: Type.Object({}), + callers: ["model"], + replay: "safe", + execute: async () => ({ + output: [ + { + type: "text" as const, + text: "Marked. Write your question as your reply now.", + }, + ], + }), + }); + + return defineExtension({ name: "mark_question", tools: [markQuestion] }); +} + +export const markQuestionTools = Layer.effectDiscard( + Effect.flatMap(BotExtensions, (extensions) => + extensions.register(ExtensionPosition.markQuestion, () => [ + markQuestionExtension(), + ]), + ), +); diff --git a/apps/server/src/bots/runtime.ts b/apps/server/src/bots/runtime.ts index fd55d0d4..6384f0a2 100644 --- a/apps/server/src/bots/runtime.ts +++ b/apps/server/src/bots/runtime.ts @@ -1105,6 +1105,19 @@ export class AgentRuntime { })); } + async jobNeed(agent: Agent) { + const { harness } = await this.open(agent); + const root = await harness.root(BACKGROUND_CONTEXT); + + const found = await Promise.all( + Object.values(JOB_READERS).map((kind) => kind.activity(harness, root.id)), + ); + + return found.includes("question") + ? ("question" as const) + : found.find((need) => need === "working"); + } + async answerJob( agent: Agent, kind: string, diff --git a/apps/server/src/contract/api-contract.ts b/apps/server/src/contract/api-contract.ts index 848e1a68..1d44587b 100644 --- a/apps/server/src/contract/api-contract.ts +++ b/apps/server/src/contract/api-contract.ts @@ -1003,10 +1003,11 @@ export const routes = { activity: { $ref: "#/components/schemas/ActivityEvent" }, learned: { $ref: "#/components/schemas/LearnedEvent" }, pins: { $ref: "#/components/schemas/PinsEvent" }, + "bot-status": { $ref: "#/components/schemas/BotStatusEvent" }, heartbeat: { $ref: "#/components/schemas/HeartbeatEvent" }, }, description: - "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Each pins event carries a PinsEvent: the account's pinned conversations after a change, which the session also returns. Current chat previews replay on connection; finished replies, learned events, and pins events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", + "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Each pins event carries a PinsEvent: the account's pinned conversations after a change, which the session also returns. Each bot-status event carries a BotStatusEvent: what a bot is doing or needs from the owner. Current chat previews and bot statuses replay on connection; finished replies, learned events, and pins events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", responses: { 200: { description: "SSE stream, not a JSON array", diff --git a/apps/server/src/contract/api-responses.ts b/apps/server/src/contract/api-responses.ts index 79419a40..0e8bde4a 100644 --- a/apps/server/src/contract/api-responses.ts +++ b/apps/server/src/contract/api-responses.ts @@ -1,3 +1,4 @@ +import { BOT_STATUSES } from "./bot-status"; import { z } from "@hono/zod-openapi"; import { PASSWORD_MANAGER_IDS, @@ -152,8 +153,13 @@ export const agentResponse = z }) .openapi("Agent"); +const botStatus = z.enum(BOT_STATUSES).openapi({ + description: + "What the bot is doing, or what it needs from the owner. blocked: a bot, call, credential, or login request or a held action waits for the owner. question: a job question or a chat question waits for the owner's answer. failed: the latest turn failed. The first that applies, in this order: blocked, question, failed, thinking, working, idle. Clients may receive other values later.", +}); + export const agentPreviewResponse = agentResponse - .extend({ lastMessage: z.string().optional() }) + .extend({ lastMessage: z.string().optional(), status: botStatus }) .openapi("AgentPreview"); const conversation = z @@ -1157,6 +1163,13 @@ export const chatPreviewEvent = z }) .openapi("ChatPreviewEvent"); +export const botStatusEvent = z + .object({ agentId: z.string(), status: botStatus }) + .openapi("BotStatusEvent", { + description: + "A bot's status changed, sent as the `bot-status` event on /v1/events. Every bot's status is sent on connect.", + }); + export const learnedEvent = z .object({ type: z.literal("learned"), @@ -1218,6 +1231,11 @@ export const eventSchemas: Array<{ component: "PinsEvent", artifact: "pins-event.schema.json", }, + { + schema: botStatusEvent, + component: "BotStatusEvent", + artifact: "bot-status-event.schema.json", + }, { schema: chatSnapshotResponse, artifact: "chat-snapshot.schema.json" }, { schema: desktopControlResponse, artifact: "desktop-control.schema.json" }, { diff --git a/apps/server/src/contract/bot-status.ts b/apps/server/src/contract/bot-status.ts new file mode 100644 index 00000000..71d2aeef --- /dev/null +++ b/apps/server/src/contract/bot-status.ts @@ -0,0 +1,10 @@ +export const BOT_STATUSES = [ + "idle", + "thinking", + "working", + "failed", + "question", + "blocked", +] as const; + +export type BotStatus = (typeof BOT_STATUSES)[number]; diff --git a/apps/server/src/contract/tools.ts b/apps/server/src/contract/tools.ts index 8a819b34..e97ed9fe 100644 --- a/apps/server/src/contract/tools.ts +++ b/apps/server/src/contract/tools.ts @@ -10,6 +10,7 @@ export const REQUEST_CREDENTIAL_TOOL_NAME = "request_credential"; export const REQUEST_LOGIN_TOOL_NAME = "request_login"; export const REQUEST_BOT_TOOL_NAME = "request_bot"; export const REACTION_TOOL_NAME = "react"; +export const MARK_QUESTION_TOOL_NAME = "mark_question"; export const CALL_OWNER_TOOL_NAME = "call_owner"; export const HANG_UP_TOOL_NAME = "hang_up"; export const REQUEST_CALL_TOOL_NAME = "request_call"; diff --git a/apps/server/src/jobs/coding.ts b/apps/server/src/jobs/coding.ts index a54da35e..0873b563 100644 --- a/apps/server/src/jobs/coding.ts +++ b/apps/server/src/jobs/coding.ts @@ -228,6 +228,7 @@ export const codingPlugin = ( onAnswer: coding.onAnswer, onQuestion: coding.onQuestion, onFinished: coding.onFinished, + onChange: coding.onChange, }, ] : [], diff --git a/apps/server/src/jobs/jobs.ts b/apps/server/src/jobs/jobs.ts index b7856f42..e01ae2ed 100644 --- a/apps/server/src/jobs/jobs.ts +++ b/apps/server/src/jobs/jobs.ts @@ -39,6 +39,7 @@ import type { UsageState, } from "@earendil-works/pi-durable"; import type { ExecutionEnv } from "@earendil-works/pi-durable/env"; +import type { BotNeed } from "../bot-ports/bot-needs"; import { formatEntryId } from "../shared/entry-ids"; import { replyText } from "../shared/reply-text"; import { defineAnchorTask } from "../shared/anchor-task"; @@ -169,6 +170,12 @@ const COMPLETED = { outcome: { status: "completed", result: null }, } as const; +const changed = (kindState: JobKindBase, agentId: string) => { + for (const listener of kindState.changeListeners) { + listener(agentId); + } +}; + const releaseHolder = (state: JobsState, name: string) => { if (state.holder?.name !== name) { return; @@ -356,6 +363,7 @@ type JobKindBase = JobKindFacts & { answerListeners: Set<(answer: JobAnswer) => void>; finishedListeners: Set<(finished: JobFinished) => void>; questionListeners: Set<(asked: JobAsked) => Promise>; + changeListeners: Set<(agentId: string) => void>; Marker: JobMarkerDoc; Jobs: JobsDoc; Request: JobRequestDoc; @@ -439,6 +447,7 @@ const jobReporterWait = for (;;) { let waiting = false; + let ended = false; await runtime.commit(async (tx) => { const { state, stopped } = await deliveryTarget( @@ -455,6 +464,7 @@ const jobReporterWait = String(reporter.id), stoppedError(kindState, name), ); + ended = true; return COMPLETED; } @@ -475,6 +485,10 @@ const jobReporterWait = return { status: "running", checkpoint: { phase: "deliver" } }; }, taskContext); + if (ended) { + changed(kindState, reporter.input.agentId); + } + if (!waiting) { return; } @@ -518,6 +532,10 @@ const admitDelivery = async ( return; }, taskContext); + if (!admitted) { + changed(kindState, reporter.input.agentId); + } + return admitted; }; @@ -639,6 +657,7 @@ const submitAndReport = async ( ); const { agentId } = reporter.input; + changed(kindState, agentId); if (reported) { for (const listener of kindState.finishedListeners) { @@ -885,12 +904,12 @@ const jobReporterAnnounce = const jobReporterAbort = (kindState: JobKindBase) => - ( + async ( reporter: RunningTask, runtime: ReporterRuntime, taskContext: Context, - ) => - runtime.commit(async (tx) => { + ) => { + const outcome = await runtime.commit(async (tx) => { const state = await tx.doc(kindState.Jobs, runtime.conversationId); settleDelivery(state.jobs[reporter.input.name], reporter.id); @@ -905,8 +924,12 @@ const jobReporterAbort = releaseHolder(state, reporter.input.name); } - return { status: "terminal", outcome: { status: "aborted" } }; + return { status: "terminal", outcome: { status: "aborted" } } as const; }, taskContext); + changed(kindState, reporter.input.agentId); + + return outcome; + }; const defineJobReporter = (kindState: JobKindBase): JobReporter => defineTask({ @@ -1001,6 +1024,7 @@ const stopJob = async ( if (conversation) { await conversation.abort(context); } + changed(kindState, call.agentId); return reply(`Stopped ${name}.`); }; @@ -1258,6 +1282,36 @@ const listedJobs = async ( ); }; +const jobActivity = async ( + kindState: JobKindBase, + harness: Harness, + chatId: ConversationId, +): Promise | undefined> => { + const jobs = + (await harness.snapshot(kindState.Jobs, chatId, BACKGROUND_CONTEXT)) + ?.jobs ?? {}; + + const found = await Promise.all( + Object.values(jobs).map(async (job) => ({ + working: (await statusOf(harness, job, BACKGROUND_CONTEXT)) === "working", + asking: Boolean( + await openQuestion( + kindState, + harness, + job.conversationId, + BACKGROUND_CONTEXT, + ), + ), + })), + ); + + if (found.some((job) => job.asking)) { + return "question"; + } + + return found.some((job) => job.working) ? "working" : undefined; +}; + const openQuestion = async ( kindState: JobKindBase, reader: DocumentReader, @@ -1416,6 +1470,7 @@ const sendJobTool = async ( knowledge: api.registry.extension(JOB_KNOWLEDGE_EXTENSION), turn: await turnOf(api, callContext), }); + changed(kindState, call.agentId); return action === "start" && result.found ? { @@ -1463,6 +1518,9 @@ const jobKindReads = (state: JobKindState) => ({ tasks: [], }, + activity: (harness: Harness, chatId: ConversationId) => + jobActivity(state, harness, chatId), + isJob: ( reader: DocumentReader, conversationId: ConversationId, @@ -1503,6 +1561,7 @@ const jobKindApi = (state: JobKindState) => { ) => answerQuestion(state, harness, chatId, answer), onQuestion: subscribe(state.questionListeners), + onChange: subscribe(state.changeListeners), }; }; @@ -1571,39 +1630,47 @@ const answerQuestion = ( chatId: ConversationId, answer: JobQuestionAnswer, ) => - harness.commit(async (tx) => { - const state = await tx.doc(kindState.Jobs, chatId); - const record = state.jobs[answer.name]; + harness + .commit(async (tx) => { + const state = await tx.doc(kindState.Jobs, chatId); + const record = state.jobs[answer.name]; - if (!record) { - return false; - } - const question = await tx.doc(kindState.Question, record.conversationId); - const pending = question.pending; + if (!record) { + return false; + } + const question = await tx.doc(kindState.Question, record.conversationId); + const pending = question.pending; - if (pending?.id !== answer.questionId) { - return false; - } - question.pending = null; - await queueDelivery( - kindState, - tx, - state, - record, - { - agentId: answer.agentId, - name: answer.name, - conversationId: record.conversationId, - message: `${answer.by ?? "The owner"} answered your question: ${answer.text}`, - followUp: false, - stops: record.stops, - ...(pending.turn !== undefined && { turn: pending.turn }), - }, - { chatId, replaces: pending.reporter }, - ); + if (pending?.id !== answer.questionId) { + return false; + } + question.pending = null; + await queueDelivery( + kindState, + tx, + state, + record, + { + agentId: answer.agentId, + name: answer.name, + conversationId: record.conversationId, + message: `${answer.by ?? "The owner"} answered your question: ${answer.text}`, + followUp: false, + stops: record.stops, + ...(pending.turn !== undefined && { turn: pending.turn }), + }, + { chatId, replaces: pending.reporter }, + ); + + return true; + }, BACKGROUND_CONTEXT) + .then((answered) => { + if (answered) { + changed(kindState, answer.agentId); + } - return true; - }, BACKGROUND_CONTEXT); + return answered; + }); export function mergeTurnWork(found: Array): TurnWork | undefined { if (!found.length) { @@ -1645,6 +1712,7 @@ const jobKindBase = (facts: JobKindFacts): JobKindBase => { answerListeners: new Set<(answer: JobAnswer) => void>(), finishedListeners: new Set<(finished: JobFinished) => void>(), questionListeners: new Set<(asked: JobAsked) => Promise>(), + changeListeners: new Set<(agentId: string) => void>(), ...jobDocuments(kind), Anchor: defineAnchorTask(`crumble.${kind}-anchor`), }; diff --git a/apps/server/src/message-gateway/message-gateway.test.ts b/apps/server/src/message-gateway/message-gateway.test.ts index 99a21543..6989bd6f 100644 --- a/apps/server/src/message-gateway/message-gateway.test.ts +++ b/apps/server/src/message-gateway/message-gateway.test.ts @@ -186,6 +186,8 @@ async function fixture( conversation: unexpected, subscribe: unsubscribe, onActivity: unsubscribe, + onBotStatus: unsubscribe, + requestStatuses: unexpected(), changed: unexpected, onSettled: unsubscribe, agentPreviews: unexpected(), diff --git a/apps/server/src/plugins/plugins.ts b/apps/server/src/plugins/plugins.ts index 7290ea93..abcea1b7 100644 --- a/apps/server/src/plugins/plugins.ts +++ b/apps/server/src/plugins/plugins.ts @@ -39,6 +39,7 @@ export type JobKindContribution = { onAnswer: (listener: (answer: JobAnswer) => void) => () => void; onQuestion?: (listener: (asked: JobAsked) => Promise) => () => void; onFinished?: (listener: (finished: JobFinished) => void) => () => void; + onChange?: (listener: (agentId: string) => void) => () => void; }; export type WorkspaceBackend = ( diff --git a/apps/server/src/transcript/chat-question.test.ts b/apps/server/src/transcript/chat-question.test.ts new file mode 100644 index 00000000..4adbea37 --- /dev/null +++ b/apps/server/src/transcript/chat-question.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, test } from "bun:test"; +import { MARK_QUESTION_TOOL_NAME } from "../contract/tools"; +import { ASSISTANT_ENTRY, MESSAGE_ENTRY } from "./entries"; +import { chatQuestionOpen } from "./chat-question"; +import type { TranscriptMessage } from "./transcript"; + +let sequence = 0; + +const message = ( + fields: Omit, +): TranscriptMessage => { + sequence += 1; + + return { + id: `m${sequence}`, + entryId: `e${sequence}`, + content: "", + ...fields, + }; +}; + +const owner = () => + message({ kind: MESSAGE_ENTRY, role: "user", origin: { kind: "owner" } }); + +const plainOwner = () => message({ kind: MESSAGE_ENTRY, role: "user" }); + +const automation = () => + message({ + kind: MESSAGE_ENTRY, + role: "user", + origin: { kind: "task", name: "Inbox check" }, + }); + +const fromBot = () => + message({ + kind: MESSAGE_ENTRY, + role: "user", + origin: { kind: "bot", name: "Helper", agentId: "other" }, + }); + +const reply = (text: string) => + message({ + kind: ASSISTANT_ENTRY, + role: "assistant", + blocks: [{ type: "text", text }], + }); + +const mark = (isError = false, toolCallId = "call-1") => + message({ + kind: "pi.tool-result", + role: "toolResult", + toolName: MARK_QUESTION_TOOL_NAME, + toolCallId, + isError, + }); + +const markCall = (text?: string, id = "call-1") => + message({ + kind: ASSISTANT_ENTRY, + role: "assistant", + blocks: [ + ...(text ? [{ type: "text" as const, text }] : []), + { + type: "toolCall" as const, + id, + name: MARK_QUESTION_TOOL_NAME, + arguments: {}, + }, + ], + }); + +const open = (messages: Array, answeringOwner = false) => + chatQuestionOpen(messages, answeringOwner); + +describe("chatQuestionOpen", () => { + test("is open once the bot marked a question and wrote it", () => { + expect(open([owner(), mark(), reply("Which database?")])).toBe(true); + expect(open([plainOwner(), mark(), reply("Which database?")])).toBe(true); + }); + + test("needs the mark and a written reply after it", () => { + expect(open([owner(), reply("Which database?")])).toBe(false); + expect(open([owner(), mark()])).toBe(false); + expect(open([owner(), reply("Which database?"), mark()])).toBe(false); + expect(open([owner(), mark(), reply(" ")])).toBe(false); + }); + + test("is open when the question is written in the message that marks it", () => { + expect(open([owner(), markCall("Which database?"), mark()])).toBe(true); + expect(open([owner(), markCall(), mark()])).toBe(false); + expect(open([owner(), reply("Let me check."), markCall(), mark()])).toBe( + false, + ); + expect( + open([ + owner(), + reply("Let me check."), + markCall(), + mark(), + reply("Which?"), + ]), + ).toBe(true); + expect(open([owner(), markCall("Which database?", "other"), mark()])).toBe( + false, + ); + expect(open([owner(), markCall("Which database?"), mark(true)])).toBe( + false, + ); + }); + + test("ignores a mark that failed or was declined", () => { + expect(open([owner(), mark(true), reply("Which database?")])).toBe(false); + }); + + test("is closed by the next owner message, not by anything else", () => { + const asked = [owner(), mark(), reply("Which database?")]; + + expect(open([...asked, owner()])).toBe(false); + expect(open([...asked, plainOwner(), reply("Postgres it is.")])).toBe( + false, + ); + expect(open([...asked, automation(), reply("Inbox is empty.")])).toBe(true); + expect(open([...asked, fromBot(), reply("Noted.")])).toBe(true); + expect(open([...asked, reply("Still waiting.")])).toBe(true); + }); + + test("ignores a question from before the latest owner message", () => { + expect( + open([owner(), mark(), reply("Which?"), owner(), reply("Done.")]), + ).toBe(false); + }); + + test("is closed while a turn answers the owner", () => { + expect(open([owner(), mark(), reply("Which database?")], true)).toBe(false); + }); + + test("is closed in an empty chat", () => { + expect(open([])).toBe(false); + }); +}); diff --git a/apps/server/src/transcript/chat-question.ts b/apps/server/src/transcript/chat-question.ts new file mode 100644 index 00000000..830b1be4 --- /dev/null +++ b/apps/server/src/transcript/chat-question.ts @@ -0,0 +1,48 @@ +import { MARK_QUESTION_TOOL_NAME } from "../contract/tools"; +import { isOwnerOrigin } from "./origins"; +import { isToolResult } from "./tool-results"; +import { isOwnerInput, textOf, toolCalls } from "./transcript"; +import type { TranscriptMessage } from "./transcript"; + +const ownerSaid = (message: TranscriptMessage) => + isOwnerInput(message) && + (message.origin === undefined || isOwnerOrigin(message.origin)); + +const writtenReply = (message: TranscriptMessage) => + message.role === "assistant" && Boolean(textOf(message)?.trim()); + +const callOf = (before: Array, result: TranscriptMessage) => + before.findLast( + (message) => + message.role === "assistant" && + toolCalls(message).some( + (call) => + call.name === MARK_QUESTION_TOOL_NAME && + (result.toolCallId === undefined || call.id === result.toolCallId), + ), + ); + +export function chatQuestionOpen( + messages: Array, + answeringOwner: boolean, +): boolean { + if (answeringOwner) { + return false; + } + const after = messages.slice(messages.findLastIndex(ownerSaid) + 1); + + const marked = after.findIndex((message) => + isToolResult(message, MARK_QUESTION_TOOL_NAME), + ); + const result = after[marked]; + + if (!result) { + return false; + } + const call = callOf(after.slice(0, marked), result); + + return ( + (call !== undefined && writtenReply(call)) || + after.slice(marked + 1).some(writtenReply) + ); +} diff --git a/apps/server/src/voice-gateway/call-requests.ts b/apps/server/src/voice-gateway/call-requests.ts index 0b26e05b..f7cae6e3 100644 --- a/apps/server/src/voice-gateway/call-requests.ts +++ b/apps/server/src/voice-gateway/call-requests.ts @@ -3,6 +3,7 @@ import { and, desc, eq } from "drizzle-orm"; import { Context, Effect, Layer } from "effect"; import { AgentRepository } from "../bot-store/agent-repository"; import { ConversationRepository } from "../bot-store/conversation-repository"; +import { BotNeeds } from "../bot-ports/bot-needs"; import { BotNotices, loggedNotices } from "../bot-ports/bot-notices"; import { BotRuntime } from "../bots/runtime"; import type { CallRequest } from "../contract/voice-gateway"; @@ -76,6 +77,8 @@ export class CallRequests extends Context.Service< const runtime = yield* BotRuntime; const gateway = yield* VoiceGateway; + const needs = yield* BotNeeds; + const notify = loggedNotices( yield* BotNotices, "Call request notice failed", @@ -136,6 +139,8 @@ export class CallRequests extends Context.Service< .pipe(Effect.orDie); if (row) { + yield* needs.changed(agentId); + return requestOf(row); } yield* found(agentId, requestId); @@ -145,7 +150,7 @@ export class CallRequests extends Context.Service< }); }); - const reopen = (requestId: string) => + const reopen = (agentId: string, requestId: string) => db .update(callRequests) .set({ @@ -160,7 +165,7 @@ export class CallRequests extends Context.Service< eq(callRequests.status, "calling"), ), ) - .pipe(Effect.orDie, Effect.asVoid); + .pipe(Effect.orDie, Effect.andThen(needs.changed(agentId))); const pendingOf = (agentId: string) => db @@ -175,6 +180,12 @@ export class CallRequests extends Context.Service< .limit(1) .pipe(Effect.orDie); + yield* needs.provide((agentId) => + Effect.map(pendingOf(agentId), (rows) => + rows.length > 0 ? ("blocked" as const) : undefined, + ), + ); + const ownerNumbers = Effect.map( gateway.describe, (description) => description.config.ownerNumbers, @@ -222,6 +233,7 @@ export class CallRequests extends Context.Service< "A call request is already pending; wait for the owner's answer.", }); } + yield* needs.changed(agentId); return yield* found(agentId, id); }); @@ -287,11 +299,11 @@ export class CallRequests extends Context.Service< const claimed = yield* claim(agentId, requestId, "calling"); const refusal = yield* dial(claimed).pipe( - Effect.onError(() => reopen(requestId)), + Effect.onError(() => reopen(agentId, requestId)), ); if (refusal) { - yield* reopen(requestId); + yield* reopen(agentId, requestId); return yield* new Conflict({ message: refusal }); } diff --git a/apps/web/features/bot-requests/bot-request-card.tsx b/apps/web/features/bot-requests/bot-request-card.tsx index f5ad8f16..331a6150 100644 --- a/apps/web/features/bot-requests/bot-request-card.tsx +++ b/apps/web/features/bot-requests/bot-request-card.tsx @@ -119,7 +119,7 @@ function useBotRequestMutations( queryClient.setQueryData>(botsQuery.queryKey, (bots) => !bots || bots.some((bot) => bot.id === agent.id) ? bots - : [...bots, agent], + : [...bots, { ...agent, status: "idle" }], ); void refresh(); void invalidateBots(); diff --git a/apps/web/features/skills/bulk-skill-actions.test.ts b/apps/web/features/skills/bulk-skill-actions.test.ts index 177e790a..21f3d50f 100644 --- a/apps/web/features/skills/bulk-skill-actions.test.ts +++ b/apps/web/features/skills/bulk-skill-actions.test.ts @@ -14,6 +14,7 @@ const bot = (id: string, name = id): Bot => ({ provider: "openai", model: "test", enabled: true, + status: "idle", tools: [], skills: [], mcpServers: [], diff --git a/apps/web/test/agent-fixture.ts b/apps/web/test/agent-fixture.ts index 27eea54a..8f645183 100644 --- a/apps/web/test/agent-fixture.ts +++ b/apps/web/test/agent-fixture.ts @@ -11,6 +11,7 @@ export function agentFixture( provider: "test", model: "test", enabled: true, + status: "idle", tools: [], skills: [], mcpServers: [], diff --git a/openapi/bot-status-event.schema.json b/openapi/bot-status-event.schema.json new file mode 100644 index 00000000..31e442b6 --- /dev/null +++ b/openapi/bot-status-event.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "agentId": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "idle", + "thinking", + "working", + "failed", + "question", + "blocked" + ] + } + }, + "required": [ + "agentId", + "status" + ], + "additionalProperties": true +} diff --git a/openapi/openapi.json b/openapi/openapi.json index a7d8b848..0b945cac 100644 --- a/openapi/openapi.json +++ b/openapi/openapi.json @@ -223,6 +223,31 @@ ], "description": "The account's pinned conversations changed, sent as the `pins` event on /v1/events with the whole list, first pin first. Not replayed: read the session on connect." }, + "BotStatusEvent": { + "type": "object", + "properties": { + "agentId": { + "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "idle", + "thinking", + "working", + "failed", + "question", + "blocked" + ], + "description": "What the bot is doing, or what it needs from the owner. blocked: a bot, call, credential, or login request or a held action waits for the owner. question: a job question or a chat question waits for the owner's answer. failed: the latest turn failed. The first that applies, in this order: blocked, question, failed, thinking, working, idle. Clients may receive other values later." + } + }, + "required": [ + "agentId", + "status" + ], + "description": "A bot's status changed, sent as the `bot-status` event on /v1/events. Every bot's status is sent on connect." + }, "VoiceGatewayConfigEvent": { "type": "object", "properties": { @@ -1004,8 +1029,23 @@ "properties": { "lastMessage": { "type": "string" + }, + "status": { + "type": "string", + "enum": [ + "idle", + "thinking", + "working", + "failed", + "question", + "blocked" + ], + "description": "What the bot is doing, or what it needs from the owner. blocked: a bot, call, credential, or login request or a held action waits for the owner. question: a job question or a chat question waits for the owner's answer. failed: the latest turn failed. The first that applies, in this order: blocked, question, failed, thinking, working, idle. Clients may receive other values later." } - } + }, + "required": [ + "status" + ] } ] }, @@ -16535,11 +16575,14 @@ "pins": { "$ref": "#/components/schemas/PinsEvent" }, + "bot-status": { + "$ref": "#/components/schemas/BotStatusEvent" + }, "heartbeat": { "$ref": "#/components/schemas/HeartbeatEvent" } }, - "description": "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Each pins event carries a PinsEvent: the account's pinned conversations after a change, which the session also returns. Current chat previews replay on connection; finished replies, learned events, and pins events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", + "description": "Server-sent events. Each activity event carries a ReplyEvent or ChatPreviewEvent JSON object in data. Each learned event carries a LearnedEvent: what a bot's review of one turn changed; GET /v1/agents/{id}/reviews lists them durably. Each pins event carries a PinsEvent: the account's pinned conversations after a change, which the session also returns. Each bot-status event carries a BotStatusEvent: what a bot is doing or needs from the owner. Current chat previews and bot statuses replay on connection; finished replies, learned events, and pins events are not replayed. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. No Last-Event-ID replay.", "security": [ { "BearerAuth": [] From ca1a0b283b570436048ff832b3db5cb928996767 Mon Sep 17 00:00:00 2001 From: Leonhard Breuer Date: Mon, 23 Nov 2026 11:57:17 +0100 Subject: [PATCH 2/2] feat(web): redesign the sidebar around pinned bots and their status Pinned bots are portraits, three to a row, above Automations and the other bots. Avatars show the bot status from the server, also for chats that aren't open. Memory and the theme move to Settings, Activity and Settings to the header. The exclamation mark no longer means a retry. --- CHANGELOG.md | 2 + apps/docs/content/clients/web.md | 46 +- .../content/concepts/memory-and-skills.md | 2 +- .../docs/content/getting-started/first-bot.md | 5 +- apps/web/app/activity-stream.ts | 16 + apps/web/app/command-palette.tsx | 7 +- apps/web/app/navigation.ts | 31 +- apps/web/app/pinned-bots.tsx | 156 +++++++ apps/web/app/router.tsx | 11 +- apps/web/app/shell.tsx | 411 +----------------- apps/web/app/sidebar.dom.test.tsx | 401 +++++++++++++++++ apps/web/app/sidebar.tsx | 269 ++++++++++++ apps/web/app/unread.tsx | 24 + apps/web/components/bot-avatar.tsx | 17 +- apps/web/components/ui/context-menu.tsx | 52 +++ apps/web/features/bot-chat/avatar.tsx | 72 ++- apps/web/features/bot-chat/working.ts | 4 - apps/web/features/bots/status.ts | 33 ++ apps/web/features/settings/appearance.tsx | 35 ++ apps/web/features/settings/sections.ts | 2 + apps/web/features/settings/settings.tsx | 2 + apps/web/lib/notifications.ts | 20 +- 22 files changed, 1141 insertions(+), 477 deletions(-) create mode 100644 apps/web/app/pinned-bots.tsx create mode 100644 apps/web/app/sidebar.dom.test.tsx create mode 100644 apps/web/app/sidebar.tsx create mode 100644 apps/web/app/unread.tsx create mode 100644 apps/web/components/ui/context-menu.tsx create mode 100644 apps/web/features/bots/status.ts create mode 100644 apps/web/features/settings/appearance.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index e51f673f..e9a70224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- The web sidebar shows pinned bots as portraits, like the Apple clients, and every bot's avatar shows its status even when its chat isn't open: thinking, working, or an exclamation mark when it needs you or its last reply failed. A retrying bot now shows as working. **Memory** and **Theme** moved to **Settings**, **Activity** and **Settings** are icons at the top, and search is `⌘K` (an icon on phones). `GET /v1/agents` returns `status` for each bot, and `/v1/events` sends `bot-status` events. +- Bots can mark a reply as a question with the `mark_question` tool. The bot has the status `question` until you answer. - Remove repository-owned source comments, preserve consequential decisions in ADRs, and enforce a zero-comment baseline across source and configuration. Add the repository-local `/delete-comment` skill. Move migration separators into metadata without changing historical hashes or execution groups, and replace inline lint/type directives with configuration. - Replace custom lint rules and vendored plugins with `@cloudflare/oxlint-config`. diff --git a/apps/docs/content/clients/web.md b/apps/docs/content/clients/web.md index 7818edc5..8e3b4c3d 100644 --- a/apps/docs/content/clients/web.md +++ b/apps/docs/content/clients/web.md @@ -12,20 +12,38 @@ Sign in with the account you created when you ## Sidebar -| Section | What's there | -| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| **Pinned** | Up to nine bot chats. Pin or unpin one from its **More** menu, and drag pins to reorder them. Your other apps show the same pins. | -| **Bots** | Each bot's chat, with its jobs and desktop. | -| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. | -| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. | -| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. | -| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. | -| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. | - -Press `⌘K`, or `Ctrl+K`, or select **Search** in the sidebar to open the -command palette. It jumps to a bot, workspace page, or settings -section, creates a bot, and switches the theme. To search inside -conversations, ask a bot. It +| Part | What's there | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Header** | The **Activity** and **Settings** icons. On a phone, a **Search** icon too. | +| **Pinned bots** | Up to nine bots as round portraits, three per row, above the list so they stay in view while you scroll. Right-click a portrait, or press and hold it, then select **Unpin**. Drag one onto another to reorder. Your other apps show the same pins. | +| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. | +| **Bots** | Each unpinned bot's chat, with its jobs and desktop. Select **+** to create a bot, or **More** > **Pin** on a bot to pin it. | + +**Activity** lists everything bots did, by day. Filter by kind or bot, and +revert a change to a skill or memory. + +Each bot's avatar shows what it's doing, and a dot marks a bot with replies you +haven't seen. The sidebar updates as bots work, whether or not their chats are +open. Point at a bot, or use a screen reader, to read why its avatar looks +the way it does, such as "has a question", "needs your decision", or "last reply +failed". + +When the web app loses its connection to the server, the sidebar shows +**Reconnecting…** or **Disconnected** below the header. + +Memory, theme, and sign-out live in **Settings**: + +- **Settings** > **General** > **Appearance** sets the theme to System, Light, + or Dark. The choice is saved to your account, so your other devices use it + too. +- **Settings** > **Memory** shows every bot's memories and your shared + memories. Edit or delete them there. The old `/memory` address redirects to + it. + +On a computer, press `⌘K` or `Ctrl+K` to open the command palette. On a phone, +select **Search** in the sidebar header. The palette jumps to a bot, workspace +page, or settings section, creates a bot, and switches the theme. To search +inside conversations, ask a bot. It [searches its transcripts](/concepts/chats#searching-the-transcript) for you. ## Request Cards diff --git a/apps/docs/content/concepts/memory-and-skills.md b/apps/docs/content/concepts/memory-and-skills.md index 08bbf01a..6ad6c558 100644 --- a/apps/docs/content/concepts/memory-and-skills.md +++ b/apps/docs/content/concepts/memory-and-skills.md @@ -17,7 +17,7 @@ A memory is either the bot's own, or **shared** with every one of your bots that has memory turned on. Every memory records where it came from: a bot chat, you, a scheduled task, or another bot. -Review and edit memories on the **Memory** page. +Review and edit memories in **Settings** > **Memory**. The bot's [jobs](/concepts/workspaces#jobs) see its memories too, but only read them. diff --git a/apps/docs/content/getting-started/first-bot.md b/apps/docs/content/getting-started/first-bot.md index 3acbd9fe..b0fb53e7 100644 --- a/apps/docs/content/getting-started/first-bot.md +++ b/apps/docs/content/getting-started/first-bot.md @@ -37,8 +37,9 @@ choice. Live avatars respect your system's reduced-motion setting. An avatar shows what its bot is doing. While the bot thinks, its body turns into three hopping dots. While it writes, searches, remembers, or uses tools, it -bends over the work. When it retries, it shows an exclamation mark. When a reply -finishes, it celebrates for a few seconds. +bends over the work, including while it retries. When it has a question for you, +needs your decision, or its last reply failed, it shows an exclamation mark. +When a reply finishes, it celebrates for a few seconds. Bots without a saved definition get a fresh gallery avatar with default colors. The bot ID selects the shape; previous avatar shapes and colors don't affect it. diff --git a/apps/web/app/activity-stream.ts b/apps/web/app/activity-stream.ts index 94a4e1d8..df019a46 100644 --- a/apps/web/app/activity-stream.ts +++ b/apps/web/app/activity-stream.ts @@ -1,6 +1,7 @@ import { useSyncExternalStore } from "react"; import { activityEvent, + botStatusEvent, pinsEvent, } from "@crumble/server/contract/api-responses"; import { authClient } from "@/lib/auth-client"; @@ -42,6 +43,14 @@ function preview(agentId: string, lastMessage: string) { ); } +function setStatusOf(agentId: string, botStatus: Bot["status"]) { + queryClient.setQueryData(botsQuery.queryKey, (bots: Array | undefined) => + bots?.map((bot) => + bot.id === agentId ? { ...bot, status: botStatus } : bot, + ), + ); +} + let activityFollower = 0; let activityController: AbortController | null = null; @@ -85,6 +94,13 @@ export function followActivity(links: ChatLinks, signal: AbortSignal) { return; } + if (name === "bot-status") { + const event = botStatusEvent.parse(JSON.parse(data)); + setStatusOf(event.agentId, event.status); + + return; + } + if (name !== "activity") { return; } diff --git a/apps/web/app/command-palette.tsx b/apps/web/app/command-palette.tsx index 2dc31513..d67d7f20 100644 --- a/apps/web/app/command-palette.tsx +++ b/apps/web/app/command-palette.tsx @@ -20,17 +20,14 @@ import { setTheme, useTheme } from "@/lib/theme"; import { BotAvatar } from "@/components/bot-avatar"; import { settingsSections } from "@/features/settings/sections"; import { useIsAdmin } from "@/lib/auth-client"; -import { THEME_OPTIONS, PAGES } from "./navigation"; +import { THEME_OPTIONS } from "@/features/settings/appearance"; +import { PAGES } from "./navigation"; const filter = (value: string, search: string, keywords?: Array) => keywords?.length ? defaultFilter(keywords.join(" "), search) : defaultFilter(value, search); -export const PALETTE_SHORTCUT = /Mac|iPhone|iPad/.test(navigator.userAgent) - ? "⌘K" - : "Ctrl K"; - type Run = (action: () => void) => void; type Go = (options: Parameters>[0]) => void; diff --git a/apps/web/app/navigation.ts b/apps/web/app/navigation.ts index 921e8e67..e10b681f 100644 --- a/apps/web/app/navigation.ts +++ b/apps/web/app/navigation.ts @@ -1,20 +1,15 @@ -import { - IconActivity, - IconBrain, - IconCalendarRepeat, - IconDeviceDesktop, - IconMoon, - IconSun, -} from "@tabler/icons-react"; +import { IconActivity, IconCalendarRepeat } from "@tabler/icons-react"; -export const PAGES = [ - { to: "/memory", label: "Memory", icon: IconBrain }, - { to: "/automations", label: "Automations", icon: IconCalendarRepeat }, - { to: "/activity", label: "Activity", icon: IconActivity }, -] as const; +export const AUTOMATIONS = { + to: "/automations", + label: "Automations", + icon: IconCalendarRepeat, +} as const; -export const THEME_OPTIONS = [ - { value: "system", label: "System", icon: IconDeviceDesktop }, - { value: "light", label: "Light", icon: IconSun }, - { value: "dark", label: "Dark", icon: IconMoon }, -] as const; +export const ACTIVITY = { + to: "/activity", + label: "Activity", + icon: IconActivity, +} as const; + +export const PAGES = [AUTOMATIONS, ACTIVITY] as const; diff --git a/apps/web/app/pinned-bots.tsx b/apps/web/app/pinned-bots.tsx new file mode 100644 index 00000000..c89ae60c --- /dev/null +++ b/apps/web/app/pinned-bots.tsx @@ -0,0 +1,156 @@ +import { useRef, useState } from "react"; +import { Link } from "@tanstack/react-router"; +import { IconPinnedOff } from "@tabler/icons-react"; +import { + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuTrigger, +} from "@/components/ui/context-menu"; +import { botColor, botStyle } from "@/components/bot-avatar"; +import { StatusBotAvatar } from "@/features/bot-chat/avatar"; +import type { Bot } from "@/features/bots/api"; +import { botLabel } from "@/features/bots/status"; +import { botPin } from "@/lib/pins"; +import type { Pins } from "@/lib/pins"; +import { cn } from "@/lib/utils"; +import { UnreadDot, useBotUnread } from "./unread"; + +const CIRCLE = 60; +const AVATAR = 41; + +type DraggedRef = { current: string | null }; + +function PinTile({ + bot, + pins, + active, + draggedRef, +}: { + bot: Bot; + pins: Pins; + active: boolean; + draggedRef: DraggedRef; +}) { + const key = botPin(bot.id); + const [target, setTarget] = useState(false); + const menuOpen = useRef(false); + const unread = useBotUnread(bot.id); + const label = botLabel(bot, { pinned: true, unread }); + + return ( + { + menuOpen.current = open; + }} + > + { + draggedRef.current = key; + event.dataTransfer.effectAllowed = "move"; + }} + onDragOver={(event) => { + if (!draggedRef.current || draggedRef.current === key) { + return; + } + + event.preventDefault(); + setTarget(true); + }} + onDragLeave={() => setTarget(false)} + onDrop={(event) => { + event.preventDefault(); + setTarget(false); + + if (draggedRef.current) { + pins.move(draggedRef.current, key); + } + + draggedRef.current = null; + }} + onDragEnd={() => { + draggedRef.current = null; + }} + /> + } + > + { + if (menuOpen.current) { + event.preventDefault(); + } + }} + className="group/pin flex w-[72px] flex-col items-center gap-1 rounded-[10px] px-1.5 pt-[7px] pb-1 outline-hidden transition-[scale] focus-visible:ring-2 focus-visible:ring-sidebar-ring active:scale-[0.96] data-active:bg-bot-soft" + > + + + {unread > 0 && } + + 0 && "font-semibold text-foreground", + !bot.enabled && "opacity-60", + )} + > + {bot.name} + + + + + pins.unpin(key)}> + + Unpin + + + + ); +} + +export function PinnedBots({ + bots, + pins, + activeId, +}: { + bots: Array; + pins: Pins; + activeId: string | undefined; +}) { + const draggedRef = useRef(null); + + if (bots.length === 0) { + return null; + } + + return ( +
    + {bots.map((bot) => ( + + ))} +
+ ); +} diff --git a/apps/web/app/router.tsx b/apps/web/app/router.tsx index 4bf7c53d..bf184b9b 100644 --- a/apps/web/app/router.tsx +++ b/apps/web/app/router.tsx @@ -157,7 +157,9 @@ const botLibraryRoute = createRoute({ const memoryRoute = createRoute({ getParentRoute: () => appRoute, path: "/memory", - component: MemoryPage, + beforeLoad: () => { + redirect({ to: "/settings/memory", replace: true, throw: true }); + }, }); const automationsRoute = createRoute({ @@ -234,6 +236,12 @@ const generalRoute = createRoute({ component: GeneralSettings, }); +const settingsMemoryRoute = createRoute({ + getParentRoute: () => settingsRoute, + path: "/memory", + component: MemoryPage, +}); + const providersRoute = createRoute({ getParentRoute: () => settingsRoute, path: "/providers", @@ -354,6 +362,7 @@ export const router = createRouter({ settingsRoute.addChildren([ settingsIndexRoute, generalRoute, + settingsMemoryRoute, providersRoute, passwordManagersRoute, webSearchRoute, diff --git a/apps/web/app/shell.tsx b/apps/web/app/shell.tsx index 92b2ded4..8e375fac 100644 --- a/apps/web/app/shell.tsx +++ b/apps/web/app/shell.tsx @@ -1,9 +1,6 @@ import { useEffect, useRef, useState } from "react"; -import type { ComponentProps } from "react"; import { useQuery } from "@tanstack/react-query"; -import type { UseQueryResult } from "@tanstack/react-query"; import { - Link, useMatchRoute, useNavigate, useRouter, @@ -11,62 +8,22 @@ import { Outlet, } from "@tanstack/react-router"; import { - IconDots, - IconPin, - IconPinnedOff, - IconPlus, - IconSearch, - IconSettings, -} from "@tabler/icons-react"; -import { - Sidebar, - SidebarContent, - SidebarFooter, - SidebarGroup, - SidebarGroupAction, - SidebarGroupContent, - SidebarGroupLabel, - SidebarHeader, SidebarInset, - SidebarMenu, - SidebarMenuAction, - SidebarMenuButton, - SidebarMenuItem, - SidebarMenuSkeleton, SidebarProvider, SidebarTrigger, useSidebar, } from "@/components/ui/sidebar"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuRadioGroup, - DropdownMenuRadioItem, - DropdownMenuTrigger, -} from "@/components/ui/dropdown-menu"; import { TooltipProvider } from "@/components/ui/tooltip"; -import { CrumbleMark } from "@/components/crumble-mark"; -import { cn, plainMarkdown } from "@/lib/utils"; import { botsQuery } from "@/features/bots/api"; import type { Bot } from "@/features/bots/api"; import { authClient } from "@/lib/auth-client"; -import { - setTheme, - setThemeColor, - useAccountTheme, - useTheme, -} from "@/lib/theme"; +import { setThemeColor, useAccountTheme, useTheme } from "@/lib/theme"; import { resetSession, signedOut } from "@/lib/session"; -import { botPin, usePins } from "@/lib/pins"; -import type { Pins } from "@/lib/pins"; -import { botStatusLine, isBusy, useWorking } from "@/features/bot-chat/working"; -import { followActivity, useConnectionStatus } from "./activity-stream"; +import { usePins } from "@/lib/pins"; +import { followActivity } from "./activity-stream"; import { markSeen, useUnreadCount } from "@/lib/notifications"; -import { botColor, botStyle } from "@/components/bot-avatar"; -import { LiveBotAvatar } from "@/features/bot-chat/avatar"; -import { CommandPalette, PALETTE_SHORTCUT } from "./command-palette"; -import { THEME_OPTIONS, PAGES } from "./navigation"; +import { CommandPalette } from "./command-palette"; +import { AppSidebar } from "./sidebar"; import type { ReplyChat } from "@/lib/notifications"; function useResetOnUserChange(userId: string | undefined) { @@ -165,21 +122,11 @@ export function Shell() { return ( - - - - - Crumble - - setPaletteOpen(true)} /> - - - - - - - - + setPaletteOpen(true)} + /> @@ -192,341 +139,3 @@ export function Shell() { ); } - -type DragProps = Pick< - ComponentProps<"li">, - "draggable" | "onDragStart" | "onDragOver" | "onDrop" | "onDragEnd" ->; - -function PinnedSection({ - pins, - bots, -}: { - pins: Pins; - bots: Array | undefined; -}) { - const matchRoute = useMatchRoute(); - const dragged = useRef(null); - - if (pins.pinned.length === 0) { - return null; - } - - const botsByPin = new Map(bots?.map((bot) => [botPin(bot.id), bot])); - - const drag = (key: string): DragProps => ({ - draggable: true, - onDragStart: (event) => { - dragged.current = key; - event.dataTransfer.effectAllowed = "move"; - }, - onDragOver: (event) => { - if (!dragged.current || dragged.current === key) { - return; - } - - event.preventDefault(); - event.dataTransfer.dropEffect = "move"; - }, - onDrop: (event) => { - event.preventDefault(); - - if (dragged.current) { - pins.move(dragged.current, key); - } - - dragged.current = null; - }, - onDragEnd: () => { - dragged.current = null; - }, - }); - - return ( - - Pinned - - - {pins.pinned.map((key) => { - const bot = botsByPin.get(key); - - if (bot) { - return ( - - ); - } - - return null; - })} - - - - ); -} - -function PinAction({ - conversation, - pins, -}: { - conversation: string; - pins: Pins; -}) { - if (!pins.ready) { - return null; - } - - const pinned = pins.isPinned(conversation); - - return ( - - } - > - - - - - pinned ? pins.unpin(conversation) : pins.pin(conversation) - } - > - {pinned ? : } - {pinned ? "Unpin" : "Pin"} - - - - ); -} - -function BotsSection({ - bots, - pins, -}: { - bots: UseQueryResult>; - pins: Pins; -}) { - const matchRoute = useMatchRoute(); - - return ( - - Bots - }> - - New bot - - - - {bots.isPending && - [0, 1, 2].map((index) => ( - - - - ))} - {bots.data - ?.filter((bot) => !pins.isPinned(botPin(bot.id))) - .map((bot) => ( - - ))} - {bots.data?.length === 0 && ( -

No bots yet

- )} -
- {bots.isError && ( -

{bots.error.message}

- )} -
-
- ); -} - -function WorkspaceSection() { - const matchRoute = useMatchRoute(); - - return ( - - Workspace - - - {PAGES.map((item) => ( - - } - > - - {item.label} - - - ))} - - - - ); -} - -function SettingsFooter() { - const matchRoute = useMatchRoute(); - - return ( - - - - - } - > - - Settings - - - - - - ); -} - -function ThemeMenu() { - const theme = useTheme(); - - const current = - THEME_OPTIONS.find(({ value }) => value === theme) ?? THEME_OPTIONS[0]; - - return ( - - - }> - - Theme - - {current.label} - - - - { - const option = THEME_OPTIONS.find((item) => item.value === value); - - if (option) { - void setTheme(option.value); - } - }} - > - {THEME_OPTIONS.map(({ value, label, icon: Icon }) => ( - - - {label} - - ))} - - - - - ); -} - -function SearchButton({ onOpen }: { onOpen: () => void }) { - return ( - - - - - Search - - {PALETTE_SHORTCUT} - - - - - ); -} - -function ConnectionStatus() { - const status = useConnectionStatus(); - - if (status === "connected") { - return null; - } - - return ( - - {status === "reconnecting" ? "Reconnecting…" : "Disconnected"} - - ); -} - -function BotRow({ - bot, - active, - pins, - drag, -}: { - bot: Bot; - active: boolean; - pins: Pins; - drag?: DragProps; -}) { - const working = isBusy(useWorking(bot.id)); - - return ( - - } - > - - - - {bot.name} - - - {botStatusLine( - bot, - working, - bot.lastMessage - ? plainMarkdown(bot.lastMessage).slice(0, 120) - : bot.description || "No messages yet", - )} - - - - - - ); -} diff --git a/apps/web/app/sidebar.dom.test.tsx b/apps/web/app/sidebar.dom.test.tsx new file mode 100644 index 00000000..e90cc351 --- /dev/null +++ b/apps/web/app/sidebar.dom.test.tsx @@ -0,0 +1,401 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + spyOn, + test, +} from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { QueryClientProvider, useQuery } from "@tanstack/react-query"; +import { + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from "@tanstack/react-router"; +import { z } from "zod"; +import type { Bot } from "@/features/bots/api"; +import { agentFixture } from "@/test/agent-fixture"; +import { defined } from "@/test/defined"; +import { requestPath } from "@/test/request-path"; +import { settle, waitFor } from "@/test/wait-for"; + +const window = new Window({ url: "http://localhost" }); +const globals = Object.getOwnPropertyDescriptors(globalThis); + +const values = { + window, + document: window.document, + navigator: window.navigator, + location: window.location, + localStorage: window.localStorage, + HTMLElement: window.HTMLElement, + Element: window.Element, + Node: window.Node, + MutationObserver: window.MutationObserver, + getComputedStyle: window.getComputedStyle.bind(window), + Event: window.Event, + MouseEvent: window.MouseEvent, + DOMRect: window.DOMRect, + scrollTo: () => {}, + IS_REACT_ACT_ENVIRONMENT: true, + requestAnimationFrame: window.requestAnimationFrame.bind(window), + cancelAnimationFrame: window.cancelAnimationFrame.bind(window), +}; + +const BOTS = [ + { id: "juniper", name: "Juniper", status: "question" }, + { id: "moss", name: "Moss", status: "idle" }, + { id: "fern", name: "Fern", status: "working" }, + { id: "ash", name: "Ash", status: "idle" }, + { id: "birch", name: "Birch", status: "thinking" }, +] satisfies Array>; + +let stored: Array = []; +let written: Array> = []; +let events: ReadableStreamDefaultController | undefined; +let root: Root; +let container: HTMLElement; +let controller: AbortController; +let notifySession: () => void; +let fetch: ReturnType; + +const stubServer = () => + spyOn(globalThis, "fetch").mockImplementation( + Object.assign( + async (input: RequestInfo | URL, init?: RequestInit) => { + const path = requestPath(input); + + if (path === "/v1/agents") { + return Response.json(BOTS.map((bot) => agentFixture(bot))); + } + + if (path === "/v1/events") { + return new Response( + new ReadableStream({ + start(stream) { + events = stream; + }, + }), + ); + } + + if (path.endsWith("/update-user")) { + const body = z + .object({ pinnedConversations: z.array(z.string()) }) + .parse(JSON.parse(z.string().parse(init?.body))); + + written.push(body.pinnedConversations); + stored = body.pinnedConversations; + + return Response.json({ status: true }); + } + + if (path.endsWith("/get-session")) { + return Response.json({ + session: { id: "s", userId: "u" }, + user: { id: "u", pinnedConversations: stored }, + }); + } + + return new Response("unexpected request", { status: 500 }); + }, + { preconnect: globalThis.fetch.preconnect }, + ), + ); + +const send = (name: string, data: unknown) => + act(async () => + events?.enqueue( + new TextEncoder().encode( + `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`, + ), + ), + ); + +const row = (name: string) => + defined( + container.querySelector(`a[aria-label^="${name}"]`), + `the ${name} link`, + ); + +const avatarOf = (name: string) => + defined( + row(name).querySelector("[data-state]"), + `${name}'s avatar`, + ).getAttribute("data-state"); + +const labels = () => + [...container.querySelectorAll("a[aria-label]")].map((link) => + link.getAttribute("aria-label"), + ); + +const follows = (first: Element, second: Element) => + Boolean( + first.compareDocumentPosition(second) & + window.Node.DOCUMENT_POSITION_FOLLOWING, + ); + +const press = (element: Element, ...types: Array) => + act(async () => { + for (const type of types) { + element.dispatchEvent( + new MouseEvent(type, { + bubbles: true, + cancelable: true, + button: 0, + }), + ); + } + }); + +const menuItem = (name: string) => + [...document.querySelectorAll('[role="menuitem"]')].find( + (item) => item.textContent === name, + ); + +beforeAll(async () => { + fetch = stubServer(); + + for (const [key, value] of Object.entries(values)) { + Object.defineProperty(globalThis, key, { configurable: true, value }); + } +}); + +beforeEach(async () => { + stored = ["agent:juniper", "agent:moss"]; + written = []; + events = undefined; + + const { createRoot } = await import("react-dom/client"); + const { SidebarProvider } = await import("@/components/ui/sidebar"); + const { botsQuery } = await import("@/features/bots/api"); + const { queryClient } = await import("@/lib/api"); + const { usePins } = await import("@/lib/pins"); + const { authClient } = await import("@/lib/auth-client"); + const { followActivity } = await import("./activity-stream"); + const { AppSidebar } = await import("./sidebar"); + + queryClient.clear(); + notifySession = () => authClient.$store.notify("$sessionSignal"); + + function Harness() { + const bots = useQuery(botsQuery); + const pins = usePins(bots.data); + + return {}} />; + } + + const rootRoute = createRootRoute({ + component: () => ( + + + + + ), + }); + + const pages = [ + "/bots/$botId", + "/bots/new", + "/automations", + "/activity", + "/settings", + ]; + + const router = createRouter({ + history: createMemoryHistory({ initialEntries: ["/bots/ash"] }), + routeTree: rootRoute.addChildren( + pages.map((path) => + createRoute({ + getParentRoute: () => rootRoute, + path, + component: () => null, + }), + ), + ), + }); + + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + + await act(async () => + root.render( + + + , + ), + ); + + controller = new AbortController(); + + followActivity( + { open: () => {}, pathOf: ({ id }) => `/bots/${id}` }, + controller.signal, + ); + + await act(async () => notifySession()); + await waitFor(() => labels().length >= BOTS.length, "the bots"); + await waitFor(() => events !== undefined, "the event stream"); +}); + +afterEach(async () => { + controller.abort(); + await act(async () => root.unmount()); + container.remove(); +}); + +afterAll(() => { + fetch.mockRestore(); + + for (const key of Object.keys(values)) { + if (globals[key]) { + Object.defineProperty(globalThis, key, globals[key]); + } else { + Reflect.deleteProperty(globalThis, key); + } + } + + window.close(); +}); + +test("lists the pins, then Automations, then the other bots", () => { + const pins = defined( + container.querySelector('[aria-label="Pinned bots"]'), + "the pins", + ); + const automations = defined( + container.querySelector('a[href="/automations"]'), + "Automations", + ); + const bots = defined( + container.querySelector('[data-sidebar="group-label"]'), + "the Bots label", + ); + + expect(pins.textContent).toBe("JuniperMoss"); + expect(follows(pins, automations)).toBe(true); + expect(follows(automations, bots)).toBe(true); + expect(bots.textContent).toBe("Bots"); + expect(follows(bots, row("Fern"))).toBe(true); + expect(pins.contains(row("Juniper"))).toBe(true); + expect(pins.contains(row("Fern"))).toBe(false); +}); + +test("shows each bot's status in its avatar and accessible name", () => { + expect( + labels().filter((label) => label?.match(/^(Juniper|Moss|Fern|Ash|Birch)/)), + ).toEqual([ + "Juniper, pinned, has a question", + "Moss, pinned", + "Fern, working", + "Ash", + "Birch, thinking", + ]); + expect(avatarOf("Juniper")).toBe("question"); + expect(avatarOf("Moss")).toBe("idle"); + expect(avatarOf("Fern")).toBe("working"); + expect(avatarOf("Birch")).toBe("thinking"); +}); + +test("follows bot-status events without any chat open", async () => { + await send("bot-status", { agentId: "ash", status: "failed" }); + await waitFor(() => avatarOf("Ash") === "blocked", "Ash to show blocked"); + expect(row("Ash").getAttribute("aria-label")).toBe("Ash, last reply failed"); + + await send("bot-status", { agentId: "juniper", status: "blocked" }); + await waitFor( + () => + row("Juniper").getAttribute("aria-label") === + "Juniper, pinned, needs your decision", + "Juniper to need a decision", + ); + expect(avatarOf("Juniper")).toBe("blocked"); +}); + +test("marks bots with unread replies", async () => { + const { notifyReply } = await import("@/lib/notifications"); + + const reply = (agentId: string, eventId: string) => + act(async () => + notifyReply( + { + type: "reply", + eventId, + serverId: "server", + agentId, + agentName: agentId, + entryId: null, + origin: "owner", + preview: "Hello", + createdAt: "2026-01-01T00:00:00.000Z", + }, + { open: () => {}, pathOf: ({ id }) => `/bots/${id}` }, + ), + ); + + await reply("juniper", "1"); + await reply("juniper", "2"); + await reply("fern", "3"); + + expect(row("Juniper").getAttribute("aria-label")).toBe( + "Juniper, pinned, 2 unread, has a question", + ); + expect(row("Fern").getAttribute("aria-label")).toBe( + "Fern, 1 unread, working", + ); + expect(row("Juniper").querySelector(".bg-bot-strong")).not.toBeNull(); + expect(row("Fern").querySelector(".bg-bot-strong")).not.toBeNull(); + expect(row("Moss").querySelector(".bg-bot-strong")).toBeNull(); +}); + +test("pins a bot from its More menu", async () => { + const more = defined( + row("Fern").parentElement?.querySelector('[title="More"]'), + "Fern's More button", + ); + + await press( + more, + "pointerdown", + "mousedown", + "pointerup", + "mouseup", + "click", + ); + await waitFor(() => menuItem("Pin") !== undefined, "the menu"); + await press(defined(menuItem("Pin"), "Pin"), "click"); + await waitFor(() => written.length === 1, "the write"); + expect(written).toEqual([["agent:juniper", "agent:moss", "agent:fern"]]); + await waitFor( + () => + defined( + container.querySelector('[aria-label="Pinned bots"]'), + "pins", + ).contains(row("Fern")), + "Fern among the pins", + ); +}); + +test("unpins a bot from its context menu", async () => { + const tile = defined(row("Moss").closest("li"), "Moss's tile"); + + await press(tile, "contextmenu"); + await waitFor(() => menuItem("Unpin") !== undefined, "the menu"); + await press(defined(menuItem("Unpin"), "Unpin"), "click"); + await waitFor(() => written.length === 1, "the write"); + expect(written).toEqual([["agent:juniper"]]); + await settle(); + expect( + container + .querySelector('[aria-label="Pinned bots"]') + ?.contains(row("Moss")), + ).toBe(false); +}); diff --git a/apps/web/app/sidebar.tsx b/apps/web/app/sidebar.tsx new file mode 100644 index 00000000..b6ed9580 --- /dev/null +++ b/apps/web/app/sidebar.tsx @@ -0,0 +1,269 @@ +import { Link, useMatchRoute } from "@tanstack/react-router"; +import type { UseQueryResult } from "@tanstack/react-query"; +import { + IconDots, + IconPin, + IconPlus, + IconSearch, + IconSettings, +} from "@tabler/icons-react"; +import { + Sidebar, + SidebarContent, + SidebarGroup, + SidebarGroupAction, + SidebarGroupContent, + SidebarGroupLabel, + SidebarHeader, + SidebarMenu, + SidebarMenuAction, + SidebarMenuButton, + SidebarMenuItem, + SidebarMenuSkeleton, +} from "@/components/ui/sidebar"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { CrumbleMark } from "@/components/crumble-mark"; +import { botColor, botStyle } from "@/components/bot-avatar"; +import { StatusBotAvatar } from "@/features/bot-chat/avatar"; +import type { Bot } from "@/features/bots/api"; +import { botLabel } from "@/features/bots/status"; +import { botPin } from "@/lib/pins"; +import type { Pins } from "@/lib/pins"; +import { cn } from "@/lib/utils"; +import { useConnectionStatus } from "./activity-stream"; +import { ACTIVITY, AUTOMATIONS } from "./navigation"; +import { PinnedBots } from "./pinned-bots"; +import { UnreadDot, useBotUnread } from "./unread"; + +const SETTINGS = { + to: "/settings", + label: "Settings", + icon: IconSettings, +} as const; + +const ICON_BUTTON = + "relative grid size-8 shrink-0 place-items-center rounded-lg text-muted-foreground outline-hidden transition-[background-color,color,scale] after:absolute after:-inset-1 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 focus-visible:ring-sidebar-ring active:scale-[0.96] [&_svg]:size-4.5"; + +const WORDMARK = + "mr-auto flex items-center gap-2 rounded-lg px-2 font-heading text-lg font-semibold tracking-tight outline-hidden focus-visible:ring-2 focus-visible:ring-sidebar-ring"; + +function HeaderLink({ item }: { item: typeof ACTIVITY | typeof SETTINGS }) { + const matchRoute = useMatchRoute(); + + return ( + + + + ); +} + +function ConnectionNote() { + const status = useConnectionStatus(); + + if (status === "connected") { + return null; + } + + return ( +

+ {status === "reconnecting" ? "Reconnecting…" : "Disconnected"} +

+ ); +} + +function PinAction({ botKey, pins }: { botKey: string; pins: Pins }) { + if (!pins.ready) { + return null; + } + + return ( + + } + > + + + + pins.pin(botKey)} + > + + Pin + + + + ); +} + +function BotRow({ + bot, + active, + pins, +}: { + bot: Bot; + active: boolean; + pins: Pins; +}) { + const unread = useBotUnread(bot.id); + const label = botLabel(bot, { pinned: false, unread }); + + return ( + + } + > + + 0 && "font-semibold", + !bot.enabled && "opacity-60", + )} + > + {bot.name} + + {unread > 0 && } + + + + ); +} + +function AutomationsRow() { + const matchRoute = useMatchRoute(); + + return ( + + + + } + > + + + + {AUTOMATIONS.label} + + + + + ); +} + +function BotsSection({ + bots, + unpinned, + pins, + activeId, +}: { + bots: UseQueryResult>; + unpinned: Array; + pins: Pins; + activeId: string | undefined; +}) { + return ( + + Bots + }> + + New bot + + + + {bots.isPending && + [0, 1, 2].map((index) => ( + + + + ))} + {unpinned.map((bot) => ( + + ))} + {bots.data?.length === 0 && ( +

No bots yet

+ )} +
+ {bots.isError && ( +

{bots.error.message}

+ )} +
+
+ ); +} + +export function AppSidebar({ + bots, + pins, + onSearch, +}: { + bots: UseQueryResult>; + pins: Pins; + onSearch: () => void; +}) { + const matchRoute = useMatchRoute(); + const match = matchRoute({ to: "/bots/$botId", fuzzy: true }); + const activeId = match ? match.botId : undefined; + const byPin = new Map(bots.data?.map((bot) => [botPin(bot.id), bot])); + const pinned = pins.pinned.flatMap((key) => byPin.get(key) ?? []); + + const unpinned = + bots.data?.filter((bot) => !pins.isPinned(botPin(bot.id))) ?? []; + + return ( + + + + + Crumble + + + + + + + + + + + + + ); +} diff --git a/apps/web/app/unread.tsx b/apps/web/app/unread.tsx new file mode 100644 index 00000000..ac0fc9a5 --- /dev/null +++ b/apps/web/app/unread.tsx @@ -0,0 +1,24 @@ +import { useRouter } from "@tanstack/react-router"; +import { cn } from "@/lib/utils"; +import { useUnread } from "@/lib/notifications"; + +export function useBotUnread(id: string) { + const router = useRouter(); + + return useUnread( + router.buildLocation({ to: "/bots/$botId", params: { botId: id } }) + .pathname, + ); +} + +export function UnreadDot({ className }: { className?: string }) { + return ( +