Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/sessions/SessionView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import { Button, ButtonLink, buttonClass, Skeleton } from "../shell/ui";
import styles from "./sessions.module.css";
import { HarnessIcon } from "./harness-icon";
import { GroupBadge } from "./group-badge";
import { WorkspaceViewSlot } from "../shell/view-slots";
import { SignedOut } from "../api/client";
import { useLoad } from "./use-load";
Expand Down Expand Up @@ -553,6 +554,7 @@ export function SessionView({
<HarnessIcon source={source} className="size-4" fallback={false} />
{harnessName(source)}
</span>
<GroupBadge group={data.catalog?.group ?? null} />
</div>
</div>
<div className="flex items-start gap-2">
Expand Down
23 changes: 20 additions & 3 deletions src/sessions/SessionsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
Copy,
CirclePause,
FolderGit2,
Tag,
Inbox,
Network,
RefreshCw,
Expand Down Expand Up @@ -81,6 +82,7 @@ import { Button, buttonClass, Skeleton } from "../shell/ui";
import { WorkspaceViewSlot } from "../shell/view-slots";
import styles from "./sessions.module.css";
import { HarnessIcon } from "./harness-icon";
import { GroupBadge } from "./group-badge";
import { SessionSearch } from "./SessionSearch";

// Hosted session-table-data.ts: status dot colors and harness icons.
Expand Down Expand Up @@ -366,7 +368,7 @@ function SidebarFilters({
// Each option's count once per change of rows, query, or clock.
const counts = useMemo(() => {
const totals = new Map<string, number>();
const fields = ["person", "is", "harness", "project"];
const fields = ["person", "is", "harness", "project", "group"];
for (const field of fields) {
const values = [
null,
Expand Down Expand Up @@ -481,6 +483,19 @@ function SidebarFilters({
icon: <FolderGit2 aria-hidden="true" />,
})),
)}
{/* Only when relaygate labels some loaded session's group. */}
{of("group").length > 0 &&
section(
"group",
"Group",
"All groups",
Tag,
of("group").map((item) => ({
value: item.value,
title: item.title,
icon: <Tag aria-hidden="true" />,
})),
)}
</div>
</WorkspaceViewSlot>
);
Expand Down Expand Up @@ -1045,9 +1060,11 @@ function SessionList({
</span>
</span>
</a>
{(row.parentSessionIds.length > 0 ||
{(row.group ||
row.parentSessionIds.length > 0 ||
row.childSessionCount > 0) && (
<span className="relative z-10 mt-1 flex gap-2 text-xs text-muted-foreground">
<span className="relative z-10 mt-1 flex items-center gap-2 text-xs text-muted-foreground">
<GroupBadge group={row.group} className="px-2 py-0 text-[10px]" />
{row.parentSessionIds.length > 0 && <span>Subagent</span>}
{row.childSessionCount > 0 && (
<span>
Expand Down
6 changes: 5 additions & 1 deletion src/sessions/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { z } from "zod";
import { read, ReadError, SignedOut } from "../api/client";
import { sessionAgentNamesEnabled, sessionShortSummariesEnabled } from "../app-path";
import { markAgentFilterNotReady } from "./agent-readiness";
import { harnessSources, sessionRow, tools, type Member, type SessionRow } from "./data";
import { harnessSources, sessionGroup, sessionRow, tools, type Member, type SessionGroup, type SessionRow } from "./data";
import {
fromDirectCursor,
ReadApiUnavailable,
Expand Down Expand Up @@ -513,6 +513,8 @@ export type SessionCatalog = {
children: SessionEdge[];
commitLinks: Record<string, unknown>[];
truncated: boolean;
/** The owning relaygate group's label, when there is one. */
group: SessionGroup | null;
};

function edge(value: Record<string, unknown>): SessionEdge | null {
Expand Down Expand Up @@ -543,6 +545,7 @@ export async function sessionCatalog(
children: z.array(record),
commitLinks: z.array(record).default([]),
truncated: z.boolean().default(false),
relaygate: z.unknown().optional(),
})
.parse(
await read(
Expand All @@ -558,6 +561,7 @@ export async function sessionCatalog(
.filter((row): row is SessionEdge => !!row),
commitLinks: body.commitLinks,
truncated: body.truncated,
group: sessionGroup(body.relaygate),
};
}

Expand Down
20 changes: 20 additions & 0 deletions src/sessions/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,27 @@ export type SessionRow = {
totalInputTokens: number | null;
totalOutputTokens: number | null;
search: { snippet: string | null; matchedBy: string[] } | null;
/** The owning relaygate group's label, when the deployment's policy gives it one. */
group: SessionGroup | null;
};

/**
* relaygate's label for a session's owning group (`relaygate: {gid, label}`,
* set only by relaygate from its `groupLabels` policy). Display only.
*/
export type SessionGroup = { gid: number; label: string };

const GROUP_LABEL = /^[A-Za-z0-9](?:[A-Za-z0-9 ._-]{0,22}[A-Za-z0-9._-])?$/;

export function sessionGroup(value: unknown): SessionGroup | null {
if (!isRecord(value)) return null;
const { gid, label } = value;
return typeof gid === "number" && Number.isSafeInteger(gid) && gid >= 0 &&
typeof label === "string" && GROUP_LABEL.test(label)
? { gid, label }
: null;
}

// Colors are brand.css tokens, so they follow the light and dark themes.
export const tools: Record<string, { label: string; color: string }> = {
claude: { label: "Claude Code", color: "var(--harness-claude)" },
Expand Down Expand Up @@ -154,6 +173,7 @@ export function sessionRow(value: Record<string, unknown>): SessionRow {
search: search
? { snippet: text(search.snippet), matchedBy: strings(search.matchedBy) }
: null,
group: sessionGroup(value.relaygate),
};
}

Expand Down
90 changes: 90 additions & 0 deletions src/sessions/group-badge.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { sessionGroup, sessionRow } from "./data";
import { matchesSessionFilters, matchesSuggestionFragment, sessionSuggestions } from "./query";
import { SessionView } from "./SessionView";
import { SessionsPage } from "./SessionsPage";

const base = { source: "codex", firstTs: "2026-11-10T10:00:00Z", lastTs: "2026-11-10T11:00:00Z", userIds: [], machineIds: [], eventCount: 1 };
const pit = { ...base, sessionId: "pit-session-1", relaygate: { gid: 22, label: "pit" } };
const plain = { ...base, sessionId: "plain-session-1" };
const empty = { items: [], members: [], nextCursor: null, error: false };

function route(catalog: Record<string, unknown> = {}) {
vi.stubGlobal("fetch", vi.fn(async (input: string | URL) => {
const url = new URL(String(input), "https://example.test");
if (url.pathname.endsWith("/sessions/activity")) return Response.json({ days: [] });
if (url.pathname.endsWith("/sessions/output")) return Response.json({ output: null, unsupported: true });
if (url.pathname.endsWith("/turns")) return Response.json({ turns: [], nextCursor: null });
if (url.pathname.endsWith("/timing")) return Response.json({ timing: null });
if (url.pathname.endsWith("/summary")) return Response.json({ summary: { status: "unsupported" } });
if (url.pathname.endsWith("/catalog"))
return Response.json({ catalog: null, parents: [], children: [], commitLinks: [], truncated: false, ...catalog });
if (url.pathname.endsWith("/sessions")) return Response.json({ ...empty, items: [pit, plain] });
if (url.pathname.includes("/sessions/")) return Response.json({ ...empty, events: [] });
return Response.json({ error: "not_found" }, { status: 404 });
}));
}

beforeEach(() => {
window.__AGENT_RELAY_DASHBOARD_CONFIG__ = { sessionReadApi: false };
window.history.replaceState(null, "", "/");
});
afterEach(() => { vi.unstubAllGlobals(); delete window.__AGENT_RELAY_DASHBOARD_CONFIG__; });

it("reads only a well-formed relaygate group label", () => {
expect(sessionRow(pit).group).toEqual({ gid: 22, label: "pit" });
expect(sessionRow(plain).group).toBeNull();
for (const bad of [null, "pit", { gid: "22", label: "pit" }, { gid: -1, label: "pit" }, { gid: 22, label: "" }, { gid: 22, label: "<b>pit</b>" }, { gid: 22, label: "x".repeat(25) }]) {
expect(sessionGroup(bad)).toBeNull();
}
});

it("filters rows by group: and offers only labels present on loaded rows", () => {
const rows = [sessionRow(pit), sessionRow(plain)];
const now = Date.parse("2026-11-16T00:00:00Z");
expect(rows.filter((row) => matchesSessionFilters(row, "group:PIT", now)).map((row) => row.sessionId)).toEqual(["pit-session-1"]);
expect(rows.filter((row) => matchesSessionFilters(row, "-group:pit", now)).map((row) => row.sessionId)).toEqual(["plain-session-1"]);
expect(sessionSuggestions(rows, [], now).filter((s) => s.field === "group")).toEqual([{ field: "group", value: "pit", title: "pit", section: "Groups" }]);
expect(sessionSuggestions([sessionRow(plain)], [], now).some((s) => s.field === "group")).toBe(false);
});

it("completes a multiword group label from an unquoted prefix", () => {
const team = { field: "group", value: "Team Alpha", title: "Team Alpha", section: "Groups" };
expect(matchesSuggestionFragment(team, "group:Tea")).toBe(true);
expect(matchesSuggestionFragment(team, "group:pit")).toBe(false);
expect(matchesSuggestionFragment(team, "harness:Tea")).toBe(false);
});

it("badges labeled rows in the session list and filters by group from the sidebar", async () => {
route();
render(<SessionsPage workspaceId="fake-workspace" initialQuery="" tab="sessions" onSignedOut={() => undefined} />);
const row = (await screen.findByRole("link", { name: /pit-session-1/ })).closest("tr")!;
expect(within(row).getByLabelText("Group: pit")).toHaveTextContent("pit");
const other = screen.getByRole("link", { name: /plain-session-1/ }).closest("tr")!;
expect(within(other).queryByLabelText(/^Group:/)).not.toBeInTheDocument();
fireEvent.click(within(screen.getByRole("group", { name: "Filter by group" })).getByRole("button", { name: "pit" }));
await waitFor(() => expect(screen.queryByRole("link", { name: /plain-session-1/ })).not.toBeInTheDocument());
expect(screen.getByRole("link", { name: /pit-session-1/ })).toBeVisible();
});

it("hides the group filter when no session has a label", async () => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ...empty, items: [plain], days: [] })));
render(<SessionsPage workspaceId="fake-workspace" initialQuery="" tab="sessions" onSignedOut={() => undefined} />);
await screen.findByRole("link", { name: /plain-session-1/ });
expect(screen.queryByRole("group", { name: "Filter by group" })).not.toBeInTheDocument();
});

it("badges the session header from the catalog's relaygate label", async () => {
route({ relaygate: { gid: 22, label: "pit" } });
render(<SessionView workspaceId="w" sessionId="pit-session-1" source="codex" event={null} />);
const identity = await screen.findByRole("group", { name: "Session identity" });
expect(within(identity).getByLabelText("Group: pit")).toHaveTextContent("pit");
});

it("shows no header badge without a label", async () => {
route();
render(<SessionView workspaceId="w" sessionId="plain-session-1" source="codex" event={null} />);
const identity = await screen.findByRole("group", { name: "Session identity" });
expect(within(identity).queryByLabelText(/^Group:/)).not.toBeInTheDocument();
});
20 changes: 20 additions & 0 deletions src/sessions/group-badge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Badge } from "../shell/ui";
import type { SessionGroup } from "./data";

/**
* The owning relaygate group's label (for example "pit"), from the
* deployment's policy. Display only: it says which group owns the session.
*/
export function GroupBadge({ group, className }: { group: SessionGroup | null; className?: string }) {
if (!group) return null;
return (
<Badge
variant="info"
className={className}
title={`Owned by the ${group.label} group`}
aria-label={`Group: ${group.label}`}
>
{group.label}
</Badge>
);
}
24 changes: 20 additions & 4 deletions src/sessions/query.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Search tokens, ported from the hosted dashboard's session-query.ts:
// `harness:`, `project:`, `is:`, `person:`, `updated:`, `created:`, with a
// `harness:`, `project:`, `is:`, `person:`, `updated:`, `created:` (and
// `group:`, a relaygate group label), with a
// leading `-` to negate. Free text goes to RelayHistory; tokens filter rows.
import type { ListFilters } from "./api";
import {
Expand Down Expand Up @@ -60,7 +61,7 @@ export function parseSessionQuery(query: string, { agents = true }: QueryOptions
continue;
}
const match = raw.match(
/^(-?)(harness|project|is|person|updated|created):(.*)$/i,
/^(-?)(harness|project|is|person|updated|created|group):(.*)$/i,
);
if (!match) {
words.push(raw);
Expand Down Expand Up @@ -158,6 +159,9 @@ export function matchesSessionFilters(
case "created":
matches = compareDate(row.firstTs, value);
break;
case "group":
matches = row.group?.label.toLowerCase() === v;
break;
}
// An incomplete date is still being typed; don't hide rows for it.
if (matches === null) return true;
Expand All @@ -175,13 +179,16 @@ export type SearchSuggestion = {
export const suggestionToken = (s: SearchSuggestion) =>
`${s.field}:${/\s/.test(s.value) ? JSON.stringify(s.value) : s.value}`;

/** Selfhost stores IDs while showing project/person labels in the picker. */
/**
* Selfhost stores IDs while showing project/person labels in the picker; a
* group label with a space is quoted in its token, so match its parsed value.
*/
export function matchesSuggestionFragment(
suggestion: SearchSuggestion,
fragment: string,
) {
const partial = parseSessionQuery(fragment).filters[0];
if (partial && (suggestion.field === "project" || suggestion.field === "person")) {
if (partial && (suggestion.field === "project" || suggestion.field === "person" || suggestion.field === "group")) {
return (
partial.field === suggestion.field && !partial.exclude &&
[suggestion.value, suggestion.title].some((value) =>
Expand Down Expand Up @@ -269,6 +276,15 @@ export function sessionSuggestions(
title,
section: "Projects",
})),
// Only labels relaygate put on loaded rows; no group is offered otherwise.
...[...new Set(rows.flatMap((row) => (row.group ? [row.group.label] : [])))]
.sort((a, b) => a.localeCompare(b))
.map((label) => ({
field: "group",
value: label,
title: label,
section: "Groups",
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
Comment thread
khaliqgant marked this conversation as resolved.
Resolved
})),
...members.map((member) => ({
field: "person",
value: member.id,
Expand Down
Loading