Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(home): add an involving-me view and live motion to the run board (#22622)

Arvin Xue701b4a46a42
diff --git a/apps/server/src/routers/lambda/agentRunBoard.ts b/apps/server/src/routers/lambda/agentRunBoard.ts
index bb6fc7c951c..686f0b88f14 100644
--- a/apps/server/src/routers/lambda/agentRunBoard.ts
+++ b/apps/server/src/routers/lambda/agentRunBoard.ts
@@ -1,4 +1,4 @@
-import { AGENT_RUN_BOARD_WINDOW_HOURS } from '@lobechat/types';
+import { AGENT_RUN_BOARD_SCOPES, AGENT_RUN_BOARD_WINDOW_HOURS } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -6,7 +6,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { AgentRunBoardModel } from '@/database/models/agentRunBoard';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { buildAgentRunBoard } from '@/server/services/agentRunBoard';
+import { buildAgentRunBoard, filterRunsBy } from '@/server/services/agentRunBoard';
const agentRunBoardProcedure = wsCompatProcedure.use(serverDatabase);
@@ -14,6 +14,9 @@ export const agentRunBoardRouter = router({
get: agentRunBoardProcedure
.input(
z.object({
+ agentId: z.string().optional(),
+ scope: z.enum(AGENT_RUN_BOARD_SCOPES).default('all'),
+ userId: z.string().optional(),
windowHours: z
.number()
.refine((value) => (AGENT_RUN_BOARD_WINDOW_HOURS as readonly number[]).includes(value)),
@@ -26,13 +29,23 @@ export const agentRunBoardRouter = router({
try {
const generatedAt = new Date();
const windowStart = new Date(generatedAt.getTime() - input.windowHours * 60 * 60_000);
- const rows = await new AgentRunBoardModel(ctx.serverDB, ctx.workspaceId).listRuns({
+ const model = new AgentRunBoardModel(ctx.serverDB, ctx.workspaceId);
+ // The involved scope narrows in the query: the model caps the workspace
+ // at 500 runs, so filtering afterwards could show an empty board.
+ const scopedRows = await model.listRuns({
+ involvedUserId: input.scope === 'involved' ? ctx.userId : undefined,
now: generatedAt,
since: windowStart,
});
return {
- data: buildAgentRunBoard({ generatedAt, rows, viewerId: ctx.userId, windowStart }),
+ data: buildAgentRunBoard({
+ filterOptionRows: scopedRows,
+ generatedAt,
+ rows: filterRunsBy(scopedRows, input),
+ viewerId: ctx.userId,
+ windowStart,
+ }),
success: true,
};
} catch (error) {
diff --git a/apps/server/src/services/agentRunBoard/index.test.ts b/apps/server/src/services/agentRunBoard/index.test.ts
index 480210b2008..ff41b39a875 100644
--- a/apps/server/src/services/agentRunBoard/index.test.ts
+++ b/apps/server/src/services/agentRunBoard/index.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { AgentRunBoardRow } from '@/database/models/agentRunBoard';
-import { buildAgentRunBoard, classifyRun } from './index';
+import { buildAgentRunBoard, classifyRun, filterRunsBy } from './index';
const generatedAt = new Date('2026-11-08T12:00:00Z');
const now = generatedAt.getTime();
@@ -14,6 +14,7 @@ const row = (overrides: Partial<AgentRunBoardRow> = {}): AgentRunBoardRow => ({
agentAvatar: null,
agentBackgroundColor: null,
agentId: 'a1',
+ agentName: null,
agentOwnerId: 'owner',
agentTitle: 'Agent',
completedAt: null,
@@ -37,7 +38,6 @@ const row = (overrides: Partial<AgentRunBoardRow> = {}): AgentRunBoardRow => ({
});
const intervention = (overrides = {}) => ({
- canonicalToolKey: 'stripe.refund',
createdAt: minutesAgo(14),
deadline: minutesAgo(-60),
operationId: 'op',
@@ -128,7 +128,8 @@ describe('buildAgentRunBoard', () => {
['mine', true],
['older-team', false],
]);
- expect(board.attention[0].detail).toBe('stripe.refund');
+ // Internal tool keys mean nothing to the person who has to act.
+ expect(board.attention[0].detail).toBeNull();
const older = board.lanes[0].runs.find((run) => run.id === 'older-team');
expect(older?.waitingSince).toEqual(minutesAgo(50));
expect(board.lanes[0].ownerUserId).toBe('owner');
@@ -193,6 +194,16 @@ describe('buildAgentRunBoard', () => {
expect(board.activity).toHaveLength(12);
});
+ it('labels an agent by its name, falling back to its title', () => {
+ const board = build([
+ row({ agentId: 'named', agentName: 'Dario', agentTitle: 'CAO', id: '1' }),
+ row({ agentId: 'titled', agentTitle: 'CAO', id: '2' }),
+ ]);
+
+ expect(board.lanes.map((lane) => lane.title).sort()).toEqual(['CAO', 'Dario']);
+ expect(board.filterOptions.agents.find((a) => a.id === 'named')?.title).toBe('Dario');
+ });
+
it('caps lanes and reports how many were left out', () => {
const rows = Array.from({ length: 33 }, (_, i) => row({ agentId: `a${i}`, id: `${i}` }));
const board = build(rows);
@@ -201,3 +212,34 @@ describe('buildAgentRunBoard', () => {
expect(board.hiddenLaneCount).toBe(3);
});
});
+
+describe('filterRunsBy', () => {
+ const rows = [
+ row({ agentId: 'a1', id: '1', userId: 'u1' }),
+ row({ agentId: 'a2', id: '2', userId: 'u1' }),
+ row({ agentId: 'a1', id: '3', userId: 'u2' }),
+ ];
+ const ids = (filter: { agentId?: string; userId?: string }) =>
+ filterRunsBy(rows, filter).map((r) => r.id);
+
+ it('narrows by agent, member, or both', () => {
+ expect(ids({ agentId: 'a1' })).toEqual(['1', '3']);
+ expect(ids({ userId: 'u1' })).toEqual(['1', '2']);
+ expect(ids({ agentId: 'a1', userId: 'u2' })).toEqual(['3']);
+ expect(ids({})).toEqual(['1', '2', '3']);
+ });
+
+ it('keeps every option offered once a pick narrows the board', () => {
+ const board = buildAgentRunBoard({
+ filterOptionRows: rows,
+ generatedAt,
+ rows: filterRunsBy(rows, { agentId: 'a2' }),
+ viewerId: 'me',
+ windowStart,
+ });
+
+ expect(board.lanes.map((lane) => lane.agentId)).toEqual(['a2']);
+ expect(board.filterOptions.agents.map((agent) => agent.id)).toEqual(['a1', 'a2']);
+ expect(board.filterOptions.memberIds).toEqual(['u1', 'u2']);
+ });
+});
diff --git a/apps/server/src/services/agentRunBoard/index.ts b/apps/server/src/services/agentRunBoard/index.ts
index 9c8a226c6b9..d8a63fd5920 100644
--- a/apps/server/src/services/agentRunBoard/index.ts
+++ b/apps/server/src/services/agentRunBoard/index.ts
@@ -1,10 +1,12 @@
-import type {
- AgentRunBoardActivityBucket,
- AgentRunBoardAttentionItem,
- AgentRunBoardData,
- AgentRunBoardLane,
- AgentRunBoardRun,
- AgentRunBoardRunStatus,
+import {
+ agentDisplayName,
+ type AgentRunBoardActivityBucket,
+ type AgentRunBoardAttentionItem,
+ type AgentRunBoardData,
+ type AgentRunBoardFilterOptions,
+ type AgentRunBoardLane,
+ type AgentRunBoardRun,
+ type AgentRunBoardRunStatus,
} from '@lobechat/types';
import type {
@@ -77,6 +79,10 @@ const ownRunningOperation = (row: AgentRunBoardRow, viewerId: string) =>
? row.runningOperation
: null;
+// `title` is becoming a role marker; people know an agent by its `name`.
+const agentLabel = (row: AgentRunBoardRow) =>
+ agentDisplayName({ name: row.agentName, title: row.agentTitle }) ?? null;
+
const oldestPending = (row: AgentRunBoardRow, now: number) =>
pendingInterventions(row, now).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())[0];
@@ -117,7 +123,7 @@ const attentionBase = (row: AgentRunBoardRow, viewerId: string) => ({
agentAvatar: row.agentAvatar,
agentBackgroundColor: row.agentBackgroundColor,
agentId: row.agentId,
- agentTitle: row.agentTitle,
+ agentTitle: agentLabel(row),
operationId: row.id,
runningOperation: ownRunningOperation(row, viewerId),
title: runTitle(row),
@@ -134,7 +140,7 @@ const toNeedsHuman = (
return {
...attentionBase(row, viewerId),
- detail: first?.canonicalToolKey ?? null,
+ detail: null,
isMine: ownerUserId === viewerId,
kind: 'needs_human',
ownerUserId,
@@ -187,12 +193,30 @@ const buildActivity = (
return buckets;
};
+/** Runs the viewer started, spoke in (`spokenTopicIds`), or is asked to approve. */
+const buildFilterOptions = (rows: AgentRunBoardRow[]): AgentRunBoardFilterOptions => ({
+ agents: [
+ ...new Map(rows.map((r) => [r.agentId, { id: r.agentId, title: agentLabel(r) }])).values(),
+ ],
+ memberIds: [...new Set(rows.map((r) => r.userId))],
+});
+
+/** Narrow to one agent and/or the member who started the run. */
+export const filterRunsBy = (
+ rows: AgentRunBoardRow[],
+ { agentId, userId }: { agentId?: string; userId?: string },
+) =>
+ rows.filter((row) => (!agentId || row.agentId === agentId) && (!userId || row.userId === userId));
+
export const buildAgentRunBoard = ({
+ filterOptionRows,
generatedAt,
rows,
viewerId,
windowStart,
}: {
+ /** The rows before the agent and member picks, so picking one keeps the others offered. */
+ filterOptionRows?: AgentRunBoardRow[];
generatedAt: Date;
rows: AgentRunBoardRow[];
viewerId: string;
@@ -236,7 +260,7 @@ export const buildAgentRunBoard = ({
backgroundColor: row.agentBackgroundColor,
ownerUserId: row.agentOwnerId,
runs: [run],
- title: row.agentTitle,
+ title: agentLabel(row),
});
}
@@ -255,6 +279,7 @@ export const buildAgentRunBoard = ({
.sort((a, b) => b.since.getTime() - a.since.getTime())
.slice(0, MAX_FAILED_ATTENTION),
],
+ filterOptions: buildFilterOptions(filterOptionRows ?? rows),
generatedAt,
hiddenLaneCount: Math.max(0, lanes.length - MAX_LANES),
lanes: lanes.slice(0, MAX_LANES),
diff --git a/locales/en-US/home.json b/locales/en-US/home.json
index 820df51288d..7dae647216d 100644
--- a/locales/en-US/home.json
+++ b/locales/en-US/home.json
@@ -190,21 +190,31 @@
"starter.newLabel": "New",
"starter.write": "Write",
"team.agent.untitled": "Untitled agent",
+ "team.attention.approvalNeeded": "Waiting for approval to continue",
"team.attention.blocked": "Waiting on teammates",
"team.attention.empty": "Nothing is waiting on anyone right now.",
"team.attention.failed": "Failed",
"team.attention.failedAgo": "Failed {{time}} ago",
+ "team.attention.handle": "Review",
"team.attention.needsYou": "Needs you",
+ "team.attention.view": "View",
"team.attention.waiting": "Waiting {{time}}",
"team.axis.now": "Now",
"team.calendar.more": "+{{count}}",
+ "team.emptyInvolved_one": "No runs involving you in the last hour.",
+ "team.emptyInvolved_other": "No runs involving you in the last {{count}} hours.",
"team.empty_one": "No team agent runs in the last hour.",
"team.empty_other": "No team agent runs in the last {{count}} hours.",
+ "team.filter.allAgents": "All agents",
+ "team.filter.allMembers": "All members",
"team.lane.more_one": "+{{count}} more topic",
"team.lane.more_other": "+{{count}} more topics",
+ "team.lane.showLess": "Show less",
"team.lanes.hidden_one": "{{count}} more agent not shown",
"team.lanes.hidden_other": "{{count}} more agents not shown",
"team.run.untitled": "Untitled run",
+ "team.scope.all": "All",
+ "team.scope.involved": "Involving me",
"team.status.done": "Done",
"team.status.failed": "Failed",
"team.status.needs_human": "Needs a person",
diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.json
index 143234e1d61..561274d15ae 100644
--- a/locales/zh-CN/home.json
+++ b/locales/zh-CN/home.json
@@ -190,18 +190,27 @@
"starter.newLabel": "上新",
"starter.write": "写作",
"team.agent.untitled": "未命名助手",
+ "team.attention.approvalNeeded": "需要批准后才能继续",
"team.attention.blocked": "等待团队成员",
"team.attention.empty": "目前没有需要处理的事项。",
"team.attention.failed": "失败",
"team.attention.failedAgo": "{{time}}前失败",
+ "team.attention.handle": "去处理",
"team.attention.needsYou": "需要你处理",
+ "team.attention.view": "查看",
"team.attention.waiting": "已等待 {{time}}",
"team.axis.now": "现在",
"team.calendar.more": "+{{count}}",
+ "team.emptyInvolved_other": "最近 {{count}} 小时没有和你相关的运行。",
"team.empty_other": "最近 {{count}} 小时团队没有 Agent 运行。",
+ "team.filter.allAgents": "全部助手",
+ "team.filter.allMembers": "全部成员",
"team.lane.more_other": "还有 {{count}} 个话题",
+ "team.lane.showLess": "收起",
"team.lanes.hidden_other": "还有 {{count}} 个助手未显示",
"team.run.untitled": "未命名运行",
+ "team.scope.all": "全部",
+ "team.scope.involved": "和我相关",
"team.status.done": "已完成",
"team.status.failed": "失败",
"team.status.needs_human": "等待人工处理",
diff --git a/packages/database/src/models/__tests__/agentRunBoard.test.ts b/packages/database/src/models/__tests__/agentRunBoard.test.ts
index 205dcb36327..53a67f06521 100644
--- a/packages/database/src/models/__tests__/agentRunBoard.test.ts
+++ b/packages/database/src/models/__tests__/agentRunBoard.test.ts
@@ -6,6 +6,7 @@ import {
agentInterventions,
agentOperations,
agents,
+ messages,
tasks,
taskTopics,
topics,
@@ -53,7 +54,14 @@ beforeEach(async () => {
{ id: otherWorkspaceId, name: 'B', primaryOwnerId: owner, slug: otherWorkspaceId },
]);
await serverDB.insert(agents).values([
- { id: 'public-agent', title: 'Public', userId: teammate, visibility: 'public', workspaceId },
+ {
+ id: 'public-agent',
+ name: 'Named',
+ title: 'Public',
+ userId: teammate,
+ visibility: 'public',
+ workspaceId,
+ },
{ id: 'private-agent', title: 'Secret', userId: owner, visibility: 'private', workspaceId },
]);
await serverDB.insert(topics).values({ id: 'base-topic', userId: teammate, workspaceId });
@@ -86,6 +94,7 @@ describe('AgentRunBoardModel.listRuns', () => {
const [row] = await new AgentRunBoardModel(serverDB, workspaceId).listRuns({ now, since });
expect(row).toMatchObject({
+ agentName: 'Named',
agentOwnerId: teammate,
agentTitle: 'Public',
errorMessage: 'boom',
@@ -208,9 +217,66 @@ describe('AgentRunBoardModel.listRuns', () => {
expect(row.interventions).toHaveLength(1);
expect(row.interventions[0]).toMatchObject({
- canonicalToolKey: 'stripe.refund',
status: 'pending',
userId: teammate,
});
});
});
+
+describe('AgentRunBoardModel.listRuns involved scope', () => {
+ it('keeps the viewer’s own runs, topics they wrote in and asks addressed to them', async () => {
+ await serverDB.insert(topics).values({ id: 'spoken-topic', userId: teammate, workspaceId });
+ await serverDB.insert(messages).values([
+ {
+ content: 'hi',
+ id: 'm-user',
+ role: 'user',
+ topicId: 'spoken-topic',
+ userId: owner,
+ workspaceId,
+ },
+ {
+ content: 'reply',
+ id: 'm-assistant',
+ role: 'assistant',
+ topicId: 'base-topic',
+ userId: owner,
+ workspaceId,
+ },
+ ]);
+ await insertRun('own-run', { userId: owner });
+ await insertRun('spoken-run', { topicId: 'spoken-topic' });
+ await insertRun('assistant-only-run');
+ await insertRun('asked-run', { status: 'waiting_for_human' });
+ await serverDB.insert(agentInterventions).values({
+ activityKey: 'activity',
+ allowedActions: [],
+ batchId: 'batch',
+ canonicalToolKey: 'stripe.refund',
+ deadline: new Date('2026-11-08T13:00:00Z'),
+ interactionKind: 'approval',
+ itemCount: 1,
+ itemIndex: 0,
+ operationId: 'asked-run',
+ requestRevisionHash: 'a'.repeat(64),
+ reviewContext: {},
+ reviewTokenHash: 'b'.repeat(64),
+ sanitizedRequest: {},
+ source: 'server',
+ stepIndex: 0,
+ surface: 'chat',
+ systemActionEligibility: 'none',
+ toolCallId: 'call',
+ userId: owner,
+ workspaceId,
+ } as never);
+
+ const rows = await new AgentRunBoardModel(serverDB, workspaceId).listRuns({
+ involvedUserId: owner,
+ now,
+ since,
+ });
+
+ expect(rows.map((r) => r.id).sort()).toEqual(['asked-run', 'own-run', 'spoken-run']);
+ });
+});
diff --git a/packages/database/src/models/agentRunBoard.ts b/packages/database/src/models/agentRunBoard.ts
index 51a528dabfc..b900d1fedbd 100644
--- a/packages/database/src/models/agentRunBoard.ts
+++ b/packages/database/src/models/agentRunBoard.ts
@@ -6,6 +6,7 @@ import {
agentOperations,
agents,
chatGroups,
+ messages,
tasks,
taskTopics,
topics,
@@ -25,6 +26,7 @@ export interface AgentRunBoardRow {
agentAvatar: string | null;
agentBackgroundColor: string | null;
agentId: string;
+ agentName: string | null;
agentOwnerId: string;
agentTitle: string | null;
completedAt: Date | null;
@@ -48,7 +50,6 @@ export interface AgentRunBoardRow {
}
export interface AgentRunBoardInterventionRow {
- canonicalToolKey: string | null;
createdAt: Date;
deadline: Date;
operationId: string;
@@ -73,13 +74,27 @@ export class AgentRunBoardModel {
this.workspaceId = workspaceId;
}
- listRuns = async ({ now, since }: { now: Date; since: Date }): Promise<AgentRunBoardRow[]> => {
+ listRuns = async ({
+ now,
+ since,
+ involvedUserId,
+ }: {
+ now: Date;
+ since: Date;
+ /** Narrows the read to one member's runs *before* the workspace-wide limits. */
+ involvedUserId?: string;
+ }): Promise<AgentRunBoardRow[]> => {
+ // Applied inside both queries: the limits below cap the workspace, so a
+ // post-filter would see a board already emptied of the viewer's runs.
+ const involvement = involvedUserId ? this.involvedCondition(involvedUserId) : undefined;
+
const [windowRows, waitingRows] = await Promise.all([
this.selectRuns(
and(
gte(agentOperations.createdAt, new Date(since.getTime() - MAX_RUN_SPAN_MS)),
ne(agentOperations.status, 'idle'),
or(isNull(agentOperations.completedAt), gte(agentOperations.completedAt, since)),
+ involvement,
),
RUN_LIMIT,
),
@@ -87,6 +102,7 @@ export class AgentRunBoardModel {
and(
gte(agentOperations.createdAt, new Date(now.getTime() - MAX_WAITING_AGE_MS)),
eq(agentOperations.status, 'waiting_for_human'),
+ involvement,
),
WAITING_RUN_LIMIT,
),
@@ -102,7 +118,6 @@ export class AgentRunBoardModel {
const interventions = await this.db
.select({
- canonicalToolKey: agentInterventions.canonicalToolKey,
createdAt: agentInterventions.createdAt,
deadline: agentInterventions.deadline,
operationId: agentInterventions.operationId,
@@ -117,12 +132,39 @@ export class AgentRunBoardModel {
return rows.map((row) => ({ ...row, interventions: byOperation.get(row.id) ?? [] }));
};
+ /**
+ * Started it, wrote in its topic, or must approve it; in SQL so the
+ * limits bound matching runs instead of the unfiltered workspace.
+ */
+ private involvedCondition = (userId: string) =>
+ or(
+ // Ran it themselves.
+ eq(agentOperations.userId, userId),
+ // Wrote in the topic the run belongs to.
+ sql`${agentOperations.topicId} IN (
+ SELECT ${messages.topicId} FROM ${messages}
+ WHERE ${messages.userId} = ${userId}
+ AND ${messages.role} = 'user'
+ AND ${messages.workspaceId} = ${this.workspaceId}
+ )`,
+ // Was asked to intervene. The board only loads interventions for waiting
+ // rows, so the predicate stays on them to keep both paths in step.
+ and(
+ eq(agentOperations.status, 'waiting_for_human'),
+ sql`${agentOperations.id} IN (
+ SELECT ${agentInterventions.operationId} FROM ${agentInterventions}
+ WHERE ${agentInterventions.userId} = ${userId}
+ )`,
+ ),
+ );
+
private selectRuns = async (condition: ReturnType<typeof and>, limit: number) => {
const rows = await this.db
.select({
agentAvatar: agents.avatar,
agentBackgroundColor: agents.backgroundColor,
agentId: agents.id,
+ agentName: agents.name,
agentOwnerId: agents.userId,
agentTitle: agents.title,
completedAt: agentOperations.completedAt,
diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.ts
index fdbce66687b..8e02bcb1a55 100644
--- a/packages/locales/src/default/home.ts
+++ b/packages/locales/src/default/home.ts
@@ -197,21 +197,31 @@ export default {
'starter.newLabel': 'New',
'starter.write': 'Write',
'team.agent.untitled': 'Untitled agent',
+ 'team.attention.approvalNeeded': 'Waiting for approval to continue',
'team.attention.blocked': 'Waiting on teammates',
'team.attention.empty': 'Nothing is waiting on anyone right now.',
'team.attention.failed': 'Failed',
'team.attention.failedAgo': 'Failed {{time}} ago',
+ 'team.attention.handle': 'Review',
'team.attention.needsYou': 'Needs you',
+ 'team.attention.view': 'View',
'team.attention.waiting': 'Waiting {{time}}',
'team.axis.now': 'Now',
'team.calendar.more': '+{{count}}',
'team.empty_one': 'No team agent runs in the last hour.',
'team.empty_other': 'No team agent runs in the last {{count}} hours.',
+ 'team.emptyInvolved_one': 'No runs involving you in the last hour.',
+ 'team.emptyInvolved_other': 'No runs involving you in the last {{count}} hours.',
+ 'team.filter.allAgents': 'All agents',
+ 'team.filter.allMembers': 'All members',
'team.lane.more_one': '+{{count}} more topic',
'team.lane.more_other': '+{{count}} more topics',
+ 'team.lane.showLess': 'Show less',
'team.lanes.hidden_one': '{{count}} more agent not shown',
'team.lanes.hidden_other': '{{count}} more agents not shown',
'team.run.untitled': 'Untitled run',
+ 'team.scope.all': 'All',
+ 'team.scope.involved': 'Involving me',
'team.status.done': 'Done',
'team.status.failed': 'Failed',
'team.status.needs_human': 'Needs a person',
diff --git a/packages/types/src/agentRunBoard.ts b/packages/types/src/agentRunBoard.ts
index 4a49a29c6bf..93335382a4c 100644
--- a/packages/types/src/agentRunBoard.ts
+++ b/packages/types/src/agentRunBoard.ts
@@ -5,6 +5,11 @@ export type AgentRunBoardRunningOperation = NonNullable<ChatTopicMetadata['runni
export const AGENT_RUN_BOARD_WINDOW_HOURS = [1, 6, 24] as const;
+/** `involved`: runs the viewer started, spoke in, or is asked to approve. */
+export const AGENT_RUN_BOARD_SCOPES = ['all', 'involved'] as const;
+
+export type AgentRunBoardScope = (typeof AGENT_RUN_BOARD_SCOPES)[number];
+
export type AgentRunBoardWindowHours = (typeof AGENT_RUN_BOARD_WINDOW_HOURS)[number];
export type AgentRunBoardRunStatus = 'done' | 'failed' | 'needs_human' | 'running' | 'stopped';
@@ -41,7 +46,7 @@ export interface AgentRunBoardAttentionItem {
agentBackgroundColor: string | null;
agentId: string;
agentTitle: string | null;
- /** Failure message, or the tool awaiting approval. */
+ /** Failure message. */
detail: string | null;
/** Whether the viewer is the member who can act on this item. */
isMine: boolean;
@@ -68,9 +73,16 @@ export interface AgentRunBoardActivityBucket extends AgentRunBoardSummary {
startedAt: Date;
}
+/** What the board can be narrowed to, independent of the current agent and member picks. */
+export interface AgentRunBoardFilterOptions {
+ agents: { id: string; title: string | null }[];
+ memberIds: string[];
+}
+
export interface AgentRunBoardData {
activity: AgentRunBoardActivityBucket[];
attention: AgentRunBoardAttentionItem[];
+ filterOptions: AgentRunBoardFilterOptions;
generatedAt: Date;
/** Active agents left out of `lanes` by the lane cap. */
hiddenLaneCount: number;
diff --git a/src/features/HomeTeamBoard/AttentionList.tsx b/src/features/HomeTeamBoard/AttentionList.tsx
index c7818b0b315..55a7174db22 100644
--- a/src/features/HomeTeamBoard/AttentionList.tsx
+++ b/src/features/HomeTeamBoard/AttentionList.tsx
@@ -13,6 +13,13 @@ import { RUN_STATUS_VISUALS } from './statusVisuals';
import { useOpenRunDrawer } from './useOpenRunDrawer';
const styles = stylex.create({
+ action: {
+ color: cssVar.colorPrimary,
+ flexShrink: 0,
+ fontSize: 12,
+ fontWeight: 500,
+ whiteSpace: 'nowrap',
+ },
card: {
backgroundColor: cssVar.colorBgContainer,
borderColor: cssVar.colorBorderSecondary,
@@ -53,6 +60,7 @@ const Item = ({ item, now }: { item: AgentRunBoardAttentionItem; now: Date }) =>
const { t } = useTranslation('home');
const openDrawer = useOpenRunDrawer();
const failed = item.kind === 'failed';
+ const canAct = item.isMine && !failed;
const elapsed = formatDuration(now.getTime() - item.since.getTime());
const title = item.title || t('team.run.untitled');
@@ -92,7 +100,15 @@ const Item = ({ item, now }: { item: AgentRunBoardAttentionItem; now: Date }) =>
{t(failed ? 'team.attention.failedAgo' : 'team.attention.waiting', { time: elapsed })}
</span>
</Flexbox>
- {item.detail && <span {...stylex.props(styles.detail)}>{item.detail}</span>}
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <span {...stylex.props(styles.detail)}>
+ {failed ? item.detail : t('team.attention.approvalNeeded')}
+ </span>
+ {/* A span: the whole row is the button, and the drawer holds the approval card. */}
+ <span {...stylex.props(styles.action)} data-testid={'team-board-attention-action'}>
+ {t(canAct ? 'team.attention.handle' : 'team.attention.view')}
+ </span>
+ </Flexbox>
</Flexbox>
</button>
);
diff --git a/src/features/HomeTeamBoard/BoardFilters.tsx b/src/features/HomeTeamBoard/BoardFilters.tsx
new file mode 100644
index 00000000000..6148d57c05f
--- /dev/null
+++ b/src/features/HomeTeamBoard/BoardFilters.tsx
@@ -0,0 +1,60 @@
+import type { AgentRunBoardFilterOptions } from '@lobechat/types';
+import { Flexbox, Select } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceMemberProfiles } from '@/business/client/hooks/useWorkspaceMemberProfiles';
+
+const ALL = 'all';
+const SELECT_STYLE = { width: 180 };
+
+interface BoardFiltersProps {
+ agentId?: string;
+ onAgentChange: (agentId?: string) => void;
+ onUserChange: (userId?: string) => void;
+ options: AgentRunBoardFilterOptions;
+ userId?: string;
+}
+
+const BoardFilters = ({
+ agentId,
+ onAgentChange,
+ onUserChange,
+ options,
+ userId,
+}: BoardFiltersProps) => {
+ const { t } = useTranslation('home');
+ const profiles = useWorkspaceMemberProfiles();
+
+ return (
+ <Flexbox horizontal data-testid={'team-board-filters'} gap={8} wrap={'wrap'}>
+ <Select
+ size={'small'}
+ style={SELECT_STYLE}
+ value={agentId ?? ALL}
+ options={[
+ { label: t('team.filter.allAgents'), value: ALL },
+ ...options.agents.map((agent) => ({
+ label: agent.title || t('team.agent.untitled'),
+ value: agent.id,
+ })),
+ ]}
+ onChange={(value) => onAgentChange(value === ALL ? undefined : String(value))}
+ />
+ <Select
+ size={'small'}
+ style={SELECT_STYLE}
+ value={userId ?? ALL}
+ options={[
+ { label: t('team.filter.allMembers'), value: ALL },
+ ...options.memberIds.map((id) => {
+ const member = profiles.get(id);
+ return { label: member?.fullName || member?.username || id, value: id };
+ }),
+ ]}
+ onChange={(value) => onUserChange(value === ALL ? undefined : String(value))}
+ />
+ </Flexbox>
+ );
+};
+
+export default BoardFilters;
diff --git a/src/features/HomeTeamBoard/Timeline.tsx b/src/features/HomeTeamBoard/Timeline.tsx
index e8c3ad7fdc0..5ab9828fb79 100644
--- a/src/features/HomeTeamBoard/Timeline.tsx
+++ b/src/features/HomeTeamBoard/Timeline.tsx
@@ -1,8 +1,10 @@
import type { AgentRunBoardData, AgentRunBoardLane, AgentRunBoardRunStatus } from '@lobechat/types';
-import { Flexbox, Text, Tooltip } from '@lobehub/ui';
+import { Flexbox, Icon, Text, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import dayjs from 'dayjs';
+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useWorkspaceMemberProfiles } from '@/business/client/hooks/useWorkspaceMemberProfiles';
@@ -12,6 +14,7 @@ import AuthorChip from '@/features/HomeInbox/AuthorChip';
import { sx } from '@/styles/sx';
import {
+ axisPercent,
buildAxisTicks,
formatDuration,
layoutLaneTopics,
@@ -24,9 +27,39 @@ import { RUN_STATUS_VISUALS } from './statusVisuals';
import { useOpenRunDrawer } from './useOpenRunDrawer';
const BAR_HEIGHT = 22;
+const WAIT_MARK_WIDTH = 28;
+
+const shineSweep = stylex.keyframes({
+ from: { transform: 'translateX(-100%)' },
+ to: { transform: 'translateX(250%)' },
+});
const styles = stylex.create({
- agent: { paddingBlock: 6 },
+ agent: {
+ alignItems: 'center',
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ borderWidth: 0,
+ color: 'inherit',
+ cursor: 'pointer',
+ display: 'flex',
+ font: 'inherit',
+ gap: 8,
+ maxWidth: '100%',
+ paddingBlock: 6,
+ paddingInline: 0,
+ textAlign: 'start',
+ },
+ moreButton: {
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ borderWidth: 0,
+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },
+ cursor: 'pointer',
+ fontSize: 12,
+ paddingBlock: 2,
+ paddingInline: 0,
+ },
axis: { height: 20, position: 'relative' },
bar: {
borderRadius: 5,
@@ -85,7 +118,6 @@ const styles = stylex.create({
transform: 'translateX(-50%)',
whiteSpace: 'nowrap',
},
- tickEnd: { transform: 'translateX(-100%)' },
tickStart: { transform: 'none' },
barLabel: {
alignItems: 'center',
@@ -101,17 +133,66 @@ const styles = stylex.create({
},
barLabelAuthor: { flexShrink: 0, pointerEvents: 'auto' },
barLabelText: {
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ borderWidth: 0,
+ color: 'inherit',
+ cursor: { 'default': 'pointer', ':disabled': 'default' },
+ font: 'inherit',
minWidth: 0,
overflow: 'hidden',
+ paddingBlock: 0,
+ paddingInline: 0,
+ pointerEvents: 'auto',
+ textDecorationLine: { 'default': 'none', ':hover:not(:disabled)': 'underline' },
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
- segment: { display: 'block', height: '100%' },
+ waitIcon: {
+ alignItems: 'center',
+ display: 'flex',
+ height: '100%',
+ justifyContent: 'center',
+ },
+ segment: { display: 'block', height: '100%', overflow: 'hidden', position: 'relative' },
+ live: { borderInlineEndStyle: 'solid', borderInlineEndWidth: 2, boxSizing: 'border-box' },
+ shine: {
+ animationDuration: '2.4s',
+ animationIterationCount: 'infinite',
+ animationName: { 'default': shineSweep, '@media (prefers-reduced-motion: reduce)': 'none' },
+ animationTimingFunction: 'ease-in-out',
+ bottom: 0,
+ display: 'block',
+ left: 0,
+ position: 'absolute',
+ top: 0,
+ width: '40%',
+ },
track: { flexGrow: 1, height: 28, minWidth: 0, position: 'relative' },
});
-const tint = (status: AgentRunBoardRunStatus) =>
- `color-mix(in srgb, ${RUN_STATUS_VISUALS[status].color} 32%, transparent)`;
+const mix = (status: AgentRunBoardRunStatus, percent: number) =>
+ `color-mix(in srgb, ${RUN_STATUS_VISUALS[status].color} ${percent}%, transparent)`;
+
+const tint = (status: AgentRunBoardRunStatus) => mix(status, 32);
+
+/** Live work: fills toward its leading edge, with a light sweeping across it. */
+const LiveSegment = () => (
+ <span
+ data-testid={'team-board-run-live'}
+ {...sx(styles.segment, styles.live, {
+ backgroundImage: `linear-gradient(to right, ${mix('running', 8)}, ${mix('running', 45)})`,
+ borderInlineEndColor: RUN_STATUS_VISUALS.running.color,
+ flexGrow: 1,
+ })}
+ >
+ <span
+ {...sx(styles.shine, {
+ backgroundImage: `linear-gradient(to right, transparent, ${mix('running', 55)}, transparent)`,
+ })}
+ />
+ </span>
+);
const Bar = ({
agentId,
@@ -127,7 +208,8 @@ const Bar = ({
const { t } = useTranslation('home');
const openDrawer = useOpenRunDrawer();
const profiles = useWorkspaceMemberProfiles();
- const { left, run, runningShare, width } = placed;
+ const { left, run, width } = placed;
+ const waiting = run.status === 'needs_human';
const member = profiles.get(run.userId);
const duration = formatDuration((run.endedAt ?? now).getTime() - run.startedAt.getTime());
@@ -151,7 +233,7 @@ const Bar = ({
type={'button'}
{...sx(styles.bar, {
insetInlineStart: `${left}%`,
- width: `${width}%`,
+ width: waiting ? `calc(${width}% + ${WAIT_MARK_WIDTH}px)` : `${width}%`,
})}
onClick={() =>
openDrawer({
@@ -162,23 +244,45 @@ const Bar = ({
})
}
>
- {runningShare !== null && (
- <span
- data-testid={'team-board-run-before-ask'}
- {...sx(styles.segment, {
- backgroundColor: tint('running'),
- flexBasis: `${runningShare}%`,
- })}
- />
+ {waiting ? (
+ <>
+ <span
+ {...sx(styles.segment, {
+ backgroundImage: `linear-gradient(to right, ${mix('running', 10)}, ${mix('running', 38)})`,
+ flexGrow: 1,
+ })}
+ />
+ <span
+ data-testid={'team-board-run-wait-mark'}
+ {...sx(styles.segment, {
+ backgroundColor: RUN_STATUS_VISUALS.needs_human.color,
+ flexBasis: WAIT_MARK_WIDTH,
+ flexShrink: 0,
+ })}
+ >
+ <span {...stylex.props(styles.waitIcon)}>
+ <Icon
+ color={cssVar.colorBgContainer}
+ icon={RUN_STATUS_VISUALS.needs_human.icon}
+ size={14}
+ />
+ </span>
+ </span>
+ </>
+ ) : run.status === 'running' ? (
+ <LiveSegment />
+ ) : (
+ <span {...sx(styles.segment, { backgroundColor: tint(run.status), flexGrow: 1 })} />
)}
- <span {...sx(styles.segment, { backgroundColor: tint(run.status), flexGrow: 1 })} />
</button>
</Tooltip>
);
};
-const RowLabel = ({ row, title }: { row: TopicRow; title: string }) => {
+const RowLabel = ({ agentId, row, title }: { agentId: string; row: TopicRow; title: string }) => {
+ const openDrawer = useOpenRunDrawer();
const { anchor, offset, room } = resolveRowLabel(row.runs);
+ const latestRun = row.runs.at(-1)!.run;
return (
<span
@@ -193,7 +297,22 @@ const RowLabel = ({ row, title }: { row: TopicRow; title: string }) => {
<span {...stylex.props(styles.barLabelAuthor)}>
<AuthorChip avatarOnly trigger={row.trigger} userId={row.startedBy} />
</span>
- <span {...stylex.props(styles.barLabelText)}>{title}</span>
+ <button
+ data-testid={'team-board-topic-open'}
+ disabled={!row.topicId}
+ type={'button'}
+ {...stylex.props(styles.barLabelText)}
+ onClick={() =>
+ openDrawer({
+ agentId,
+ runningOperation: latestRun.runningOperation,
+ title,
+ topicId: row.topicId,
+ })
+ }
+ >
+ {title}
+ </button>
</span>
);
};
@@ -209,12 +328,25 @@ const Lane = ({
}) => {
const { t } = useTranslation('home');
const meta = useAgentDisplayMeta(lane.agentId);
- const { overflow, rows } = layoutLaneTopics(lane.runs, windowStart, now);
+ const [collapsed, setCollapsed] = useState(false);
+ const [expanded, setExpanded] = useState(false);
+ const { overflow, rows } = layoutLaneTopics(lane.runs, windowStart, now, { expanded });
const agentTitle = lane.title || meta?.title || t('team.agent.untitled');
return (
<div {...stylex.props(styles.lane)} data-testid={'team-board-lane'}>
- <Flexbox horizontal align={'center'} gap={8} {...stylex.props(styles.agent)}>
+ <button
+ aria-expanded={!collapsed}
+ data-testid={'team-board-lane-toggle'}
+ type={'button'}
+ {...stylex.props(styles.agent)}
+ onClick={() => setCollapsed((value) => !value)}
+ >
+ <Icon
+ color={cssVar.colorTextQuaternary}
+ icon={collapsed ? ChevronRightIcon : ChevronDownIcon}
+ size={14}
+ />
<AgentAvatar
agentId={lane.agentId}
avatar={lane.avatar ?? undefined}
@@ -226,37 +358,43 @@ const Lane = ({
{agentTitle}
</Text>
<AuthorChip avatarOnly userId={lane.ownerUserId} />
- </Flexbox>
- {rows.map((row) => {
- const title = row.title || t('team.run.untitled');
+ </button>
+ {!collapsed &&
+ rows.map((row) => {
+ const title = row.title || t('team.run.untitled');
- return (
- <Flexbox
- horizontal
- align={'center'}
- data-testid={'team-board-topic'}
- key={row.key}
- {...stylex.props(styles.row)}
- >
- <div {...stylex.props(styles.track)}>
- {row.runs.map((placed) => (
- <Bar
- agentId={lane.agentId}
- key={placed.run.id}
- now={now}
- placed={placed}
- title={title}
- />
- ))}
- <RowLabel row={row} title={title} />
- </div>
- </Flexbox>
- );
- })}
- {overflow > 0 && (
- <span {...sx(styles.meta, { paddingInlineStart: 0 })}>
- {t('team.lane.more', { count: overflow })}
- </span>
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ data-testid={'team-board-topic'}
+ key={row.key}
+ {...stylex.props(styles.row)}
+ >
+ <div {...stylex.props(styles.track)}>
+ {row.runs.map((placed) => (
+ <Bar
+ agentId={lane.agentId}
+ key={placed.run.id}
+ now={now}
+ placed={placed}
+ title={title}
+ />
+ ))}
+ <RowLabel agentId={lane.agentId} row={row} title={title} />
+ </div>
+ </Flexbox>
+ );
+ })}
+ {!collapsed && overflow > 0 && (
+ <button
+ data-testid={'team-board-lane-more'}
+ type={'button'}
+ {...stylex.props(styles.moreButton)}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ {expanded ? t('team.lane.showLess') : t('team.lane.more', { count: overflow })}
+ </button>
)}
</div>
);
@@ -266,7 +404,7 @@ const Timeline = ({ board }: { board: AgentRunBoardData }) => {
const { t } = useTranslation('home');
const { generatedAt, hiddenLaneCount, lanes, windowStart } = board;
const ticks = buildAxisTicks(windowStart, generatedAt);
- const tickPercent = (index: number) => `${(index / (ticks.length - 1)) * 100}%`;
+ const tickPercent = (index: number) => `${axisPercent(ticks[index], windowStart, generatedAt)}%`;
return (
<div {...stylex.props(styles.card)}>
@@ -274,12 +412,9 @@ const Timeline = ({ board }: { board: AgentRunBoardData }) => {
{ticks.map((tick, index) => (
<span
key={tick.getTime()}
- {...sx(
- styles.tick,
- index === 0 && styles.tickStart,
- index === ticks.length - 1 && styles.tickEnd,
- { insetInlineStart: tickPercent(index) },
- )}
+ {...sx(styles.tick, index === 0 && styles.tickStart, {
+ insetInlineStart: tickPercent(index),
+ })}
>
{index === NOW_TICK_INDEX ? t('team.axis.now') : dayjs(tick).format('HH:mm')}
</span>
diff --git a/src/features/HomeTeamBoard/index.tsx b/src/features/HomeTeamBoard/index.tsx
index a944faef9cb..b2c3c801b9e 100644
--- a/src/features/HomeTeamBoard/index.tsx
+++ b/src/features/HomeTeamBoard/index.tsx
@@ -1,4 +1,4 @@
-import type { AgentRunBoardWindowHours } from '@lobechat/types';
+import type { AgentRunBoardScope, AgentRunBoardWindowHours } from '@lobechat/types';
import { Flexbox, Segmented, Skeleton } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
@@ -12,6 +12,7 @@ import { agentRunBoardService } from '@/services/agentRunBoard';
import ActivityPanel from './ActivityPanel';
import AttentionList from './AttentionList';
+import BoardFilters from './BoardFilters';
import DayCalendar from './DayCalendar';
import Timeline from './Timeline';
@@ -48,10 +49,19 @@ const HomeTeamBoard = () => {
const { t } = useTranslation('home');
const cacheScope = useCacheScope();
const [windowHours, setWindowHours] = useState<AgentRunBoardWindowHours>(1);
+ const [scope, setScope] = useState<AgentRunBoardScope>('all');
+ const [agentId, setAgentId] = useState<string>();
+ const [userId, setUserId] = useState<string>();
+
+ // The options depend on the scope and window, so a pick may not exist in the next one.
+ const clearPicks = () => {
+ setAgentId(undefined);
+ setUserId(undefined);
+ };
const { data, error, mutate } = useClientPollingSWR(
- ['agentRunBoard', cacheScope, windowHours],
- () => agentRunBoardService.get(windowHours),
+ ['agentRunBoard', cacheScope, windowHours, scope, agentId, userId],
+ () => agentRunBoardService.get({ agentId, scope, userId, windowHours }),
{
// The polling default dedupes for 30s, which would swallow every other tick.
dedupingInterval: POLL_INTERVAL / 2,
@@ -73,20 +83,48 @@ const HomeTeamBoard = () => {
activity={data.activity}
summary={data.summary}
action={
- <Segmented
- size={'small'}
- value={String(windowHours)}
- options={WINDOW_OPTIONS.map((value) => ({
- label: t('team.window', { count: value }),
- value: String(value),
- }))}
- onChange={(value) => setWindowHours(Number(value) as AgentRunBoardWindowHours)}
- />
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ <Segmented
+ size={'small'}
+ value={scope}
+ options={[
+ { label: t('team.scope.all'), value: 'all' },
+ { label: t('team.scope.involved'), value: 'involved' },
+ ]}
+ onChange={(value) => {
+ setScope(value as AgentRunBoardScope);
+ clearPicks();
+ }}
+ />
+ <Segmented
+ size={'small'}
+ value={String(windowHours)}
+ options={WINDOW_OPTIONS.map((value) => ({
+ label: t('team.window', { count: value }),
+ value: String(value),
+ }))}
+ onChange={(value) => {
+ setWindowHours(Number(value) as AgentRunBoardWindowHours);
+ clearPicks();
+ }}
+ />
+ </Flexbox>
}
/>
+ <BoardFilters
+ agentId={agentId}
+ options={data.filterOptions}
+ userId={userId}
+ onAgentChange={setAgentId}
+ onUserChange={setUserId}
+ />
<div {...stylex.props(styles.columns)}>
{!data.lanes?.length ? (
- <div {...stylex.props(styles.empty)}>{t('team.empty', { count: windowHours })}</div>
+ <div {...stylex.props(styles.empty)}>
+ {t(scope === 'involved' ? 'team.emptyInvolved' : 'team.empty', {
+ count: windowHours,
+ })}
+ </div>
) : windowHours === 24 ? (
<DayCalendar board={data} />
) : (
diff --git a/src/features/HomeTeamBoard/layout.test.ts b/src/features/HomeTeamBoard/layout.test.ts
index 6469b1d9313..ffadf1f18f0 100644
--- a/src/features/HomeTeamBoard/layout.test.ts
+++ b/src/features/HomeTeamBoard/layout.test.ts
@@ -2,6 +2,7 @@ import type { AgentRunBoardRun } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import {
+ axisPercent,
buildAxisTicks,
buildHourCells,
extendActivityWithFuture,
@@ -41,14 +42,15 @@ describe('layoutLaneTopics', () => {
it('positions a run as percentages and extends a live run to the end', () => {
const { rows } = layoutLaneTopics([run('a', 30, null)], start, end);
- expect(rows[0].runs[0]).toMatchObject({ left: 40, width: 40 });
+ expect(rows[0].runs[0].left).toBeCloseTo(45);
+ expect(rows[0].runs[0].width).toBeCloseTo(45);
});
it('clamps a run that began before the window', () => {
const { rows } = layoutLaneTopics([run('a', -30, 6)], start, end);
expect(rows[0].runs[0].left).toBe(0);
- expect(rows[0].runs[0].width).toBe(8);
+ expect(rows[0].runs[0].width).toBeCloseTo(9);
});
it('gives concurrent topics their own rows and lines up turns of one topic', () => {
@@ -95,14 +97,22 @@ describe('layoutLaneTopics', () => {
expect(layout.overflow).toBe(2);
});
- it('splits a waiting run at the moment it asked', () => {
+ it('shows every topic once expanded, still reporting the overflow', () => {
+ const runs = Array.from({ length: 7 }, (_, i) => run(`r${i}`, i, i + 1));
+ const layout = layoutLaneTopics(runs, start, end, { expanded: true });
+
+ expect(layout.rows).toHaveLength(7);
+ expect(layout.overflow).toBe(2);
+ });
+
+ it('ends a waiting run at the moment it asked', () => {
const { rows } = layoutLaneTopics(
[run('a', 0, null, { status: 'needs_human', waitingSince: at(45) })],
start,
end,
);
- expect(rows[0].runs[0].runningShare).toBe(75);
+ expect(rows[0].runs[0].width).toBeCloseTo(67.5);
expect(rows[0].startedBy).toBe('u');
});
@@ -110,7 +120,7 @@ describe('layoutLaneTopics', () => {
const { rows } = layoutLaneTopics([run('a', 60, 60)], start, end);
expect(rows[0].runs[0].width).toBe(MIN_BAR_PERCENT);
- expect(rows[0].runs[0].left).toBe(80);
+ expect(rows[0].runs[0].left).toBeCloseTo(90);
});
});
@@ -118,7 +128,6 @@ describe('resolveRowLabel', () => {
const placed = (left: number, width: number) => ({
left,
run: run('a', 0, 1),
- runningShare: null,
width,
});
@@ -130,6 +139,12 @@ describe('resolveRowLabel', () => {
});
});
+ it('keeps a waiting row left of its wait mark, however early it starts', () => {
+ const waiting = { ...placed(10, 30), run: run('w', 0, null, { status: 'needs_human' }) };
+
+ expect(resolveRowLabel([waiting])).toEqual({ anchor: 'end', offset: 60, room: 40 });
+ });
+
it('hangs a late row back from its last bar, using the room on its left', () => {
expect(resolveRowLabel([placed(70, 5), placed(78, 2)])).toEqual({
anchor: 'end',
@@ -173,17 +188,18 @@ describe('buildHourCells', () => {
});
describe('buildAxisTicks', () => {
- it('puts the present at 4/5 of the axis', () => {
+ it('puts the present at 90% of the axis', () => {
const ticks = buildAxisTicks(start, end);
- expect(ticks).toHaveLength(6);
+ expect(ticks).toHaveLength(4);
+ expect(axisPercent(ticks[NOW_TICK_INDEX], start, end)).toBeCloseTo(90);
expect(ticks[0]).toEqual(start);
expect(ticks[NOW_TICK_INDEX]).toEqual(end);
});
});
describe('extendActivityWithFuture', () => {
- it('appends empty slices for the last 1/5 of the axis', () => {
+ it('appends empty slices after the present', () => {
const empty = { done: 0, failed: 0, needsHuman: 0, running: 0 };
const activity = Array.from({ length: 12 }, (_, i) => ({
...empty,
@@ -192,7 +208,7 @@ describe('extendActivityWithFuture', () => {
}));
const extended = extendActivityWithFuture(activity);
- expect(extended).toHaveLength(15);
+ expect(extended).toHaveLength(13);
expect(extended[12]).toEqual({ ...empty, startedAt: at(60) });
});
});
diff --git a/src/features/HomeTeamBoard/layout.ts b/src/features/HomeTeamBoard/layout.ts
index 410c229236c..79ac6d9280f 100644
--- a/src/features/HomeTeamBoard/layout.ts
+++ b/src/features/HomeTeamBoard/layout.ts
@@ -9,10 +9,9 @@ import type {
export const MIN_BAR_PERCENT = 0.8;
/** Past this an agent stops growing; the rest are counted. */
export const MAX_TOPIC_ROWS = 5;
-/** The window fills the first 4/5 of the axis; the rest is room for what comes next. */
-const FUTURE_RATIO = 1 / 4;
-const TICKS_PER_PAST = 4;
-const TICK_COUNT = 5;
+/** The window fills the first 90% of the axis; the rest is room for what comes next. */
+const FUTURE_RATIO = 1 / 9;
+const TICKS_PER_PAST = 3;
/** A title starting past this would run out of room, so it hangs left of its bar's end. */
const LABEL_FLIP_PERCENT = 55;
/** Which of the axis ticks is the present. */
@@ -30,8 +29,6 @@ export interface PlacedRun {
/** Inline-start offset, as a percentage of the time axis. */
left: number;
run: AgentRunBoardRun;
- /** For a run waiting on a person: how much of its bar, in %, it ran before asking. */
- runningShare: number | null;
width: number;
}
@@ -46,12 +43,12 @@ export interface TopicRow {
}
export interface LaneLayout {
- /** Topics that did not fit in {@link MAX_TOPIC_ROWS}. */
+ /** Topics beyond {@link MAX_TOPIC_ROWS}, whether or not the lane is expanded. */
overflow: number;
rows: TopicRow[];
}
-/** The present sits at 4/5 of the axis, leaving the rest for time still to come. */
+/** The present sits at 90% of the axis, leaving the rest for time still to come. */
export const resolveAxisEnd = (windowStart: Date, now: Date) =>
new Date(now.getTime() + (now.getTime() - windowStart.getTime()) * FUTURE_RATIO);
@@ -59,19 +56,13 @@ const toPercent = (time: number, start: number, end: number) =>
Math.min(100, Math.max(0, ((time - start) / (end - start)) * 100));
const placeRun = (run: AgentRunBoardRun, start: number, end: number, now: Date): PlacedRun => {
+ // A run waiting on a person stops at the moment it asked; the wait is a fixed mark there.
+ const barEnd = run.waitingSince ?? run.endedAt ?? now;
const from = toPercent(run.startedAt.getTime(), start, end);
- const to = toPercent((run.endedAt ?? now).getTime(), start, end);
+ const to = toPercent(barEnd.getTime(), start, end);
const width = Math.max(to - from, MIN_BAR_PERCENT);
- const left = Math.min(from, 100 - width);
- const waitingAt = run.waitingSince && toPercent(run.waitingSince.getTime(), start, end);
- return {
- left,
- run,
- runningShare:
- waitingAt === null ? null : Math.min(100, Math.max(0, ((waitingAt - left) / width) * 100)),
- width,
- };
+ return { left: Math.min(from, 100 - width), run, width };
};
const latestStart = (runs: PlacedRun[]) =>
@@ -87,6 +78,7 @@ export const layoutLaneTopics = (
runs: AgentRunBoardRun[],
windowStart: Date,
now: Date,
+ { expanded = false }: { expanded?: boolean } = {},
): LaneLayout => {
const start = windowStart.getTime();
const end = resolveAxisEnd(windowStart, now).getTime();
@@ -109,7 +101,7 @@ export const layoutLaneTopics = (
return {
overflow: Math.max(0, rows.length - MAX_TOPIC_ROWS),
- rows: rows.slice(0, MAX_TOPIC_ROWS),
+ rows: expanded ? rows : rows.slice(0, MAX_TOPIC_ROWS),
};
};
@@ -123,14 +115,15 @@ export interface RowLabelPlacement {
/**
* Where a topic's title sits along its row: from the first bar's start, or back
- * from the last bar's end when the row begins too late to fit it.
+ * from the last bar's end when the row begins too late to fit it or is waiting.
*/
export const resolveRowLabel = (runs: PlacedRun[]): RowLabelPlacement => {
const first = runs[0];
- if (first.left <= LABEL_FLIP_PERCENT)
+ const last = runs.at(-1)!;
+ // The wait mark sits right after a waiting bar's end, so its title must stop there.
+ if (first.left <= LABEL_FLIP_PERCENT && last.run.status !== 'needs_human')
return { anchor: 'start', offset: first.left, room: 100 - first.left };
- const last = runs.at(-1)!;
const end = last.left + last.width;
return { anchor: 'end', offset: 100 - end, room: end };
};
@@ -182,15 +175,19 @@ export const buildHourCells = (lanes: AgentRunBoardLane[], now: Date): HourCell[
return cells;
};
-/** Evenly spaced times along the axis, with the present at {@link NOW_TICK_INDEX}. */
+/** Where a time falls along the axis, as a percentage. */
+export const axisPercent = (time: Date, windowStart: Date, now: Date) =>
+ toPercent(time.getTime(), windowStart.getTime(), resolveAxisEnd(windowStart, now).getTime());
+
+/** Evenly spaced times up to the present, which is {@link NOW_TICK_INDEX}. */
export const buildAxisTicks = (windowStart: Date, now: Date): Date[] => {
const start = windowStart.getTime();
const step = (now.getTime() - start) / TICKS_PER_PAST;
- return Array.from({ length: TICK_COUNT + 1 }, (_, i) => new Date(start + step * i));
+ return Array.from({ length: TICKS_PER_PAST + 1 }, (_, i) => new Date(start + step * i));
};
-/** Empty slices after the present, so the chart shares the timeline's 4/5 axis. */
+/** Empty slices after the present, so the chart ends about where the timeline's present sits. */
export const extendActivityWithFuture = (
activity: AgentRunBoardActivityBucket[],
): AgentRunBoardActivityBucket[] => {
diff --git a/src/services/agentRunBoard.ts b/src/services/agentRunBoard.ts
index 89dd21557cb..d27a5890b96 100644
--- a/src/services/agentRunBoard.ts
+++ b/src/services/agentRunBoard.ts
@@ -1,10 +1,17 @@
-import type { AgentRunBoardWindowHours } from '@lobechat/types';
+import type { AgentRunBoardScope, AgentRunBoardWindowHours } from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
+export interface AgentRunBoardQuery {
+ agentId?: string;
+ scope: AgentRunBoardScope;
+ userId?: string;
+ windowHours: AgentRunBoardWindowHours;
+}
+
class AgentRunBoardService {
- get = async (windowHours: AgentRunBoardWindowHours) => {
- const { data } = await lambdaClient.agentRunBoard.get.query({ windowHours });
+ get = async (query: AgentRunBoardQuery) => {
+ const { data } = await lambdaClient.agentRunBoard.get.query(query);
return data;
};
}