Skip to content

An open-source, faster Devin alternative

TypeScript

feat(sessions): labels, filtered paged listing, and list rows on the public surface

Igor Zalutski6b9fb92a60f6
diff --git a/cli/src/api.ts b/cli/src/api.ts
index bd09d6a3..5b18fc95 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -235,6 +235,32 @@ export interface ManagedSessionSnapshot {
}>;
}
+/** One row of `GET /sessions` (docs/agents/api.mdx, "Get and list"): no turns. */
+export interface ManagedSessionSummary {
+ id: string;
+ projectId: string;
+ agentId: string;
+ deploymentId: string;
+ environment: "development" | "production" | null;
+ source: string;
+ status: string;
+ labels: Record<string, string>;
+ createdAt: string;
+ updatedAt: string;
+ revision: number;
+ activity: {
+ activeTurnId: string | null;
+ queued: number;
+ lastSettledTurn: { id: string; status: string; at: string } | null;
+ };
+ result: { turnId: string; callId: string; reportedAt: string; data: unknown } | null;
+}
+
+export interface ManagedSessionPage {
+ sessions: ManagedSessionSummary[];
+ nextCursor: string | null;
+}
+
export type MemoryEnvironment = "development" | "production";
export type MemoryWriter =
@@ -1008,11 +1034,13 @@ export class OpenComputerClient {
return { created: response.status === 201, ...body };
}
- async sessions(): Promise<ManagedSessionSnapshot[]> {
- const result = await this.request<{
- sessions: ManagedSessionSnapshot[];
- }>("/api/managed-agents/sessions");
- return result.sessions;
+ /** One page of session rows, newest created first; pass `cursor` for the next page. */
+ async sessions(options: { cursor?: string; limit?: number } = {}): Promise<ManagedSessionPage> {
+ const query = new URLSearchParams();
+ if (options.cursor) query.set("cursor", options.cursor);
+ if (options.limit) query.set("limit", String(options.limit));
+ const suffix = query.size ? `?${query.toString()}` : "";
+ return this.request<ManagedSessionPage>(`/api/managed-agents/sessions${suffix}`);
}
session(sessionId: string) {
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index cb8d7f73..11e9c8c1 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -3,6 +3,7 @@ import {
type ManagedAgentEvent,
type ManagedAgentLog,
type ManagedSessionSnapshot,
+ type ManagedSessionSummary,
type MemoryBindings,
type MemoryDocument,
type MemoryDocumentMeta,
@@ -264,13 +265,20 @@ async function requireAgentRoot(): Promise<string> {
return root;
}
-function printSession(session: ManagedSessionSnapshot): void {
+function printSession(session: ManagedSessionSnapshot | ManagedSessionSummary): void {
const deployment = session.deploymentId
? session.deploymentId.slice(session.deploymentId.lastIndexOf(":") + 1)
: "—";
+ const labels =
+ "labels" in session && Object.keys(session.labels).length
+ ? " " +
+ Object.entries(session.labels)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(",")
+ : "";
process.stdout.write(
`${session.id} ${session.status.padEnd(15)} ` +
- `${session.agentId ?? "—"} ${deployment.slice(0, 12)}\n`,
+ `${session.agentId ?? "—"} ${deployment.slice(0, 12)}${labels}\n`,
);
}
@@ -1957,12 +1965,20 @@ export async function runCommand(
const session = parseSessionCommand(args);
const sessionArgs = session.args;
if (session.action === "list") {
+ const cursor = option(sessionArgs, "--cursor");
if (sessionArgs.length)
throw new Error(`Unexpected argument: ${sessionArgs[0]}`);
- const sessions = await client.sessions();
- if (globals.json) printJSON(sessions);
- else if (!sessions.length) process.stdout.write("No sessions.\n");
- else sessions.forEach(printSession);
+ // One page of rows, newest created first. The page carries the
+ // cursor of the next one; `--cursor` continues from it.
+ const page = await client.sessions(cursor ? { cursor } : {});
+ if (globals.json) printJSON(page);
+ else if (!page.sessions.length) process.stdout.write("No sessions.\n");
+ else {
+ page.sessions.forEach(printSession);
+ if (page.nextCursor) {
+ process.stdout.write(`More: --cursor ${page.nextCursor}\n`);
+ }
+ }
return;
}
if (session.action === "create") {
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 762e4092..519a78c8 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -1858,6 +1858,171 @@ describe("managed agents proxy", () => {
});
});
+ it("lists session rows with the query and cursor passed through and the owner's labels intact", async () => {
+ const fetchSpy = vi.fn(async () =>
+ Response.json({
+ sessions: [
+ {
+ id: "session-1",
+ projectId: "prj_test",
+ agentId: "reviewer",
+ deploymentId: "reviewer:digest",
+ environment: "development",
+ source: "api",
+ status: "idle",
+ labels: { repo: "acme/api", user_id: "u-42", task: "t-1" },
+ createdAt: "2026-09-15T00:00:00.000Z",
+ updatedAt: "2026-09-15T00:01:00.000Z",
+ revision: 7,
+ activity: {
+ activeTurnId: null,
+ queued: 0,
+ lastSettledTurn: { id: "turn-1", status: "completed", at: "2026-09-15T00:01:00.000Z" },
+ },
+ result: null,
+ accountId: "org_test",
+ runtimeId: "internal-runtime",
+ },
+ ],
+ nextCursor: "eyJjIjoxfQ",
+ }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/sessions?project=prj_test&label.repo=acme%2Fapi&limit=25&cursor=abc",
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(200);
+ const [target] = fetchSpy.mock.calls[0] as unknown as [URL];
+ expect(String(target)).toBe(
+ "https://managedagents.test/v1/sessions?project=prj_test&label.repo=acme%2Fapi&limit=25&cursor=abc",
+ );
+ const body = (await response.json()) as {
+ sessions: Array<Record<string, unknown>>;
+ nextCursor: string | null;
+ };
+ expect(body.nextCursor).toBe("eyJjIjoxfQ");
+ expect(body.sessions).toEqual([
+ {
+ id: "session-1",
+ projectId: "prj_test",
+ agentId: "reviewer",
+ deploymentId: "reviewer:digest",
+ environment: "development",
+ source: "api",
+ status: "idle",
+ labels: { repo: "acme/api", user_id: "u-42", task: "t-1" },
+ createdAt: "2026-09-15T00:00:00.000Z",
+ updatedAt: "2026-09-15T00:01:00.000Z",
+ revision: 7,
+ activity: {
+ activeTurnId: null,
+ queued: 0,
+ lastSettledTurn: { id: "turn-1", status: "completed", at: "2026-09-15T00:01:00.000Z" },
+ },
+ result: null,
+ },
+ ]);
+ expect(JSON.stringify(body)).not.toMatch(/accountId|runtimeId|org_test|internal-runtime/);
+ });
+
+ it("patches session labels and returns the sanitized session with its labels", async () => {
+ const fetchSpy = vi.fn(async () =>
+ Response.json({
+ id: "session-1",
+ status: "idle",
+ executionMode: "workerd",
+ accountId: "org_test",
+ runtimeToken: "internal-runtime-token",
+ labels: { runtime_id: "kept", repo: "acme/api" },
+ labelsUpdatedAt: "2026-09-15T00:02:00.000Z",
+ revision: 8,
+ result: null,
+ turns: [],
+ }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/labels",
+ {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ set: { repo: "acme/api" }, unset: ["task"] }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+
+ expect(response.status).toBe(200);
+ const [target, init] = fetchSpy.mock.calls[0] as unknown as [URL, RequestInit];
+ expect(String(target)).toBe(
+ "https://managedagents.test/v1/sessions/session-1/labels",
+ );
+ expect(init.method).toBe("PATCH");
+ const body = (await response.json()) as Record<string, unknown>;
+ expect(body.labels).toEqual({ runtime_id: "kept", repo: "acme/api" });
+ expect(body.labelsUpdatedAt).toBe("2026-09-15T00:02:00.000Z");
+ expect(body.revision).toBe(8);
+ expect(body.result).toBeNull();
+ expect(JSON.stringify(body)).not.toMatch(/runtimeToken|accountId|org_test/);
+
+ const refused = await proxyManagedAgents(
+ new Request(
+ "https://app.opencomputer.dev/api/managed-agents/sessions/session-1/labels",
+ { method: "PUT", body: "{}" },
+ ),
+ { OC_MANAGED_AGENTS_SECRET: "test-secret" },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+ expect(refused.status).toBe(404);
+ });
+
+ it("passes invalid_labels and invalid_query through as typed client errors", async () => {
+ for (const [code, path, init] of [
+ ["invalid_query", "/sessions?unknown=1", undefined],
+ [
+ "invalid_labels",
+ "/sessions/session-1/labels",
+ { method: "PATCH", body: JSON.stringify({ set: { Bad: "x" } }) },
+ ],
+ ] as const) {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json(
+ { error: { code, message: "Label key \"Bad\" must match /internal-pattern/" } },
+ { status: 400 },
+ ),
+ ),
+ );
+ const response = await proxyManagedAgents(
+ new Request(`https://app.opencomputer.dev/api/managed-agents${path}`, init),
+ { OC_MANAGED_AGENTS_SECRET: "test-secret" },
+ { orgID: "org_test", userID: "user_test" },
+ "/api/managed-agents",
+ );
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toMatchObject({ error: { code } });
+ }
+ });
+
it("interrupts a session's running turn and returns the sanitized snapshot", async () => {
const fetchSpy = vi.fn(async () =>
Response.json({
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index b1fe813c..f02db5fa 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -737,12 +737,29 @@ function publicDelivery(value: unknown): Record<string, unknown> {
};
}
+/**
+ * Session labels are the owner's own strings under the owner's own keys.
+ * They are reattached after the private-key strip, which would otherwise
+ * drop a label the owner happened to call `user_id` or `runtime_id`.
+ */
+function ownerLabels(source: Record<string, unknown>): Record<string, string> {
+ const labels = record(source.labels) ?? {};
+ return Object.fromEntries(
+ Object.entries(labels).filter(
+ (entry): entry is [string, string] => typeof entry[1] === "string",
+ ),
+ );
+}
+
function publicSessionSnapshot(value: unknown): unknown {
+ const source = record(value);
const session = record(stripPrivateValues(value));
- if (!session || !Array.isArray(session.turns)) return session ?? value;
+ if (!session || !source) return session ?? value;
+ const labelled = "labels" in source ? { ...session, labels: ownerLabels(source) } : session;
+ if (!Array.isArray(labelled.turns)) return labelled;
return {
- ...session,
- turns: session.turns.map((entry) => {
+ ...labelled,
+ turns: labelled.turns.map((entry) => {
const turn = record(entry);
if (!turn || !Array.isArray(turn.deliveries)) return entry;
return { ...turn, deliveries: turn.deliveries.map(publicDelivery) };
@@ -750,6 +767,28 @@ function publicSessionSnapshot(value: unknown): unknown {
};
}
+/** One list row as documented: nothing private is in it, and the labels are the owner's. */
+function publicSessionSummary(value: unknown): unknown {
+ const source = record(value);
+ const row = record(stripPrivateValues(value));
+ if (!row || !source) return row ?? value;
+ return {
+ id: row.id,
+ projectId: row.projectId,
+ agentId: row.agentId,
+ deploymentId: row.deploymentId,
+ environment: row.environment ?? null,
+ source: row.source,
+ status: row.status,
+ labels: ownerLabels(source),
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt,
+ revision: row.revision,
+ activity: row.activity,
+ result: source.result ?? null,
+ };
+}
+
const PRIVATE_EVENT_KEYS = new Set([
"accountId",
"account_id",
@@ -1377,14 +1416,15 @@ function publicSuccessBody(
}
if (method === "GET" && suffix === "/sessions") {
return {
- ...(record(stripPrivateValues(body)) ?? {}),
sessions: Array.isArray(body.sessions)
- ? body.sessions.map(publicSessionSnapshot)
+ ? body.sessions.map(publicSessionSummary)
: [],
+ nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null,
};
}
if (
(method === "GET" && /^\/sessions\/[^/]+$/.test(suffix)) ||
+ (method === "PATCH" && /^\/sessions\/[^/]+\/labels$/.test(suffix)) ||
(method === "POST" &&
/^\/sessions\/[^/]+\/(resume|end|terminate|interrupt)$/.test(suffix))
) {
@@ -1704,6 +1744,9 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {
if (method === "GET" && suffix === "/sessions") return true;
if (method === "GET" && suffix === "/billing/sessions") return true;
if (method === "GET" && /^\/sessions\/[^/]+$/.test(suffix)) return true;
+ if (method === "PATCH" && /^\/sessions\/[^/]+\/labels$/.test(suffix)) {
+ return true;
+ }
if (method === "GET" && /^\/sessions\/[^/]+\/events$/.test(suffix)) {
return true;
}
diff --git a/docs/agents/api.mdx b/docs/agents/api.mdx
index 30f95856..2901c3c0 100644
--- a/docs/agents/api.mdx
+++ b/docs/agents/api.mdx
@@ -49,7 +49,8 @@ deployment it was created on; see [Sessions and turns](/agents/sessions).
| --- | --- | --- |
| Create | `POST /sessions` | `201` with the session, `200` when the key had already created it |
| Get | `GET /sessions/<id>` | `200` with the session |
-| List | `GET /sessions` | `200` with `{ sessions }` |
+| List | `GET /sessions` | `200` with `{ sessions, nextCursor }`: one page of rows |
+| Labels | `PATCH /sessions/<id>/labels` | `200` with the session |
| End | `POST /sessions/<id>/end` | `200` with the ended session |
| Interrupt | `POST /sessions/<id>/interrupt` | `200` with the session |
@@ -62,6 +63,7 @@ curl -X POST 'https://app.opencomputer.dev/api/managed-agents/sessions' \
-H 'Idempotency-Key: topic/workshop/1' \
-d '{
"agentId": "<agent-id>@development",
+ "labels": { "topic": "workshop", "requested_by": "u-42" },
"memory": {
"notes": { "scope": "document", "id": "workshop", "access": "read-write" }
}
@@ -75,6 +77,7 @@ curl -X POST 'https://app.opencomputer.dev/api/managed-agents/sessions' \
| `environment` | `development` or `production`. Optional with `agentId`; it must agree with the alias. |
| `memory` | Bindings keyed by resource ID, at most eight. Needs a deployed agent and an environment. Shapes on [Document memory](/agents/document-memory#session-bindings). |
| `source` | `api` (default), `playground`, `channel` or `webhook`. The dashboard groups sessions by it. |
+| `labels` | Your own metadata on the session, an object of strings; see [Labels](#labels). Applied at creation and ignored on a replay of the same `Idempotency-Key`. |
The response is `{ session: { id, executionMode, status, createdAt }, deployment }`.
The session starts without a turn; send one with the turns route.
@@ -92,8 +95,8 @@ identifies the session within your organization:
confirmed in time. Retry with the same key; the retry resumes the wait.
Other codes: `400 invalid_environment`, `400 invalid_memory_binding`,
-`404 deployment_not_found`, `409 deployment_not_promoted` (a pinned
-deployment is not active in the named environment), `402
+`400 invalid_labels`, `404 deployment_not_found`, `409 deployment_not_promoted`
+(a pinned deployment is not active in the named environment), `402
insufficient_credits`.
### Get and list
@@ -103,16 +106,75 @@ insufficient_credits`.
| Field | Meaning |
| --- | --- |
| `id`, `agentId`, `deploymentId` | The session and the deployment it pins |
+| `projectId` | The project the agent belongs to |
| `environment` | `development` or `production`, when the request named one |
| `status` | `new`, `connecting`, `idle`, `running`, `waiting_runtime`, `suspending`, `suspended`, `resuming`, `failed` or `ended` |
| `source` | The `source` given at creation |
+| `labels`, `labelsUpdatedAt` | Your metadata, and when it last changed; see [Labels](#labels) |
| `memory` | Bindings with `resource`, `scope`, `id`, `access` and `writable`; present when the session was created with bindings |
| `turns` | Every turn: `id`, `input`, `mode`, `status`, `createdAt`, `updatedAt`, and `deliveries` when an [event subscription](#event-subscriptions) selected its outcome |
+| `result` | The latest committed output of the agent's result tool, `{ turnId, callId, reportedAt, data }`, or `null` when no turn has reported one |
+| `revision` | A counter that increases with every change to the session's status, turns, labels or result |
| `createdAt`, `updatedAt` | Timestamps |
-`GET /sessions` returns `{ sessions }`: the fifty most recently updated
-sessions of the organization, newest first, in the same shape. There are no
-filters or paging parameters; keep your own index of session IDs.
+`GET /sessions` returns one page of rows, `{ sessions, nextCursor }`, filtered
+by the query:
+
+```bash
+curl 'https://app.opencomputer.dev/api/managed-agents/sessions?project=<project-id>&environment=development&label.topic=workshop&limit=50' \
+ -H 'x-api-key: <api-key>'
+```
+
+| Parameter | Meaning |
+| --- | --- |
+| `project` | A project id or slug |
+| `environment` | `development` or `production` |
+| `agent` | An agent id |
+| `status` | One session status |
+| `label.<key>=<value>` | Sessions whose label `<key>` equals `<value>` exactly; at most three |
+| `limit` | Rows per page, 1 to 100; default 50 |
+| `cursor` | The `nextCursor` of the previous page |
+
+Any other parameter is `400 invalid_query`, as is a malformed value. A
+project-scoped key lists its own project; naming another is
+`403 project_scope_violation`.
+
+A row is `id`, `projectId`, `agentId`, `deploymentId`, `environment` (`null`
+when the session has none), `source`, `status`, `labels`, `createdAt`,
+`updatedAt`, `revision`, `activity` and `result`. `activity` is
+`{ activeTurnId, queued, lastSettledTurn }`: the running turn's id or `null`,
+how many turns wait behind it, and the most recently finished turn as
+`{ id, status, at }` or `null`. Rows carry no `turns` and no `memory`; read
+`GET /sessions/<id>` for those.
+
+Rows are ordered by `createdAt`, newest first, then by `id`, and the order
+never changes: a session that is updated does not move, so a traversal with
+`cursor` sees every row exactly once even while sessions are running. To show
+recent activity first, sort the page you hold by `updatedAt`. `nextCursor` is
+`null` on the last page. A session appears in the list as soon as its create
+call has returned.
+
+### Labels
+
+Labels are your own metadata on a session: at most 16 keys, each matching
+`^[a-z][a-z0-9_.-]{0,63}$`, each value at most 256 characters, 4 KB in all.
+They filter the list and appear on the session and its row. They are not
+permissions, are not searched beyond equality, and are never shown to the
+agent; give the agent its context in the turn input.
+
+`PATCH /sessions/<id>/labels` changes them and returns the session:
+
+```bash
+curl -X PATCH 'https://app.opencomputer.dev/api/managed-agents/sessions/<session-id>/labels' \
+ -H 'x-api-key: <api-key>' \
+ -H 'Content-Type: application/json' \
+ -d '{ "set": { "outcome": "merged" }, "unset": ["requested_by"] }'
+```
+
+`unset` removes keys, then `set` writes keys; each key takes the last write.
+The session's `labelsUpdatedAt` records the change. A patch that would exceed
+the bounds, or a key or value that does not fit them, is `400 invalid_labels`
+and changes nothing. Labels can be changed on an ended session.
### End and interrupt
diff --git a/docs/agents/sessions.mdx b/docs/agents/sessions.mdx
index d754c9e6..816ae133 100644
--- a/docs/agents/sessions.mdx
+++ b/docs/agents/sessions.mdx
@@ -28,6 +28,15 @@ inspected.
See [Playground and debugging](/agents/playground) for target selection and the
debug inspector.
+## Finding sessions
+
+Give a session labels when you create it, such as the ticket, repository or
+user it works for, and list sessions by project, environment, agent, status
+and label instead of keeping your own index of session ids. The list returns
+rows with the session's status, its current turn activity and its latest
+result; open a session for its turns and events. The query, the row shape and
+the label bounds are on the [API reference](/agents/api#get-and-list).
+
## CLI
Start a session against the development agent:
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index cbdce947..7dabf476 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -51,12 +51,14 @@ import {
getManagedAgentDeployment,
getManagedAgentDeployments,
getManagedAgentChannels,
+ getManagedAgentSession,
getManagedAgentSessionEvents,
getManagedAgents,
getManagedAgentSessions,
type ManagedAgentEvent,
type ManagedAgentInputMode,
type ManagedAgentSession,
+ type ManagedAgentSessionSummary,
type ManagedAgentSummary,
type ManagedProjectOverview,
} from './api'
@@ -106,6 +108,22 @@ function eventText(event: ManagedAgentEvent) {
return typeof event.data.text === 'string' ? event.data.text : ''
}
+/** What a list row says about its turns: running, waiting, or how the last one ended. */
+function sessionActivityLabel(session: ManagedAgentSessionSummary) {
+ const { activity } = session
+ const parts: string[] = []
+ if (activity.activeTurnId) parts.push('running')
+ if (activity.queued) parts.push(`${activity.queued} queued`)
+ if (!parts.length) {
+ parts.push(
+ activity.lastSettledTurn
+ ? `last ${activity.lastSettledTurn.status}`
+ : 'no turns yet',
+ )
+ }
+ return parts.join(' · ')
+}
+
function historicalMessages(
session: ManagedAgentSession | undefined,
events: ManagedAgentEvent[],
@@ -605,6 +623,13 @@ export default function ManagedAgentDetail({
enabled: Boolean(selectedPlaygroundId),
refetchInterval: 1_000,
})
+ // The list carries rows; the open session's turns come from its own route.
+ const selectedPlaygroundSession = useQuery({
+ queryKey: ['managed-agent-session', selectedPlaygroundId],
+ queryFn: () => getManagedAgentSession(selectedPlaygroundId!),
+ enabled: Boolean(selectedPlaygroundId),
+ refetchInterval: 5_000,
+ })
const continuationCommand =
project?.templateSource?.cloneReady &&
projectCloneCommand(project.project.id)
@@ -632,7 +657,7 @@ export default function ManagedAgentDetail({
const declaredChannels =
activeDeployment.data?.projectDeployment?.resources.channels ?? []
- const sessionColumns: Column<ManagedAgentSession>[] = [
+ const sessionColumns: Column<ManagedAgentSessionSummary>[] = [
{
key: 'session',
header: 'Session',
@@ -655,11 +680,22 @@ export default function ManagedAgentDetail({
cell: (session) => <StatusBadge status={session.status} />,
},
{
- key: 'turns',
- header: 'Turns',
+ key: 'activity',
+ header: 'Activity',
cell: (session) => (
<span className="text-muted-foreground text-xs">
- {session.turns.length}
+ {sessionActivityLabel(session)}
+ </span>
+ ),
+ },
+ {
+ key: 'labels',
+ header: 'Labels',
+ cell: (session) => (
+ <span className="text-muted-foreground truncate font-mono text-[10px]">
+ {Object.entries(session.labels)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(' ')}
</span>
),
},
@@ -931,11 +967,10 @@ export default function ManagedAgentDetail({
)}
>
<span className="block truncate text-xs font-medium">
- {session.turns[0]?.input || 'Playground session'}
+ Playground session
</span>
<span className="text-muted-foreground mt-0.5 block text-[10px]">
- {session.turns.length}{' '}
- {session.turns.length === 1 ? 'turn' : 'turns'} ·{' '}
+ {sessionActivityLabel(session)} ·{' '}
{formatDate(session.updatedAt)}
</span>
<span className="text-muted-foreground mt-0.5 block truncate font-mono text-[10px]">
@@ -947,7 +982,8 @@ export default function ManagedAgentDetail({
</aside>
{selectedPlaygroundId &&
selectedPlaygroundId !== adoptedPlaygroundId &&
- selectedPlaygroundEvents.isLoading ? (
+ (selectedPlaygroundEvents.isLoading ||
+ selectedPlaygroundSession.isLoading) ? (
<div className="text-muted-foreground flex min-h-0 items-center justify-center gap-2 text-sm">
<Loader2 className="size-4 animate-spin" /> Loading session…
</div>
@@ -956,7 +992,9 @@ export default function ManagedAgentDetail({
key={`${environment}:${playgroundChatId}`}
chatId={`${environment}:${playgroundChatId}`}
agentId={project ? `${agentId}@${environment}` : agentId}
- session={selectedPlayground}
+ session={
+ selectedPlaygroundId ? selectedPlaygroundSession.data : undefined
+ }
events={
selectedPlaygroundEvents.data ?? EMPTY_MANAGED_AGENT_EVENTS
}
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 4d834f11..c54a94f7 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -535,7 +535,49 @@ const sessionSchema = z.object({
.default([]),
})
-const sessionsResponseSchema = z.object({ sessions: z.array(sessionSchema) })
+// One list row (docs/agents/api.mdx, "Get and list"): no turns and no memory;
+// the session route keeps those. `activity` summarizes the turn work and
+// `result` is the agent's latest committed result tool output, when any.
+const sessionSummarySchema = z.object({
+ id: z.string(),
+ projectId: z.string(),
+ agentId: z.string(),
+ deploymentId: z.string(),
+ environment: z.enum(['development', 'production']).nullable().default(null),
+ source: z
+ .enum(['api', 'channel', 'playground', 'schedule', 'webhook'])
+ .optional()
+ .default('api'),
+ status: z.string(),
+ labels: z.record(z.string(), z.string()).default({}),
+ createdAt: z.string(),
+ updatedAt: z.string(),
+ revision: z.number(),
+ activity: z
+ .object({
+ activeTurnId: z.string().nullable().default(null),
+ queued: z.number().default(0),
+ lastSettledTurn: z
+ .object({ id: z.string(), status: z.string(), at: z.string() })
+ .nullable()
+ .default(null),
+ })
+ .default({ activeTurnId: null, queued: 0, lastSettledTurn: null }),
+ result: z
+ .object({
+ turnId: z.string(),
+ callId: z.string(),
+ reportedAt: z.string(),
+ data: z.unknown(),
+ })
+ .nullable()
+ .default(null),
+})
+
+const sessionsResponseSchema = z.object({
+ sessions: z.array(sessionSummarySchema),
+ nextCursor: z.string().nullable().default(null),
+})
// Project memory documents (docs/agents/document-memory.mdx, "Management API").
const memoryWriterSchema = z.union([
@@ -593,12 +635,11 @@ const projectOverviewSchema = z.object({
cloneReady: z.boolean().optional().default(false),
})
.optional(),
- sessions: z.array(sessionSchema),
+ sessions: z.array(sessionSummarySchema),
deployments: z.array(deploymentSchema),
connections: z.array(connectionSchema),
channels: z.array(channelSchema),
schedules: z.array(z.record(z.string(), z.unknown())),
- files: z.array(z.record(z.string(), z.unknown())),
schema: z.record(z.string(), z.unknown()),
})
@@ -610,6 +651,7 @@ export type ManagedAgentEvent = z.infer<typeof eventSchema>
export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>
export type ManagedAgentModelRoute = z.infer<typeof modelRouteSchema>
export type ManagedAgentSession = z.infer<typeof sessionSchema>
+export type ManagedAgentSessionSummary = z.infer<typeof sessionSummarySchema>
export type ManagedSessionMemoryBinding = ManagedAgentSession['memory'][number]
export type ManagedMemoryDeclaration = z.infer<typeof memoryDeclarationSchema>
export type ManagedMemoryDocumentMeta = z.infer<typeof memoryDocumentMetaSchema>
@@ -1245,15 +1287,20 @@ export async function getManagedAgentDeployments(agentId: string) {
).deployments
}
+/**
+ * The newest page of session rows, filtered by the API rather than here.
+ * Rows are ordered by creation time; one page of a hundred is what the
+ * agent view shows.
+ */
export async function getManagedAgentSessions(agentId?: string) {
+ const query = new URLSearchParams({ limit: '100' })
+ if (agentId) query.set('agent', agentId)
const { sessions } = await apiFetch(
- '/managed-agents/sessions',
+ `/managed-agents/sessions?${query.toString()}`,
undefined,
sessionsResponseSchema,
)
- return agentId
- ? sessions.filter((session) => session.agentId === agentId)
- : sessions
+ return sessions
}
export async function collectManagedAgentEventPages(
diff --git a/web/src/managed-agents/session-history.test.ts b/web/src/managed-agents/session-history.test.ts
index de5e96c8..58ea54b9 100644
--- a/web/src/managed-agents/session-history.test.ts
+++ b/web/src/managed-agents/session-history.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
import type {
ManagedAgentDeployment,
ManagedAgentEvent,
- ManagedAgentSession,
+ ManagedAgentSessionSummary,
} from './api'
import {
playgroundSessionIdFromSearch,
@@ -28,18 +28,21 @@ function deployment(
}
}
-function session(id: string, deploymentId: string): ManagedAgentSession {
+function session(id: string, deploymentId: string): ManagedAgentSessionSummary {
return {
id,
+ projectId: 'prj_test',
agentId: 'reviewer',
deploymentId,
- executionMode: 'microvm',
+ environment: 'development',
status: 'idle',
source: 'playground',
+ labels: {},
createdAt: '2026-08-15T00:00:00.000Z',
updatedAt: '2026-08-15T00:00:00.000Z',
- turns: [],
- memory: [],
+ revision: 1,
+ activity: { activeTurnId: null, queued: 0, lastSettledTurn: null },
+ result: null,
}
}
diff --git a/web/src/managed-agents/session-history.ts b/web/src/managed-agents/session-history.ts
index f7dd7172..5a59e133 100644
--- a/web/src/managed-agents/session-history.ts
+++ b/web/src/managed-agents/session-history.ts
@@ -5,12 +5,12 @@ import type {
} from './api'
import type { ProjectEnvironment } from './project-context'
-export function sessionsForEnvironment(
- sessions: ManagedAgentSession[],
+export function sessionsForEnvironment<T extends Pick<ManagedAgentSession, 'deploymentId'>>(
+ sessions: T[],
deployments: ManagedAgentDeployment[],
agentId: string,
environment: ProjectEnvironment,
-) {
+): T[] {
const deploymentIds = new Set(
deployments
.filter(