Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agent-session): fold the cached log from the GraphQL cache (comparison with #7150) (#7206)

Wolf Mermelsteina6de90d861a3
diff --git a/Cargo.lock b/Cargo.lock
index a3ba58d0ff..c5964aa0eb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4392,6 +4392,7 @@ name = "complete_graph"
version = "0.1.0"
dependencies = [
"activity",
+ "agent_session",
"anyhow",
"apollo-compiler",
"async-graphql",
@@ -4428,6 +4429,7 @@ dependencies = [
"rootcause",
"scheduled_action",
"serde",
+ "serde_json",
"soup",
"soup-filter-projection",
"soup_realtime",
diff --git a/apps/web/src/features/block-agent/context/create-agent-session.test.tsx b/apps/web/src/features/block-agent/context/create-agent-session.test.tsx
index 1a62d624c0..be8d21d87f 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session.test.tsx
+++ b/apps/web/src/features/block-agent/context/create-agent-session.test.tsx
@@ -17,9 +17,12 @@ const fold = vi.hoisted(() => ({
}));
const harness = vi.hoisted(() => ({
get: vi.fn(),
- getLog: vi.fn(),
control: vi.fn(),
}));
+const logSource = vi.hoisted(() => ({
+ cached: vi.fn(),
+ fetched: vi.fn(),
+}));
vi.mock('@core/agent-fold/client', () => fold);
vi.mock('@service-agent-harness/client', () => ({
@@ -28,6 +31,16 @@ vi.mock('@service-agent-harness/client', () => ({
vi.mock('@queries/agent-session/queue-sync', () => ({
subscribeSocketSessionStarted: () => () => {},
}));
+vi.mock('@queries/agent-session/log', () => ({
+ AgentSessionLogUnavailable: class extends Error {},
+ watchAgentSessionLog: () => ({
+ cached: logSource.cached(),
+ fetched: logSource.fetched(),
+ stop: () => {},
+ }),
+ appendAgentSessionLogRows: vi.fn(async () => undefined),
+ forgetAgentSessionLog: vi.fn(async () => undefined),
+}));
vi.mock('@queries/agent-session/session-metadata-sync', () => ({
subscribeAgentSessionRenamed: () => () => {},
subscribeAgentSessionUpdated: () => () => {},
@@ -76,10 +89,20 @@ beforeEach(() => {
metadata: { turn: 'idle' },
});
harness.get.mockResolvedValue(ok(session));
- harness.getLog.mockResolvedValue(ok({ bot, entries: [] }));
+ logSource.cached.mockResolvedValue(undefined);
+ logSource.fetched.mockResolvedValue({ bot, rows: [] });
});
afterEach(cleanup);
+/** A promise the test resolves by hand. */
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
describe('createAgentSession', () => {
it('shows the fallback while loading and the session once loaded', async () => {
mount();
@@ -88,13 +111,36 @@ describe('createAgentSession', () => {
});
it('leaves the fallback and reports a failed load', async () => {
- harness.getLog.mockResolvedValue(err([{ code: 'SERVER_ERROR' }]));
+ logSource.fetched.mockRejectedValue(new Error('server error'));
mount();
expect(await screen.findByText('load failed')).toBeTruthy();
expect(screen.queryByText('loading')).toBeNull();
expect(screen.getByText('untitled')).toBeTruthy();
});
+ it('shows the session from the cached log before the fetch answers', async () => {
+ logSource.cached.mockResolvedValue({ bot, rows: [] });
+ const log = deferred<{ bot: typeof bot; rows: never[] }>();
+ logSource.fetched.mockReturnValue(log.promise);
+
+ mount();
+ expect(await screen.findByText('A session')).toBeTruthy();
+ expect(screen.queryByText('loading')).toBeNull();
+ expect(log.promise).toBeDefined();
+
+ log.resolve({ bot, rows: [] });
+ expect(await screen.findByText('A session')).toBeTruthy();
+ });
+
+ it('reports a fetch that fails after the cached session is on screen', async () => {
+ logSource.cached.mockResolvedValue({ bot, rows: [] });
+ logSource.fetched.mockRejectedValue(new Error('server error'));
+
+ mount();
+ expect(await screen.findByText('load failed')).toBeTruthy();
+ expect(screen.getByText('untitled')).toBeTruthy();
+ });
+
it('tells a 401 on the session apart from a generic failure', async () => {
harness.get.mockResolvedValue(err([{ code: 'UNAUTHORIZED' }]));
mount();
diff --git a/apps/web/src/features/block-agent/context/create-agent-session.ts b/apps/web/src/features/block-agent/context/create-agent-session.ts
index 136ed224b5..e1ddd426d6 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts
@@ -11,6 +11,7 @@
import {
AgentSession,
AgentSessionAccessDenied,
+ type AgentSessionRecord,
type IssueResult,
} from '@core/agent-session/AgentSession';
import type { AgentSessionRenamedEvent } from '@queries/agent-session/realtime-protocol';
@@ -208,40 +209,88 @@ export function createAgentSession(
let latestRename: AgentSessionRenamedEvent | undefined;
let renameRefresh = 0;
+ /**
+ * The fetch failed after a cached transcript was already on screen. The
+ * resource resolved with the cached row, so its own error never fires;
+ * this carries the failure the same way.
+ */
+ const [settleFailure, setSettleFailure] = createSignal<unknown>();
+
+ const superseded = (session: AgentSession) =>
+ untrack(sessionId) !== session.id;
+
+ /**
+ * Show what the machine holds for `record`. Read after every input pushed
+ * so far, and applied before any event that arrives later: events between
+ * subscribe and here upserted into the list, and this replaces the list
+ * with a view that includes them.
+ */
+ const show = async (
+ session: AgentSession,
+ record: AgentSessionRecord,
+ kind: 'cached' | 'fetched'
+ ) => {
+ const snapshot = await session.snapshot();
+ if (superseded(session)) return;
+ batch(() => {
+ setBot(record.bot);
+ setMetadata(snapshot.metadata);
+ replace(snapshot.messages);
+ });
+ session.rendered(kind);
+ };
+
+ /** The fetched session, shown, with a rename that landed meanwhile kept. */
+ const settle = async (
+ session: AgentSession,
+ renameRefreshAtStart: number
+ ): Promise<AgentSessionResponse> => {
+ const record = await session.load();
+ if (superseded(session)) return record.session;
+ await show(session, record, 'fetched');
+ return renameRefresh > renameRefreshAtStart &&
+ latestRename?.agentSessionId === session.id
+ ? { ...record.session, name: latestRename.name }
+ : record.session;
+ };
const [resource, { mutate, refetch }] = createResource(
live,
async (session) => {
const renameRefreshAtStart = renameRefresh;
- const superseded = () => untrack(sessionId) !== session.id;
batch(() => {
setList(reconcile([]));
setBot(undefined);
setMetadata(undefined);
+ setSettleFailure(undefined);
});
- const record = await session.load();
- if (superseded()) return record.session;
- // Read after every input pushed so far, and applied before any event
- // that arrives later: events between subscribe and here upserted into
- // the list, and this replaces the list with a view that includes them.
- const snapshot = await session.snapshot();
- if (superseded()) return record.session;
-
- batch(() => {
- setBot(record.bot);
- setMetadata(snapshot.metadata);
- replace(snapshot.messages);
- });
-
- return renameRefresh > renameRefreshAtStart &&
- latestRename?.agentSessionId === session.id
- ? { ...record.session, name: latestRename.name }
- : record.session;
+ const cached = await session.warm();
+ if (!cached || superseded(session)) {
+ return settle(session, renameRefreshAtStart);
+ }
+ // A transcript from the last open goes up now; the fetched one
+ // replaces it when it lands, through the same store, so the resource
+ // resolves here and the fetch settles it in the background.
+ await show(session, cached, 'cached');
+ void settleInBackground(session, renameRefreshAtStart);
+ return cached.session;
}
);
+ async function settleInBackground(
+ session: AgentSession,
+ renameRefreshAtStart: number
+ ): Promise<void> {
+ try {
+ const fetched = await settle(session, renameRefreshAtStart);
+ if (!superseded(session)) mutate(fetched);
+ } catch (error) {
+ if (!superseded(session)) setSettleFailure(error);
+ }
+ }
+
onCleanup(
subscribeAgentSessionRenamed((event) => {
if (event.agentSessionId !== sessionId()) return;
@@ -294,8 +343,9 @@ export function createAgentSession(
// update queue before the enclosing `<Suspense>` swaps its fallback back
// out, and the block shows a spinner forever instead of its error panel.
// The failure is reported through `loadFailed`; absent is what the row is.
+ const failure = () => resource.error ?? settleFailure();
const session = () => {
- if (resource.error !== undefined) return undefined;
+ if (failure() !== undefined) return undefined;
if (openedPending && resource.state === 'pending') return undefined;
return resource.latest;
};
@@ -305,8 +355,8 @@ export function createAgentSession(
bot,
metadata,
messages: () => list,
- loadFailed: () => resource.error !== undefined,
- accessDenied: () => resource.error instanceof AgentSessionAccessDenied,
+ loadFailed: () => failure() !== undefined,
+ accessDenied: () => failure() instanceof AgentSessionAccessDenied,
retry: () => void refetch(),
issue: (action) => live()?.issue(action, { userId: options.userId() }),
selectModel: async (model, effort) => {
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
index 07546f47c8..8e5da9cf71 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
@@ -7,11 +7,8 @@
import type { FoldInput } from '@core/agent-fold/client';
import type { FoldedStreamEvent } from '@service-agent-fold/generated/types';
-import type {
- AgentSessionLogEntryDto,
- AgentSessionLogResponse,
-} from '@service-agent-harness/generated/schemas';
-import { err, ok, type Result } from 'neverthrow';
+import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';
+import { err, ok } from 'neverthrow';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const fold = vi.hoisted(() => ({
@@ -21,9 +18,32 @@ const fold = vi.hoisted(() => ({
}));
const harness = vi.hoisted(() => ({
get: vi.fn(),
- getLog: vi.fn(),
control: vi.fn(),
}));
+const logSource = vi.hoisted(() => {
+ class Unavailable extends Error {
+ constructor(
+ readonly sessionId: string,
+ readonly reason: 'inaccessible' | 'failed'
+ ) {
+ super(`agent session log is ${reason}: ${sessionId}`);
+ }
+ }
+ const source = {
+ Unavailable,
+ cached: vi.fn(),
+ fetched: vi.fn(),
+ append: vi.fn(),
+ forget: vi.fn(),
+ watch: vi.fn(),
+ };
+ source.watch.mockImplementation(() => ({
+ cached: source.cached(),
+ fetched: source.fetched(),
+ stop: () => {},
+ }));
+ return source;
+});
const socket = vi.hoisted(() => ({
listeners: new Set<() => void>(),
subscribeSocketSessionStarted: vi.fn((listener: () => void) => {
@@ -54,6 +74,12 @@ vi.mock('@service-agent-harness/client', () => ({
vi.mock('@queries/agent-session/queue-sync', () => ({
subscribeSocketSessionStarted: socket.subscribeSocketSessionStarted,
}));
+vi.mock('@queries/agent-session/log', () => ({
+ AgentSessionLogUnavailable: logSource.Unavailable,
+ watchAgentSessionLog: logSource.watch,
+ appendAgentSessionLogRows: logSource.append,
+ forgetAgentSessionLog: logSource.forget,
+}));
import {
AgentSession,
@@ -75,9 +101,11 @@ function row(n: number): AgentSessionLogEntryDto {
const bot = { id: 'bot-id', name: 'Agent', handle: 'agent' };
const session = { id: SESSION, name: 'A session', canEdit: true };
-type LogResult = Result<AgentSessionLogResponse, unknown>;
-const logOf = (entries: AgentSessionLogEntryDto[]): LogResult =>
- ok({ bot, entries } as unknown as AgentSessionLogResponse);
+type LogSnapshot = { bot: typeof bot; rows: AgentSessionLogEntryDto[] };
+const logOf = (rows: AgentSessionLogEntryDto[]): LogSnapshot => ({
+ bot,
+ rows,
+});
/** Every input the worker saw, flattened across pushes. */
const inputs = (): FoldInput[] =>
@@ -89,10 +117,12 @@ const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
/** A deferred the test resolves by hand. */
function deferred<T>() {
let resolve!: (value: T) => void;
- const promise = new Promise<T>((r) => {
- resolve = r;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
});
- return { promise, resolve };
+ return { promise, resolve, reject };
}
beforeEach(() => {
@@ -112,7 +142,10 @@ beforeEach(() => {
fold.pushSession.mockResolvedValue([]);
fold.readSession.mockResolvedValue({ messages: [], metadata: {} });
harness.get.mockResolvedValue(ok(session));
- harness.getLog.mockResolvedValue(ok({ bot, entries: [row(1)] }));
+ logSource.cached.mockResolvedValue(undefined);
+ logSource.fetched.mockResolvedValue(logOf([row(1)]));
+ logSource.append.mockResolvedValue(undefined);
+ logSource.forget.mockResolvedValue(undefined);
harness.control.mockImplementation(
async (_id: string, request: { actionId: string }) =>
ok({ actionId: request.actionId, status: 'sent' })
@@ -121,8 +154,8 @@ beforeEach(() => {
describe('AgentSession', () => {
it('folds the snapshot first, then rows that arrived during the load', async () => {
- const log = deferred<LogResult>();
- harness.getLog.mockReturnValue(log.promise);
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValue(log.promise);
const live = AgentSession.acquire(SESSION);
AgentSession.ingest({ agentSessionId: SESSION, entries: [row(2)] });
@@ -140,8 +173,8 @@ describe('AgentSession', () => {
});
it('names a load abandoned by its last release, rather than failing it', async () => {
- const log = deferred<LogResult>();
- harness.getLog.mockReturnValue(log.promise);
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValue(log.promise);
const live = AgentSession.acquire(SESSION);
const loading = live.load();
@@ -300,8 +333,8 @@ describe('AgentSession', () => {
});
it('buffers an action issued before the snapshot behind it', async () => {
- const log = deferred<LogResult>();
- harness.getLog.mockReturnValue(log.promise);
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValue(log.promise);
const live = AgentSession.acquire(SESSION);
void live.issue({ type: 'prompt', prompt: 'early' });
@@ -322,7 +355,7 @@ describe('AgentSession', () => {
const second = AgentSession.acquire(SESSION);
expect(second).toBe(first);
await first.load();
- expect(harness.getLog).toHaveBeenCalledOnce();
+ expect(logSource.watch).toHaveBeenCalledOnce();
first.release();
expect(fold.closeSession).not.toHaveBeenCalled();
@@ -335,10 +368,10 @@ describe('AgentSession', () => {
it('reloads committed recovery state and preserves frames received during the read', async () => {
const live = AgentSession.acquire(SESSION);
await live.load();
- const log = deferred<LogResult>();
- harness.getLog.mockReturnValueOnce(log.promise);
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValueOnce(log.promise);
invalidate('another-session');
- expect(harness.getLog).toHaveBeenCalledTimes(1);
+ expect(logSource.watch).toHaveBeenCalledTimes(1);
invalidate();
AgentSession.ingest({ agentSessionId: SESSION, entries: [row(3)] });
expect(inputs().filter((input) => input.kind === 'confirmed')).toEqual([]);
@@ -355,9 +388,9 @@ describe('AgentSession', () => {
});
it('coalesces repeated invalidations and catches one received during initial loading', async () => {
- const first = deferred<LogResult>();
- const refresh = deferred<LogResult>();
- harness.getLog
+ const first = deferred<LogSnapshot>();
+ const refresh = deferred<LogSnapshot>();
+ logSource.fetched
.mockReturnValueOnce(first.promise)
.mockReturnValueOnce(refresh.promise)
.mockResolvedValueOnce(logOf([row(1), row(2), row(3)]));
@@ -365,10 +398,10 @@ describe('AgentSession', () => {
invalidate();
first.resolve(logOf([row(1)]));
await live.load();
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
invalidate();
invalidate();
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
refresh.resolve(logOf([row(1), row(2)]));
await vi.waitFor(() =>
expect(inputs().at(-1)).toEqual({
@@ -376,18 +409,18 @@ describe('AgentSession', () => {
rows: [row(1), row(2), row(3)],
})
);
- expect(harness.getLog).toHaveBeenCalledTimes(3);
+ expect(logSource.watch).toHaveBeenCalledTimes(3);
live.release();
});
it('releases buffered live frames after a failed refresh', async () => {
const live = AgentSession.acquire(SESSION);
await live.load();
- const refresh = deferred<LogResult>();
- harness.getLog.mockReturnValueOnce(refresh.promise);
+ const refresh = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValueOnce(refresh.promise);
invalidate();
AgentSession.ingest({ agentSessionId: SESSION, entries: [row(2)] });
- refresh.resolve(err([{ code: 'INTERNAL' }]));
+ refresh.reject(new logSource.Unavailable(SESSION, 'failed'));
await vi.waitFor(() =>
expect(inputs().at(-1)).toEqual({ kind: 'confirmed', row: row(2) })
);
@@ -405,22 +438,26 @@ describe('AgentSession', () => {
try {
await live.load();
if (failure === 'result')
- harness.getLog.mockResolvedValueOnce(err([{ code: 'INTERNAL' }]));
- else harness.getLog.mockRejectedValueOnce(new Error('network down'));
- harness.getLog.mockResolvedValueOnce(logOf([row(1), row(2), row(3)]));
+ logSource.fetched.mockRejectedValueOnce(
+ new logSource.Unavailable(SESSION, 'failed')
+ );
+ else logSource.fetched.mockRejectedValueOnce(new Error('network down'));
+ logSource.fetched.mockResolvedValueOnce(
+ logOf([row(1), row(2), row(3)])
+ );
invalidate();
await vi.advanceTimersByTimeAsync(0);
AgentSession.ingest({ agentSessionId: SESSION, entries: [row(2)] });
await live.snapshot();
expect(inputs().at(-1)).toEqual({ kind: 'confirmed', row: row(2) });
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1_000);
expect(inputs().at(-1)).toEqual({
kind: 'snapshot',
rows: [row(1), row(2), row(3)],
});
await vi.advanceTimersByTimeAsync(60_000);
- expect(harness.getLog).toHaveBeenCalledTimes(3);
+ expect(logSource.watch).toHaveBeenCalledTimes(3);
} finally {
live.release();
vi.useRealTimers();
@@ -433,13 +470,15 @@ describe('AgentSession', () => {
const live = AgentSession.acquire(SESSION);
try {
await live.load();
- harness.getLog.mockResolvedValue(err([{ code: 'INTERNAL' }]));
+ logSource.fetched.mockRejectedValue(
+ new logSource.Unavailable(SESSION, 'failed')
+ );
invalidate();
await vi.advanceTimersByTimeAsync(60_000);
- expect(harness.getLog).toHaveBeenCalledTimes(5);
+ expect(logSource.watch).toHaveBeenCalledTimes(5);
invalidate();
await vi.advanceTimersByTimeAsync(60_000);
- expect(harness.getLog).toHaveBeenCalledTimes(9);
+ expect(logSource.watch).toHaveBeenCalledTimes(9);
} finally {
live.release();
vi.useRealTimers();
@@ -451,12 +490,14 @@ describe('AgentSession', () => {
const live = AgentSession.acquire(SESSION);
try {
await live.load();
- harness.getLog.mockResolvedValue(err([{ code: 'INTERNAL' }]));
+ logSource.fetched.mockRejectedValue(
+ new logSource.Unavailable(SESSION, 'failed')
+ );
invalidate();
await vi.advanceTimersByTimeAsync(0);
live.release();
await vi.advanceTimersByTimeAsync(60_000);
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
} finally {
if (AgentSession.get(SESSION)) live.release();
vi.useRealTimers();
@@ -468,10 +509,12 @@ describe('AgentSession', () => {
const live = AgentSession.acquire(SESSION);
try {
await live.load();
- harness.getLog.mockResolvedValue(err([{ code: 'FORBIDDEN' }]));
+ logSource.fetched.mockRejectedValue(
+ new logSource.Unavailable(SESSION, 'inaccessible')
+ );
invalidate();
await vi.advanceTimersByTimeAsync(60_000);
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
} finally {
live.release();
vi.useRealTimers();
@@ -487,8 +530,8 @@ describe('AgentSession', () => {
);
const live = AgentSession.acquire(SESSION);
await live.load();
- const refresh = deferred<LogResult>();
- harness.getLog.mockReturnValueOnce(refresh.promise);
+ const refresh = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValueOnce(refresh.promise);
invalidate();
await live.issue({ type: 'prompt', prompt: 'Continue' });
expect(inputs().filter((input) => input.kind === 'speculated')).toEqual(
@@ -515,8 +558,8 @@ describe('AgentSession', () => {
it('does not recreate a released session when a refresh completes', async () => {
const live = AgentSession.acquire(SESSION);
await live.load();
- const refresh = deferred<LogResult>();
- harness.getLog.mockReturnValueOnce(refresh.promise);
+ const refresh = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValueOnce(refresh.promise);
invalidate();
live.release();
const before = inputs();
@@ -529,7 +572,7 @@ describe('AgentSession', () => {
it('re-snapshots when the socket reopens', async () => {
const live = AgentSession.acquire(SESSION);
await live.load();
- harness.getLog.mockResolvedValue(ok({ bot, entries: [row(1), row(2)] }));
+ logSource.fetched.mockResolvedValue(logOf([row(1), row(2)]));
for (const listener of socket.listeners) listener();
await settle();
@@ -697,21 +740,120 @@ describe('AgentSession', () => {
const live = AgentSession.acquire(SESSION);
await expect(live.load()).rejects.toBeInstanceOf(AgentSessionAccessDenied);
- harness.getLog.mockResolvedValueOnce(err([{ code: 'FORBIDDEN' }]));
+ logSource.fetched.mockRejectedValueOnce(
+ new logSource.Unavailable(SESSION, 'inaccessible')
+ );
await expect(live.load()).rejects.toBeInstanceOf(AgentSessionAccessDenied);
live.release();
});
+ describe('cached log', () => {
+ it('folds the cached log first and the fetched one over it', async () => {
+ logSource.cached.mockResolvedValue(logOf([row(1), row(2)]));
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValue(log.promise);
+
+ const live = AgentSession.acquire(SESSION);
+ expect(await live.warm()).toEqual({ session, bot });
+ expect(inputs()).toEqual([{ kind: 'snapshot', rows: [row(1), row(2)] }]);
+
+ log.resolve(logOf([row(1), row(2), row(3)]));
+ expect(await live.load()).toEqual({ session, bot });
+ expect(inputs().at(-1)).toEqual({
+ kind: 'snapshot',
+ rows: [row(1), row(2), row(3)],
+ });
+ live.release();
+ });
+
+ it('holds live rows behind the fetched log while the cached one shows', async () => {
+ logSource.cached.mockResolvedValue(logOf([row(1)]));
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValue(log.promise);
+
+ const live = AgentSession.acquire(SESSION);
+ await live.warm();
+ // Delivered while the fetch is on the wire. The cached transcript is
+ // on screen but frozen: folding this row onto it now could lose it to
+ // the fetched snapshot's replace, so it waits behind that snapshot.
+ AgentSession.ingest({ agentSessionId: SESSION, entries: [row(3)] });
+ await settle();
+ expect(inputs()).toEqual([{ kind: 'snapshot', rows: [row(1)] }]);
+
+ log.resolve(logOf([row(1), row(2)]));
+ await live.load();
+ expect(inputs().slice(1)).toEqual([
+ { kind: 'snapshot', rows: [row(1), row(2)] },
+ { kind: 'confirmed', row: row(3) },
+ ]);
+ live.release();
+ });
+
+ it('never lets a cached log replace a fetched one that landed first', async () => {
+ const read = deferred<unknown>();
+ logSource.cached.mockReturnValue(read.promise);
+
+ const live = AgentSession.acquire(SESSION);
+ await live.load();
+ read.resolve(logOf([row(9)]));
+
+ expect(await live.warm()).toBeUndefined();
+ expect(inputs()).toEqual([{ kind: 'snapshot', rows: [row(1)] }]);
+ live.release();
+ });
+
+ it('appends every row delivered after the fetched log to the cached copy, once', async () => {
+ const live = AgentSession.acquire(SESSION);
+ await live.load();
+ AgentSession.ingest({ agentSessionId: SESSION, entries: [row(2)] });
+ AgentSession.ingest({ agentSessionId: SESSION, entries: [row(2)] });
+ await settle();
+ // Debounced: nothing written yet.
+ expect(logSource.append).not.toHaveBeenCalled();
+
+ live.release();
+ // The exchange wrote the fetched log itself; only the new row goes.
+ expect(logSource.append).toHaveBeenCalledWith(SESSION, [row(2)]);
+ });
+
+ it('appends rows that waited behind the fetched log too', async () => {
+ const log = deferred<LogSnapshot>();
+ logSource.fetched.mockReturnValue(log.promise);
+ const live = AgentSession.acquire(SESSION);
+ AgentSession.ingest({ agentSessionId: SESSION, entries: [row(2)] });
+ log.resolve(logOf([row(1)]));
+ await live.load();
+ live.release();
+ // The buffered row is folded after the snapshot, and appended too.
+ expect(logSource.append).toHaveBeenCalledWith(SESSION, [row(2)]);
+ });
+
+ it('forgets the cached log when the viewer is refused', async () => {
+ logSource.fetched.mockRejectedValueOnce(
+ new logSource.Unavailable(SESSION, 'inaccessible')
+ );
+ const live = AgentSession.acquire(SESSION);
+ await expect(live.load()).rejects.toBeInstanceOf(
+ AgentSessionAccessDenied
+ );
+ expect(logSource.forget).toHaveBeenCalledWith(SESSION);
+ expect(logSource.append).not.toHaveBeenCalled();
+ live.release();
+ });
+ });
+
it('re-runs a failed load on the next call only', async () => {
- harness.getLog.mockResolvedValueOnce(err([{ code: 'NOT_FOUND' }]));
+ logSource.fetched.mockRejectedValueOnce(
+ new logSource.Unavailable(SESSION, 'failed')
+ );
const live = AgentSession.acquire(SESSION);
await expect(live.load()).rejects.toThrow('log could not be fetched');
const record = await live.load();
expect(record.bot).toEqual(bot);
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
await live.load();
- expect(harness.getLog).toHaveBeenCalledTimes(2);
+ expect(logSource.watch).toHaveBeenCalledTimes(2);
live.release();
});
});
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.ts
index 72a8182621..8be7e0e3ec 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts
@@ -11,6 +11,12 @@
* rebases it when a foreign row lands first, and drops it if this class
* retracts it. Listeners only ever see fold events; whether a message is
* still on the wire is a field on the message, never a second channel.
+ *
+ * A session opened before is folded twice: first from the raw log the
+ * GraphQL cache holds from its last open, so the surface has a transcript
+ * while the fetch is on the wire, then from the fetched log, which the
+ * machine reconciles by row id. The exchange writes the fetched log back;
+ * rows the socket delivers after it are appended to the cached copy here.
*/
import {
@@ -20,7 +26,13 @@ import {
readSession,
type SessionFoldSnapshot,
} from '@core/agent-fold/client';
-import { fetchAgentSessionLog } from '@queries/agent-session/log';
+import {
+ AgentSessionLogUnavailable,
+ appendAgentSessionLogRows,
+ forgetAgentSessionLog,
+ type SessionLogWatch,
+ watchAgentSessionLog,
+} from '@queries/agent-session/log';
import { subscribeSocketSessionStarted } from '@queries/agent-session/queue-sync';
import type { AgentSessionLogEvent } from '@queries/agent-session/realtime-protocol';
import { subscribeAgentSessionUpdated } from '@queries/agent-session/session-metadata-sync';
@@ -31,12 +43,17 @@ import type {
import { agentHarnessServiceClient } from '@service-agent-harness/client';
import type {
AgentAction,
+ AgentSessionLogEntryDto,
AgentSessionResponse,
ControlRequest,
SessionBot,
} from '@service-agent-harness/generated/schemas';
import { v7 as uuidv7 } from 'uuid';
-import { SessionLoadTrace, traceAcquire } from './load-telemetry';
+import {
+ SessionLoadTrace,
+ traceAcquire,
+ traceCacheWrite,
+} from './load-telemetry';
import { publishSessionTurn } from './session-turn';
export type AgentSessionListener = (events: FoldedStreamEvent[]) => void;
@@ -78,6 +95,11 @@ export class AgentSessionAccessDenied extends Error {
}
}
+/** The log query answered that the viewer cannot see this session. */
+const inaccessible = (error: unknown) =>
+ error instanceof AgentSessionLogUnavailable &&
+ error.reason === 'inaccessible';
+
const accessDenied = (errors: { code: string }[]) =>
errors.some(
(error) => error.code === 'UNAUTHORIZED' || error.code === 'FORBIDDEN'
@@ -94,6 +116,12 @@ function occupiesTurn(action: AgentAction): boolean {
const RESYNC_RETRY_DELAYS_MS = [1_000, 3_000, 10_000];
+/**
+ * How long appended rows wait before the cached log is extended. A streaming
+ * turn delivers rows many times a second, and each append re-reads the list.
+ */
+const CACHE_WRITE_DEBOUNCE_MS = 1_000;
+
export class AgentSession {
private static readonly open = new Map<string, AgentSession>();
@@ -132,8 +160,27 @@ export class AgentSession {
private references = 0;
private closed = false;
- /** The snapshot has been folded; inputs no longer wait for it. */
+ /** The fetched snapshot has been folded; inputs no longer wait for it. */
private ready = false;
+ /**
+ * The fetched log has been folded. Before this the machine may hold the
+ * cached log, shown but frozen: live rows wait in `buffered` and fold
+ * after the fetched snapshot, which cannot have lost them.
+ */
+ private settled = false;
+ /**
+ * Rows the socket delivered since the fetched log, not yet appended to
+ * the cached copy; `knownIds` is everything the cache already holds.
+ */
+ private pendingAppend: AgentSessionLogEntryDto[] = [];
+ private knownIds: Set<string> | undefined;
+ private cacheWriteTimer?: ReturnType<typeof setTimeout>;
+ /** The log query in flight for the current load: cached copy, then fetched. */
+ private watch: SessionLogWatch;
+ /** The session row, fetched alongside the log and shared by warm and load. */
+ private sessionRow: Promise<
+ Awaited<ReturnType<typeof agentHarnessServiceClient.get>>
+ >;
/** Inputs that arrived before the snapshot, in order. */
private buffered: FoldInput[] = [];
private readonly listeners = new Set<AgentSessionListener>();
@@ -148,6 +195,7 @@ export class AgentSession {
* class saw them, even though each push is its own await.
*/
private chain: Promise<void> = Promise.resolve();
+ private warming: Promise<AgentSessionRecord | undefined>;
private loading: Promise<AgentSessionRecord>;
private loadFailed = false;
/** The span for the attempt in flight, ended by whatever settles it. */
@@ -176,7 +224,24 @@ export class AgentSession {
if (event.agentSessionId === this.id) void this.resync();
});
this.trace = new SessionLoadTrace(id);
+ this.watch = watchAgentSessionLog(id);
+ this.sessionRow = agentHarnessServiceClient.get(id);
+ this.warming = this.startWarm();
this.loading = this.startLoad();
+ // A surface rendering the cached log has not called `load` yet when a
+ // fast failure lands, and an unobserved rejection is reported as
+ // unhandled. The failure still reaches every caller of `load`.
+ this.loading.catch(() => undefined);
+ }
+
+ /**
+ * The session as the GraphQL cache last saw it, folded from the cached
+ * log: what a surface can render while {@link load} is on the wire.
+ * Resolves to nothing when there is no cached log, or when the fetched
+ * one landed first. Never fails: a cache that cannot be read is a miss.
+ */
+ warm(): Promise<AgentSessionRecord | undefined> {
+ return this.warming;
}
/**
@@ -188,6 +253,8 @@ export class AgentSession {
if (this.loadFailed) {
this.loadFailed = false;
this.trace = new SessionLoadTrace(this.id);
+ this.watch = watchAgentSessionLog(this.id);
+ this.sessionRow = agentHarnessServiceClient.get(this.id);
this.loading = this.startLoad();
}
return this.loading;
@@ -357,9 +424,44 @@ export class AgentSession {
this.unsubscribeSocket();
this.unsubscribeUpdated();
clearTimeout(this.resyncTimer);
+ this.flushCacheWrite();
closeSession(this.id);
}
+ private async startWarm(): Promise<AgentSessionRecord | undefined> {
+ const readStartedAt = performance.now();
+ // The cached log carries no session row, so the (small) row fetch is
+ // part of warming: the transcript can show only inside a session.
+ const [cached, session] = await Promise.all([
+ this.watch.cached.then((cached) => {
+ this.trace.cacheRead(
+ readStartedAt,
+ cached && { rows: cached.rows.length }
+ );
+ return cached;
+ }),
+ this.sessionRow,
+ ]);
+ // `settled` is set in the same tick as the fetched snapshot's push, so
+ // checking it here and pushing below cannot interleave with that push:
+ // a cached log never replaces a fetched one.
+ if (!cached || session.isErr() || this.closed || this.settled) {
+ return undefined;
+ }
+ const foldStartedAt = performance.now();
+ // `ready` stays false: live rows keep waiting for the fetched snapshot.
+ await this.apply([{ kind: 'snapshot', rows: cached.rows }]);
+ if (this.closed) return undefined;
+ this.trace.stage('cache_fold', foldStartedAt);
+ this.setTurn((await readSession(this.id)).metadata.turn);
+ return { session: session.value, bot: cached.bot };
+ }
+
+ /** A surface put this session's transcript on screen. */
+ rendered(kind: 'cached' | 'fetched'): void {
+ this.trace.rendered(kind);
+ }
+
private startLoad(): Promise<AgentSessionRecord> {
return this.fetchAndFold().then(
(record) => {
@@ -378,32 +480,107 @@ export class AgentSession {
}
private async fetchAndFold(): Promise<AgentSessionRecord> {
+ const fetchStartedAt = performance.now();
const [session, log] = await Promise.all([
- agentHarnessServiceClient.get(this.id),
- fetchAgentSessionLog(this.id),
+ this.sessionRow.then((session) => {
+ this.trace.stage('session_fetch', fetchStartedAt);
+ return session;
+ }),
+ this.watch.fetched.then(
+ (log) => ({ ok: true as const, log }),
+ (error: unknown) => ({ ok: false as const, error })
+ ),
]);
if (session.isErr()) {
if (accessDenied(session.error)) {
+ this.forgetCached();
throw new AgentSessionAccessDenied(this.id);
}
throw new Error(`agent session could not be fetched: ${this.id}`);
}
- if (log.isErr()) {
- if (accessDenied(log.error)) throw new AgentSessionAccessDenied(this.id);
- throw new Error(`agent session log could not be fetched: ${this.id}`);
+ if (!log.ok) {
+ if (inaccessible(log.error)) {
+ this.forgetCached();
+ throw new AgentSessionAccessDenied(this.id);
+ }
+ throw new Error(`agent session log could not be fetched: ${this.id}`, {
+ cause: log.error,
+ });
}
if (this.closed) throw new AgentSessionReleased(this.id);
- this.trace.fetched(log.value.entries.length);
+ this.trace.fetched(fetchStartedAt, log.log.rows.length);
const foldStartedAt = performance.now();
- await this.apply([{ kind: 'snapshot', rows: log.value.entries }]);
+ this.settled = true;
+ await this.apply([{ kind: 'snapshot', rows: log.log.rows }]);
// Inputs can keep arriving while each push is in flight; drain until a
// check finds nothing, then flip ready so the next one goes straight in.
await this.drainBuffered();
this.trace.folded(foldStartedAt);
this.setTurn((await readSession(this.id)).metadata.turn);
if (this.resyncRequested) void this.resync();
- return { session: session.value, bot: log.value.bot };
+ return { session: session.value, bot: log.log.bot };
+ }
+
+ /** The viewer was refused: nothing cached may render for them again. */
+ private forgetCached(): void {
+ this.warming = Promise.resolve(undefined);
+ void forgetAgentSessionLog(this.id).catch((error: unknown) => {
+ console.warn('[agent-session] cached log could not be removed', error);
+ });
+ }
+
+ /**
+ * Keep the cached log in step with what the machine was given, once the
+ * fetched log is what it holds. The exchange already wrote each fetched
+ * snapshot; only confirmed rows after one need appending. The machine
+ * dedupes by row id on its side; this does the same so a row delivered
+ * twice is stored once.
+ */
+ private remember(inputs: FoldInput[]): void {
+ if (!this.settled) return;
+ let changed = false;
+ for (const input of inputs) {
+ if (input.kind === 'snapshot') {
+ this.knownIds = new Set(input.rows.map((row) => row.id));
+ this.pendingAppend = [];
+ } else if (input.kind === 'confirmed' && this.knownIds) {
+ if (this.knownIds.has(input.row.id)) continue;
+ this.knownIds.add(input.row.id);
+ this.pendingAppend.push(input.row);
+ changed = true;
+ }
+ }
+ if (changed) this.scheduleCacheWrite();
+ }
+
+ private scheduleCacheWrite(): void {
+ if (this.cacheWriteTimer !== undefined) return;
+ this.cacheWriteTimer = setTimeout(() => {
+ this.cacheWriteTimer = undefined;
+ this.writeCache();
+ }, CACHE_WRITE_DEBOUNCE_MS);
+ }
+
+ /** Write now what a pending timer would have: the session is going away. */
+ private flushCacheWrite(): void {
+ if (this.cacheWriteTimer === undefined) return;
+ clearTimeout(this.cacheWriteTimer);
+ this.cacheWriteTimer = undefined;
+ this.writeCache();
+ }
+
+ private writeCache(): void {
+ const rows = this.pendingAppend;
+ if (rows.length === 0) return;
+ this.pendingAppend = [];
+ const startedAt = performance.now();
+ void appendAgentSessionLogRows(this.id, rows).then(
+ () => traceCacheWrite(this.id, startedAt, rows.length),
+ (error: unknown) => {
+ console.warn('[agent-session] log rows could not be cached', error);
+ }
+ );
}
/**
@@ -425,11 +602,15 @@ export class AgentSession {
try {
do {
this.resyncRequested = false;
- const log = await fetchAgentSessionLog(this.id);
+ let log: Awaited<SessionLogWatch['fetched']> | undefined;
+ try {
+ log = await watchAgentSessionLog(this.id, 'network-only').fetched;
+ } catch (error: unknown) {
+ failed = !inaccessible(error);
+ }
if (this.closed) return;
- failed = log.isErr() && !accessDenied(log.error);
- if (log.isOk()) {
- await this.apply([{ kind: 'snapshot', rows: log.value.entries }]);
+ if (log) {
+ await this.apply([{ kind: 'snapshot', rows: log.rows }]);
this.resyncRetry = 0;
}
} while (this.resyncRequested);
@@ -475,6 +656,7 @@ export class AgentSession {
}
private apply(inputs: FoldInput[]): Promise<void> {
+ this.remember(inputs);
const run = this.chain.then(async () => {
if (this.closed) return;
const events = await pushSession(this.id, inputs);
diff --git a/apps/web/src/lib/core/agent-session/load-telemetry.ts b/apps/web/src/lib/core/agent-session/load-telemetry.ts
index e3d72f9d45..4b718797db 100644
--- a/apps/web/src/lib/core/agent-session/load-telemetry.ts
+++ b/apps/web/src/lib/core/agent-session/load-telemetry.ts
@@ -48,13 +48,48 @@ const STALL_THRESHOLD_MS = 15_000;
* Held rather than run around an operation because the operation it measures
* can be abandoned: `release` ends the span from outside the load.
*/
+/** A stage of the load, named as its measure and attribute suffix. */
+export type LoadStage =
+ /** The cached log was looked up. */
+ | 'cache_read'
+ /** The cached log was folded; the surface can show it. */
+ | 'cache_fold'
+ /** The session row was fetched. */
+ | 'session_fetch'
+ /** The log was fetched. */
+ | 'log_fetch'
+ /** The fetched log was folded; the surface can show the truth. */
+ | 'fold'
+ /** A surface painted the cached transcript. */
+ | 'warm_render'
+ /** A surface painted the fetched transcript. */
+ | 'render';
+
+/**
+ * One attempt to open a session, from the first acquisition to whatever
+ * ended it.
+ *
+ * Every stage lands in three places: an attribute and an event on the
+ * `agent.session.load` span, so a slow open can be read in Datadog; a
+ * `performance.measure` named `agent.session.load.<stage>`, so the same
+ * stages show in the DevTools Performance panel and can be read back with
+ * `performance.getEntriesByType('measure')`; and, when
+ * `window.debugAgentSessionLoad` is set, one `console.debug` line at the end
+ * with everything the attempt recorded.
+ *
+ * Held rather than run around an operation because the operation it measures
+ * can be abandoned: `release` ends the span from outside the load.
+ */
export class SessionLoadTrace {
readonly #span: Span | undefined;
+ readonly #sessionId: string;
readonly #startedAt = performance.now();
+ readonly #recorded: Record<string, string | number | boolean> = {};
#ended = false;
#stallTimer: ReturnType<typeof setTimeout> | undefined;
constructor(sessionId: string) {
+ this.#sessionId = sessionId;
this.#span = start('agent.session.load', sessionId);
this.#stallTimer = setTimeout(
() => this.end('stalled'),
@@ -62,15 +97,91 @@ export class SessionLoadTrace {
);
}
+ /**
+ * A stage finished: it began at `startedAt` (a `performance.now()` value)
+ * and ends now. Records its duration, and its distance from the start of
+ * the load as `<stage>_at_ms`, so stages that overlap (the two fetches, a
+ * cache read beside them) can still be laid out on one line.
+ */
+ stage(
+ stage: LoadStage,
+ startedAt: number,
+ attributes: Record<string, string | number | boolean> = {}
+ ): void {
+ const now = performance.now();
+ const ms = now - startedAt;
+ this.#set(`agent.session.load.${stage}_ms`, ms);
+ this.#set(`agent.session.load.${stage}_at_ms`, now - this.#startedAt);
+ for (const [name, value] of Object.entries(attributes)) {
+ this.#set(`agent.session.load.${name}`, value);
+ }
+ try {
+ this.#span?.event(`agent.session.load.${stage}`, { ms, ...attributes });
+ performance.measure(`agent.session.load.${stage}`, {
+ start: startedAt,
+ end: now,
+ detail: { sessionId: this.#sessionId, ...attributes },
+ });
+ } catch {
+ // See the module comment.
+ }
+ }
+
+ /**
+ * The cached log was looked up: `hit` is what it held, or nothing. A miss
+ * is a stage too; its duration is what a cold open paid for looking.
+ */
+ cacheRead(startedAt: number, hit: { rows: number } | undefined): void {
+ this.stage('cache_read', startedAt, {
+ cache_hit: hit !== undefined,
+ ...(hit && { cache_rows: hit.rows }),
+ });
+ }
+
/** The log arrived; `rows` is what the fold is about to be given. */
- fetched(rows: number): void {
+ fetched(startedAt: number, rows: number): void {
+ this.stage('log_fetch', startedAt, { log_rows: rows });
+ // Kept under its historical name: dashboards read it.
this.#set('agent.session.log.rows', rows);
this.#set('agent.session.load.fetch_ms', this.#since());
}
- /** The snapshot is folded and the surface can read the session. */
+ /** The fetched snapshot is folded and the surface can read the session. */
folded(foldStartedAt: number): void {
- this.#set('agent.session.load.fold_ms', performance.now() - foldStartedAt);
+ this.stage('fold', foldStartedAt);
+ }
+
+ /**
+ * A surface put a transcript on screen. `cached` is the warm paint from
+ * the cached log; the other is the fetched one. Measured from the start
+ * of the load, which is what a person waited. Its own span rather than a
+ * stage: the load span has usually ended by the time a surface paints,
+ * and an ended span drops what is set on it.
+ */
+ rendered(kind: 'cached' | 'fetched'): void {
+ const stage: LoadStage = kind === 'cached' ? 'warm_render' : 'render';
+ const now = performance.now();
+ const ms = now - this.#startedAt;
+ this.#recorded[`agent.session.load.${stage}_ms`] = Math.round(ms);
+ const span = start('agent.session.render', this.#sessionId);
+ try {
+ span?.setAttr('agent.session.render.kind', kind);
+ span?.setAttr('agent.session.render.since_load_ms', ms);
+ span?.end();
+ performance.measure(`agent.session.load.${stage}`, {
+ start: this.#startedAt,
+ end: now,
+ detail: { sessionId: this.#sessionId, kind },
+ });
+ if (loadDebugEnabled()) {
+ console.debug('[agent-session] render', this.#sessionId, {
+ kind,
+ since_load_ms: Math.round(ms),
+ });
+ }
+ } catch {
+ // See the module comment.
+ }
}
/**
@@ -86,10 +197,18 @@ export class SessionLoadTrace {
this.#set('agent.session.load.outcome', outcome);
this.#set('agent.session.load.total_ms', this.#since());
try {
+ performance.measure('agent.session.load', {
+ start: this.#startedAt,
+ end: performance.now(),
+ detail: { sessionId: this.#sessionId, outcome },
+ });
// A release is the expected end of an abandoned load, not a fault:
// recording it as an error would bury the ones worth looking at.
if (outcome === 'failed' && error !== undefined) this.#span?.error(error);
this.#span?.end();
+ if (loadDebugEnabled()) {
+ console.debug('[agent-session] load', this.#sessionId, this.#recorded);
+ }
} catch {
// See the module comment.
}
@@ -99,7 +218,9 @@ export class SessionLoadTrace {
return performance.now() - this.#startedAt;
}
- #set(name: string, value: string | number): void {
+ #set(name: string, value: string | number | boolean): void {
+ this.#recorded[name] =
+ typeof value === 'number' ? Math.round(value) : value;
try {
this.#span?.setAttr(name, value);
} catch {
@@ -108,6 +229,46 @@ export class SessionLoadTrace {
}
}
+/**
+ * A write of the cached log, after the load: its own short span and
+ * measure, since the load span has usually ended by the time rows stream in.
+ */
+export function traceCacheWrite(
+ sessionId: string,
+ startedAt: number,
+ rows: number
+): void {
+ const now = performance.now();
+ const span = start('agent.session.cache.write', sessionId);
+ try {
+ span?.setAttr('agent.session.cache.write_ms', now - startedAt);
+ span?.setAttr('agent.session.cache.rows', rows);
+ span?.end();
+ performance.measure('agent.session.cache.write', {
+ start: startedAt,
+ end: now,
+ detail: { sessionId, rows },
+ });
+ if (loadDebugEnabled()) {
+ console.debug('[agent-session] cache write', sessionId, {
+ rows,
+ ms: Math.round(now - startedAt),
+ });
+ }
+ } catch {
+ // See the module comment.
+ }
+}
+
+function loadDebugEnabled(): boolean {
+ return (
+ typeof window !== 'undefined' &&
+ Boolean(
+ (window as { debugAgentSessionLoad?: boolean }).debugAgentSessionLoad
+ )
+ );
+}
+
/**
* Record that a surface took a reference to a session.
*
diff --git a/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts b/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts
index 66997d9c82..f61dce15c1 100644
--- a/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts
+++ b/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts
@@ -39,6 +39,10 @@ export const entityResolverSchema = {
},
},
GraphqlUser: {
+ agentSession: {
+ targets: ['GraphqlSoupAgentSession'],
+ argumentPaths: [['sessionId']],
+ },
emailThread: {
targets: ['GraphqlSoupEmailThread'],
argumentPaths: [['input', 'threadId']],
@@ -54,6 +58,7 @@ export type GeneratedEntityResolverSchema = typeof entityResolverSchema;
export type GeneratedEntityResolverTarget =
| 'GraphqlChannelActivity'
| 'GraphqlProperty'
+ | 'GraphqlSoupAgentSession'
| 'GraphqlSoupEmailThread'
| 'GraphqlSoupInitiative';
export type GeneratedEntityResolverArgumentPath =
@@ -63,4 +68,5 @@ export type GeneratedEntityResolverArgumentPath =
| readonly ['input', 'propertyDefinitionId']
| readonly ['input', 'threadId']
| readonly ['input', 'value', 'entityReference', 'specificMessageId']
- | readonly ['input', 'value', 'selectOption'];
+ | readonly ['input', 'value', 'selectOption']
+ | readonly ['sessionId'];
diff --git a/apps/web/src/lib/queries/agent-session/log.ts b/apps/web/src/lib/queries/agent-session/log.ts
index 8b90f72be9..accf859432 100644
--- a/apps/web/src/lib/queries/agent-session/log.ts
+++ b/apps/web/src/lib/queries/agent-session/log.ts
@@ -1,6 +1,245 @@
-import { agentHarnessServiceClient } from '@service-agent-harness/client';
+/**
+ * The session log over GraphQL, through the normalized cache.
+ *
+ * `cache-and-network` answers twice: from disk when the cache holds the log,
+ * then from the network, which the exchange writes back. The caller hears
+ * both in order. Rows the socket delivers after the fetch are appended to
+ * the cached list here, so the next open starts from a log as complete as
+ * the last one ended.
+ */
-/** Read the authoritative log; the shared fold owns its in-memory projection. */
-export function fetchAgentSessionLog(sessionId: string) {
- return agentHarnessServiceClient.getLog(sessionId);
+import { normalizedCacheResultMetadata } from '@graphql-cache/exchange/normalized-cache-exchange';
+import type {
+ AgentSessionLogEntryDto,
+ LogDirectionDto,
+ SessionBot,
+} from '@service-agent-harness/generated/schemas';
+import {
+ AgentSessionLogDocument,
+ type AgentSessionLogQuery,
+ type AgentSessionLogQueryVariables,
+} from '@service-storage/graphql/generated/graphql';
+import {
+ getGraphqlCacheHost,
+ getGraphqlSoupClient,
+} from '@service-storage/graphql-soup';
+import { type OperationResult, stringifyDocument } from '@urql/core';
+import { pipe, subscribe } from 'wonka';
+
+/** What the fold needs: the agent and the raw rows. */
+export type SessionLogSnapshot = {
+ bot: SessionBot;
+ rows: AgentSessionLogEntryDto[];
+};
+
+/**
+ * The log could not be served. `reason` separates a session the viewer
+ * cannot see (or that does not exist) from a transport failure that a
+ * retry could fix.
+ */
+export class AgentSessionLogUnavailable extends Error {
+ constructor(
+ readonly sessionId: string,
+ readonly reason: 'inaccessible' | 'failed',
+ options?: ErrorOptions
+ ) {
+ super(`agent session log is ${reason}: ${sessionId}`, options);
+ this.name = 'AgentSessionLogUnavailable';
+ }
+}
+
+export type SessionLogWatch = {
+ /**
+ * The log as the cache last held it, or nothing when the cache has no
+ * copy or the network answered first. Never rejects.
+ */
+ cached: Promise<SessionLogSnapshot | undefined>;
+ /** The log as the server holds it now. Rejects with {@link AgentSessionLogUnavailable}. */
+ fetched: Promise<SessionLogSnapshot>;
+ /** Stop listening. Unsettled promises settle as a miss and a failure. */
+ stop: () => void;
+};
+
+const DIRECTIONS: ReadonlySet<string> = new Set<LogDirectionDto>([
+ 'to_server',
+ 'to_runtime',
+]);
+
+function isDirection(value: string): value is LogDirectionDto {
+ return DIRECTIONS.has(value);
+}
+
+type LogData = NonNullable<AgentSessionLogQuery['user']['agentSession']>['log'];
+
+/** The wire shape the fold reads, from the GraphQL selection. */
+function toSnapshot(sessionId: string, log: LogData): SessionLogSnapshot {
+ return {
+ bot: {
+ id: log.bot.id,
+ name: log.bot.name,
+ handle: log.bot.handle,
+ ...(log.bot.avatarUrl === null ? {} : { avatarUrl: log.bot.avatarUrl }),
+ },
+ rows: log.entries.map((entry) => {
+ if (!isDirection(entry.direction)) {
+ throw new AgentSessionLogUnavailable(sessionId, 'failed', {
+ cause: new Error(`unknown log direction: ${entry.direction}`),
+ });
+ }
+ return {
+ id: entry.id,
+ createdAt: entry.createdAt,
+ ...(entry.userId === null ? {} : { userId: entry.userId }),
+ direction: entry.direction,
+ content: entry.content as AgentSessionLogEntryDto['content'],
+ };
+ }),
+ };
+}
+
+/**
+ * Watch one session's log: the cached copy first when there is one, then
+ * the fetched one. `policy` `network-only` skips the cache read, for a
+ * resync that wants only what the server holds.
+ */
+export function watchAgentSessionLog(
+ sessionId: string,
+ policy: 'cache-and-network' | 'network-only' = 'cache-and-network'
+): SessionLogWatch {
+ let resolveCached!: (snapshot: SessionLogSnapshot | undefined) => void;
+ let resolveFetched!: (snapshot: SessionLogSnapshot) => void;
+ let rejectFetched!: (error: AgentSessionLogUnavailable) => void;
+ const cached = new Promise<SessionLogSnapshot | undefined>((resolve) => {
+ resolveCached = resolve;
+ });
+ const fetched = new Promise<SessionLogSnapshot>((resolve, reject) => {
+ resolveFetched = resolve;
+ rejectFetched = reject;
+ });
+ // A rejection nobody has awaited yet must not be reported as unhandled.
+ fetched.catch(() => undefined);
+
+ const settleFetched = (result: OperationResult<AgentSessionLogQuery>) => {
+ resolveCached(undefined);
+ if (result.error) {
+ rejectFetched(
+ new AgentSessionLogUnavailable(sessionId, 'failed', {
+ cause: result.error,
+ })
+ );
+ return;
+ }
+ const log = result.data?.user.agentSession?.log;
+ if (!log) {
+ rejectFetched(new AgentSessionLogUnavailable(sessionId, 'inaccessible'));
+ return;
+ }
+ try {
+ resolveFetched(toSnapshot(sessionId, log));
+ } catch (error) {
+ rejectFetched(
+ error instanceof AgentSessionLogUnavailable
+ ? error
+ : new AgentSessionLogUnavailable(sessionId, 'failed', {
+ cause: error,
+ })
+ );
+ }
+ };
+
+ const { unsubscribe } = pipe(
+ getGraphqlSoupClient().query<
+ AgentSessionLogQuery,
+ AgentSessionLogQueryVariables
+ >(AgentSessionLogDocument, { sessionId }, { requestPolicy: policy }),
+ subscribe((result) => {
+ const source = normalizedCacheResultMetadata(result)?.source;
+ const fromCache =
+ source === 'normalized-cache-hit' ||
+ source === 'affected-cache-reread' ||
+ result.stale;
+ if (fromCache) {
+ const log = result.data?.user.agentSession?.log;
+ // A cached miss or a cached refusal is not worth folding; the
+ // network answer settles both.
+ if (log && !result.error) {
+ try {
+ resolveCached(toSnapshot(sessionId, log));
+ } catch {
+ resolveCached(undefined);
+ }
+ }
+ return;
+ }
+ settleFetched(result);
+ unsubscribe();
+ })
+ );
+
+ return {
+ cached,
+ fetched,
+ stop: () => {
+ unsubscribe();
+ resolveCached(undefined);
+ rejectFetched(new AgentSessionLogUnavailable(sessionId, 'failed'));
+ },
+ };
+}
+
+const LOG_QUERY = stringifyDocument(AgentSessionLogDocument);
+const LOG_OPERATION = 'AgentSessionLog';
+
+/**
+ * Append rows the socket delivered to the cached log, so the next open
+ * folds them before the network answers. A cache without this session's
+ * log has nothing to extend; the next fetch writes the whole thing.
+ */
+export async function appendAgentSessionLogRows(
+ sessionId: string,
+ rows: AgentSessionLogEntryDto[]
+): Promise<void> {
+ const host = getGraphqlCacheHost();
+ if (!host || rows.length === 0) return;
+ const args = {
+ query: LOG_QUERY,
+ operationName: LOG_OPERATION,
+ variables: { sessionId } satisfies AgentSessionLogQueryVariables,
+ };
+ const read = await host.readQuery({ ...args, priority: 'user-visible' });
+ if (read.kind !== 'hit') return;
+ // The generated document defines the normalized cache result's shape.
+ const data = read.data as AgentSessionLogQuery;
+ const log = data.user.agentSession?.log;
+ if (!log) return;
+ const known = new Set(log.entries.map((entry) => entry.id));
+ const appended = rows
+ .filter((row) => !known.has(row.id))
+ .map((row) => ({
+ id: row.id,
+ createdAt: row.createdAt,
+ userId: row.userId ?? null,
+ direction: row.direction,
+ content: row.content,
+ }));
+ if (appended.length === 0) return;
+ await host.writeQuery({
+ ...args,
+ data: {
+ user: {
+ id: data.user.id,
+ agentSession: {
+ id: sessionId,
+ log: { bot: log.bot, entries: [...log.entries, ...appended] },
+ },
+ },
+ } satisfies AgentSessionLogQuery,
+ });
+}
+
+/** Drop the cached session so nothing renders for a viewer who was refused. */
+export async function forgetAgentSessionLog(sessionId: string): Promise<void> {
+ const host = getGraphqlCacheHost();
+ if (!host) return;
+ await host.deleteRecords([`GraphqlSoupAgentSession:${sessionId}`]);
}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/agent-session-log.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/agent-session-log.graphql
new file mode 100644
index 0000000000..9f790cde8f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/agent-session-log.graphql
@@ -0,0 +1,26 @@
+# The raw protocol log of one agent session, as the fold reads it. Entries
+# carry ids, so the normalized cache keeps each row once and serves the whole
+# list from disk on the next open before the network answers.
+query AgentSessionLog($sessionId: ID!) {
+ user {
+ id
+ agentSession(sessionId: $sessionId) {
+ id
+ log {
+ bot {
+ id
+ name
+ handle
+ avatarUrl
+ }
+ entries {
+ id
+ createdAt
+ userId
+ direction
+ content
+ }
+ }
+ }
+ }
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 67f4988cce..1a8b9551fb 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -2125,6 +2125,13 @@ export type ActivityEventFieldsFragment = { __typename: 'GraphqlActivityEvent',
| { __typename: 'GraphqlActivityUnknownAction', tag: string, payload: unknown }
};
+export type AgentSessionLogQueryVariables = Exact<{
+ sessionId: string | number;
+}>;
+
+
+export type AgentSessionLogQuery = { user: { id: string, agentSession: { id: string, log: { bot: { id: string, name: string, handle: string, avatarUrl: string | null }, entries: Array<{ id: string, createdAt: string, userId: string | null, direction: string, content: unknown }> } } | null } };
+
export type AgentSessionMentionsQueryVariables = Exact<{
input: SoupInput;
}>;
@@ -15753,6 +15760,7 @@ export const MyActivityDocument = {"kind":"Document","definitions":[{"kind":"Ope
export const MyActivityOverviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyActivityOverview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ActivityOverviewInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"activityOverview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"from"}},{"kind":"Field","name":{"kind":"Name","value":"to"}},{"kind":"Field","name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","name":{"kind":"Name","value":"total"}},{"kind":"Field","name":{"kind":"Name","value":"days"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"date"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"topEntities"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}}]}}]}}]}}]} as unknown as DocumentNode<MyActivityOverviewQuery, MyActivityOverviewQueryVariables>;
export const EntityActivityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"EntityActivity"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"EntityActivityFields"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ActivityEventFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"actorId"}},{"kind":"Field","name":{"kind":"Name","value":"subjectId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"occurredAt"}},{"kind":"Field","name":{"kind":"Name","value":"action"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityPropertyChanged"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"property"}},{"kind":"Field","name":{"kind":"Name","value":"from"}},{"kind":"Field","name":{"kind":"Name","value":"to"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityParticipantAdded"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"participant"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityParticipantRemoved"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"participant"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityCallStarted"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"callId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityUnknownAction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"tag"}},{"kind":"Field","name":{"kind":"Name","value":"payload"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"EntityActivityFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"activity"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ActivityEventFields"}}]}}]}}]} as unknown as DocumentNode<EntityActivityQuery, EntityActivityQueryVariables>;
export const DatabaseActivityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"DatabaseActivity"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"databaseId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"databaseActivity"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"databaseId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"databaseId"}}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ActivityEventFields"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ActivityEventFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"actorId"}},{"kind":"Field","name":{"kind":"Name","value":"subjectId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"occurredAt"}},{"kind":"Field","name":{"kind":"Name","value":"action"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityPropertyChanged"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"property"}},{"kind":"Field","name":{"kind":"Name","value":"from"}},{"kind":"Field","name":{"kind":"Name","value":"to"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityParticipantAdded"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"participant"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityParticipantRemoved"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"participant"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityCallStarted"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"callId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlActivityUnknownAction"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"tag"}},{"kind":"Field","name":{"kind":"Name","value":"payload"}}]}}]}}]}}]} as unknown as DocumentNode<DatabaseActivityQuery, DatabaseActivityQueryVariables>;
+export const AgentSessionLogDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"AgentSessionLog"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"sessionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"agentSession"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"sessionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"sessionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"log"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"bot"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"entries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"direction"}},{"kind":"Field","name":{"kind":"Name","value":"content"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<AgentSessionLogQuery, AgentSessionLogQueryVariables>;
export const AgentSessionMentionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"AgentSessionMentions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupAgentSession"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"bot"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<AgentSessionMentionsQuery, AgentSessionMentionsQueryVariables>;
export const RecordChannelActivityDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RecordChannelActivity"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"RecordChannelActivityInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordChannelActivity"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}}]}}]}}]} as unknown as DocumentNode<RecordChannelActivityMutation, RecordChannelActivityMutationVariables>;
export const UpdateNotificationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateNotifications"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateNotificationsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateNotifications"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationStateFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationNavigationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDocumentMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"documentMentionDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"documentMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMentionedInDocumentCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentMentionId"},"name":{"kind":"Name","value":"mentionId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"mentionedInDocumentCommentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlRepliedToDocumentCommentThreadMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"repliedToDocumentCommentThreadSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCommentedOnDocumentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentDocumentName"},"name":{"kind":"Name","value":"documentName"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentFileType"},"name":{"kind":"Name","value":"fileType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentCommentId"},"name":{"kind":"Name","value":"commentId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"commentedOnDocumentSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInitiativeDiscussionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionProjectName"},"name":{"kind":"Name","value":"projectName"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionReason"},"name":{"kind":"Name","value":"reason"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"initiativeDiscussionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCrmDiscussionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionRecordName"},"name":{"kind":"Name","value":"recordName"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionReason"},"name":{"kind":"Name","value":"reason"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionText"},"name":{"kind":"Name","value":"text"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"crmDiscussionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelInviteMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelInviteInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelInviteSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageReactionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionEmoji"},"name":{"kind":"Name","value":"emoji"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionChannelType"},"name":{"kind":"Name","value":"channelType"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageReactionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageId"},"name":{"kind":"Name","value":"messageId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyUserId"},"name":{"kind":"Name","value":"userId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyThreadParentSenderId"},"name":{"kind":"Name","value":"threadParentSenderId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelType"},"name":{"kind":"Name","value":"channelType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCallStartedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"callStartedChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"callStartedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNewEmailMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"newEmailSender"},"name":{"kind":"Name","value":"sender"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailToEmail"},"name":{"kind":"Name","value":"toEmail"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailThreadId"},"name":{"kind":"Name","value":"threadId"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSubject"},"name":{"kind":"Name","value":"subject"}},{"kind":"Field","alias":{"kind":"Name","value":"newEmailSnippet"},"name":{"kind":"Name","value":"snippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInboxReauthRequiredMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inboxReauthRequiredEmailAddress"},"name":{"kind":"Name","value":"emailAddress"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlInviteToTeamMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamName"},"name":{"kind":"Name","value":"teamName"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamTeamInviteId"},"name":{"kind":"Name","value":"teamInviteId"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamInvitedBy"},"name":{"kind":"Name","value":"invitedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamRole"},"name":{"kind":"Name","value":"role"}},{"kind":"Field","alias":{"kind":"Name","value":"inviteToTeamSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlTaskAssignedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskId"},"name":{"kind":"Name","value":"taskId"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedTaskName"},"name":{"kind":"Name","value":"taskName"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSubType"},"name":{"kind":"Name","value":"subType"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedAssignedBy"},"name":{"kind":"Name","value":"assignedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"taskAssignedSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"reminderReminderId"},"name":{"kind":"Name","value":"reminderId"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderDescription"},"name":{"kind":"Name","value":"description"}},{"kind":"Field","alias":{"kind":"Name","value":"reminderScheduledFor"},"name":{"kind":"Name","value":"scheduledFor"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCalendarEventReminderMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEventId"},"name":{"kind":"Name","value":"eventId"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderOccurrenceKey"},"name":{"kind":"Name","value":"occurrenceKey"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartsAt"},"name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderEndsAt"},"name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderStartDate"},"name":{"kind":"Name","value":"startDate"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderTimeZone"},"name":{"kind":"Name","value":"timeZone"}},{"kind":"Field","alias":{"kind":"Name","value":"calendarEventReminderMinutesBefore"},"name":{"kind":"Name","value":"minutesBefore"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAiResponseMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"aiResponseSummary"},"name":{"kind":"Name","value":"summary"}},{"kind":"Field","alias":{"kind":"Name","value":"aiResponseMessageId"},"name":{"kind":"Name","value":"messageId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrStatusChangedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedStatus"},"name":{"kind":"Name","value":"status"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedAction"},"name":{"kind":"Name","value":"action"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedPreviousStatus"},"name":{"kind":"Name","value":"previousStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedHeadBranch"},"name":{"kind":"Name","value":"headBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedBaseBranch"},"name":{"kind":"Name","value":"baseBranch"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrStatusChangedMergedAt"},"name":{"kind":"Name","value":"mergedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCheckRunMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckRunGithubId"},"name":{"kind":"Name","value":"checkRunGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckName"},"name":{"kind":"Name","value":"checkName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckStatus"},"name":{"kind":"Name","value":"checkStatus"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunConclusion"},"name":{"kind":"Name","value":"conclusion"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCheckUrl"},"name":{"kind":"Name","value":"checkUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCheckRunCompletedAt"},"name":{"kind":"Name","value":"completedAt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubReviewRequestedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubLogin"},"name":{"kind":"Name","value":"requestedReviewerGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubReviewRequestedRequestedReviewerGithubUserId"},"name":{"kind":"Name","value":"requestedReviewerGithubUserId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrCommentMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentKind"},"name":{"kind":"Name","value":"commentKind"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrCommentCommentSnippet"},"name":{"kind":"Name","value":"commentSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionLocation"},"name":{"kind":"Name","value":"location"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentGithubId"},"name":{"kind":"Name","value":"commentGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionCommentUrl"},"name":{"kind":"Name","value":"commentUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrMentionTextSnippet"},"name":{"kind":"Name","value":"textSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlGithubPrReviewMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewForeignEntityId"},"name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewGithubKey"},"name":{"kind":"Name","value":"githubKey"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewOwner"},"name":{"kind":"Name","value":"owner"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewRepo"},"name":{"kind":"Name","value":"repo"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewNumber"},"name":{"kind":"Name","value":"number"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewUrl"},"name":{"kind":"Name","value":"url"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewDisplayName"},"name":{"kind":"Name","value":"displayName"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewTitle"},"name":{"kind":"Name","value":"title"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubLogin"},"name":{"kind":"Name","value":"senderGithubLogin"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubUserId"},"name":{"kind":"Name","value":"senderGithubUserId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewSenderGithubAvatarUrl"},"name":{"kind":"Name","value":"senderGithubAvatarUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewGithubId"},"name":{"kind":"Name","value":"reviewGithubId"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewUrl"},"name":{"kind":"Name","value":"reviewUrl"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewState"},"name":{"kind":"Name","value":"state"}},{"kind":"Field","alias":{"kind":"Name","value":"githubPrReviewReviewSnippet"},"name":{"kind":"Name","value":"reviewSnippet"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionSettledMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledActor"},"name":{"kind":"Name","value":"actor"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledStopReason"},"name":{"kind":"Name","value":"stopReason"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionSettledExcerpt"},"name":{"kind":"Name","value":"excerpt"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionWaitingForInputMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputTurn"},"name":{"kind":"Name","value":"turn"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionWaitingForInputQuestion"},"name":{"kind":"Name","value":"question"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlAgentSessionMentionedMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedSession"},"name":{"kind":"Name","value":"session"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sessionId"}},{"kind":"Field","name":{"kind":"Name","value":"sessionName"}},{"kind":"Field","name":{"kind":"Name","value":"botId"}},{"kind":"Field","name":{"kind":"Name","value":"botName"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"announcementMessageId"}}]}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedMentionedBy"},"name":{"kind":"Name","value":"mentionedBy"}},{"kind":"Field","alias":{"kind":"Name","value":"agentSessionMentionedActionId"},"name":{"kind":"Name","value":"actionId"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotifEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationNavigationMetadataFields"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMentionMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMentionHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMentionSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelMessageSendMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendMessageContent"},"name":{"kind":"Name","value":"messageContent"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelMessageSendSenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlChannelReplyMetadata"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"channelReplyHasAttachments"},"name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderDisplayName"},"name":{"kind":"Name","value":"senderDisplayName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplyChannelName"},"name":{"kind":"Name","value":"channelName"}},{"kind":"Field","alias":{"kind":"Name","value":"channelReplySenderProfilePictureUrl"},"name":{"kind":"Name","value":"senderProfilePictureUrl"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationStateFields"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationMetadataFields"}}]}}]}}]} as unknown as DocumentNode<UpdateNotificationsMutation, UpdateNotificationsMutationVariables>;
diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.toml
index e85a7b2540..b6bb176d72 100644
--- a/crates/complete_graph/Cargo.toml
+++ b/crates/complete_graph/Cargo.toml
@@ -5,9 +5,12 @@ publish = false
version = "0.1.0"
[dependencies]
+serde_json = { workspace = true }
+chrono = { workspace = true }
anyhow = { workspace = true }
async-graphql = { workspace = true, features = ["dataloader"] }
axum = { workspace = true }
+agent_session = { path = "../agent_session", default-features = false }
bots = { path = "../bots", default-features = false, features = ["ports"] }
email = { path = "../email", default-features = false, features = [
"axum",
diff --git a/crates/complete_graph/src/edges.rs b/crates/complete_graph/src/edges.rs
index 6179bd7413..032308a05e 100644
--- a/crates/complete_graph/src/edges.rs
+++ b/crates/complete_graph/src/edges.rs
@@ -1,6 +1,10 @@
use std::{collections::HashMap, future::Future, marker::PhantomData, pin::Pin, sync::Arc};
-use async_graphql::{Context, ID, Object, SimpleObject, dataloader::DataLoader};
+use agent_session::domain::{
+ model::{AgentSessionId, SessionBot, StoredAgentSessionLog},
+ ports::{AgentSessionLogRepo, AgentSessionRepo},
+};
+use async_graphql::{Context, ID, Json, Object, SimpleObject, dataloader::DataLoader};
use bots::domain::{
models::{BotId, BotProfile},
ports::BotRepo,
@@ -123,8 +127,9 @@ where
SoupInitiativeEdges { initiative_id }
}
- fn agent_session_edges(bot_id: Uuid) -> Self::AgentSessionEdges {
+ fn agent_session_edges(session_id: Uuid, bot_id: Uuid) -> Self::AgentSessionEdges {
SoupAgentSessionEdges {
+ session_id: AgentSessionId::new_from_uuid(session_id),
bot_id: BotId::new_from_uuid(bot_id),
}
}
@@ -245,14 +250,16 @@ where
)
}
-/// Agent-session-specific fields composed from the bots domain.
+/// Agent-session-specific fields composed from the bots and agent-session domains.
#[derive(Clone)]
pub struct SoupAgentSessionEdges {
+ /// The session itself, for its log.
+ session_id: AgentSessionId,
/// Bot referenced by the session.
bot_id: BotId,
}
-/// Bot fields attached only to a Soup agent session.
+/// Bot and log fields attached only to a Soup agent session.
#[Object]
impl SoupAgentSessionEdges {
/// The bot running this session, when its profile still exists.
@@ -264,6 +271,181 @@ impl SoupAgentSessionEdges {
.map_err(|error| async_graphql::Error::new(error.to_string()))?;
Ok(profile.map(Into::into))
}
+
+ /// The session's raw protocol log: what the client folds into messages.
+ /// Served whole, in log order, the same rows the harness's REST log
+ /// endpoint serves.
+ async fn log(&self, ctx: &Context<'_>) -> async_graphql::Result<GraphqlAgentSessionLog> {
+ let loader = ctx.data::<AgentSessionLogDataLoader>()?;
+ loader
+ .load_one(self.session_id)
+ .await
+ .map_err(|error| async_graphql::Error::new(error.to_string()))?
+ .ok_or_else(|| async_graphql::Error::new("agent session log is unavailable"))
+ }
+}
+
+/// One session's raw protocol log and the agent whose messages it derives.
+#[derive(Clone, SimpleObject)]
+pub struct GraphqlAgentSessionLog {
+ /// The bot the session runs as: the sender of every agent message.
+ bot: GraphqlAgentSessionLogBot,
+ /// Effective history in ascending `(createdAt, id)` order. The first row
+ /// is the inclusive history boundary; a reader reconciles overlap by id.
+ entries: Vec<GraphqlAgentSessionLogEntry>,
+}
+
+/// The bot as the log's reader needs it, handle included.
+#[derive(Clone, SimpleObject)]
+pub struct GraphqlAgentSessionLogBot {
+ /// The bot's id. A message it sent has `"bot|{id}"` as its sender.
+ id: ID,
+ /// Display name.
+ name: String,
+ /// Stable `@` handle, without a leading `@`.
+ handle: String,
+ /// Avatar, when it has one.
+ avatar_url: Option<String>,
+}
+
+impl From<SessionBot> for GraphqlAgentSessionLogBot {
+ fn from(bot: SessionBot) -> Self {
+ Self {
+ id: ID(bot.id.to_string()),
+ name: bot.name,
+ handle: bot.handle,
+ avatar_url: bot.avatar_url,
+ }
+ }
+}
+
+/// One logged frame, in the shape the fold reads: the transport row's
+/// identity and time beside the frame's own `direction` and `content`.
+#[derive(Clone, SimpleObject)]
+pub struct GraphqlAgentSessionLogEntry {
+ /// Durable transport row identity; with `createdAt`, its order cursor.
+ id: ID,
+ /// When the log recorded the frame.
+ created_at: String,
+ /// The user whose action produced the frame, absent when no user did.
+ user_id: Option<String>,
+ /// Which way the frame travelled: `to_server` or `to_runtime`.
+ direction: String,
+ /// The protocol envelope, verbatim.
+ content: Json<serde_json::Value>,
+}
+
+impl TryFrom<StoredAgentSessionLog> for GraphqlAgentSessionLogEntry {
+ type Error = anyhow::Error;
+
+ fn try_from(stored: StoredAgentSessionLog) -> Result<Self, Self::Error> {
+ // Serialized by the fold's own log type so the wire shape cannot
+ // drift from what the fold reads back; split into the two fields
+ // the schema names.
+ let serde_json::Value::Object(mut frame) = serde_json::to_value(&stored.entry.content)?
+ else {
+ anyhow::bail!("a logged frame did not serialize to an object");
+ };
+ let direction = match frame.remove("direction") {
+ Some(serde_json::Value::String(direction)) => direction,
+ _ => anyhow::bail!("a logged frame has no direction"),
+ };
+ let content = frame
+ .remove("content")
+ .ok_or_else(|| anyhow::anyhow!("a logged frame has no content"))?;
+ Ok(Self {
+ id: ID(stored.id.to_string()),
+ created_at: stored
+ .created_at
+ .to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true),
+ user_id: stored.entry.user_id.map(|user| user.to_string()),
+ direction,
+ content: Json(content),
+ })
+ }
+}
+
+/// Owned future returned by the erased session-log batch reader.
+type AgentSessionLogBatchFuture = Pin<
+ Box<
+ dyn Future<
+ Output = Result<
+ HashMap<AgentSessionId, GraphqlAgentSessionLog>,
+ Arc<anyhow::Error>,
+ >,
+ > + Send
+ + 'static,
+ >,
+>;
+
+/// Type-erased batch reader kept in the concrete GraphQL DataLoader.
+type AgentSessionLogBatchReader =
+ dyn Fn(Vec<AgentSessionId>) -> AgentSessionLogBatchFuture + Send + Sync + 'static;
+
+/// DataLoader implementation for agent-session logs.
+pub struct AgentSessionLogLoader {
+ /// Erased agent-session repository call.
+ load_batch: Arc<AgentSessionLogBatchReader>,
+}
+
+impl async_graphql::dataloader::Loader<AgentSessionId> for AgentSessionLogLoader {
+ type Value = GraphqlAgentSessionLog;
+ type Error = Arc<anyhow::Error>;
+
+ async fn load(
+ &self,
+ keys: &[AgentSessionId],
+ ) -> Result<HashMap<AgentSessionId, Self::Value>, Self::Error> {
+ (self.load_batch)(keys.to_vec()).await
+ }
+}
+
+/// Concrete request-scoped DataLoader for agent-session logs.
+pub type AgentSessionLogDataLoader = DataLoader<AgentSessionLogLoader>;
+
+/// Build a request-scoped DataLoader over the agent-session repository. One
+/// request rarely asks for more than one log, so the batch is a loop; the
+/// loader is for request-scoped memoization, not for batching.
+pub fn agent_session_log_loader<R>(repo: R) -> AgentSessionLogDataLoader
+where
+ R: AgentSessionRepo + AgentSessionLogRepo + Clone,
+{
+ let load_batch = move |session_ids: Vec<AgentSessionId>| {
+ let repo = repo.clone();
+ Box::pin(async move {
+ let mut logs = HashMap::with_capacity(session_ids.len());
+ for session_id in session_ids {
+ let session = AgentSessionRepo::get(&repo, session_id)
+ .await
+ .map_err(|error| Arc::new(anyhow::Error::new(error)))?;
+ let bot = repo
+ .session_bot(session.bot_id)
+ .await
+ .map_err(|error| Arc::new(anyhow::Error::new(error)))?;
+ let entries = AgentSessionLogRepo::list_by_session(&repo, session_id)
+ .await
+ .map_err(|error| Arc::new(anyhow::Error::new(error)))?
+ .into_iter()
+ .map(GraphqlAgentSessionLogEntry::try_from)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(Arc::new)?;
+ logs.insert(
+ session_id,
+ GraphqlAgentSessionLog {
+ bot: bot.into(),
+ entries,
+ },
+ );
+ }
+ Ok(logs)
+ }) as AgentSessionLogBatchFuture
+ };
+ DataLoader::new(
+ AgentSessionLogLoader {
+ load_batch: Arc::new(load_batch),
+ },
+ tokio::spawn,
+ )
}
/// Cross-domain fields attached to a property-bearing Soup entity.
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index 9995658b48..b6ebfae0df 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -14,7 +14,7 @@ mod sdl_test;
pub use edges::{
AgentSessionBotDataLoader, AgentSessionBotLoader, GraphqlSessionBot, SoupAgentSessionEdges,
- SoupEdges, SoupEmailThreadEdges, agent_session_bot_loader,
+ SoupEdges, SoupEmailThreadEdges, agent_session_bot_loader, agent_session_log_loader,
};
pub use graphql_activity::{
ActivityEdgeKey, ActivityEdgeLoad, ActivityFeedInput, ActivityFeedReader,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index a90a7870f8..d31e23e3a7 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -48,9 +48,10 @@ use graphql_properties::{
};
use graphql_scheduled_action::{GraphqlScheduledAction, resolve_scheduled_actions};
use graphql_soup::{
- GraphqlSoupEmailThread, GraphqlSoupInitiative, GroupedSoup, GroupedSoupInput,
- SoupEmailThreadMutationOutput, SoupEntityEdges, SoupInput, SoupPage, SoupPatch,
- resolve_grouped_soup, resolve_soup, resolve_soup_email_thread, resolve_soup_updates,
+ GraphqlSoupAgentSession, GraphqlSoupEmailThread, GraphqlSoupInitiative, GroupedSoup,
+ GroupedSoupInput, SoupEmailThreadMutationOutput, SoupEntityEdges, SoupInput, SoupPage,
+ SoupPatch, resolve_grouped_soup, resolve_soup, resolve_soup_agent_session,
+ resolve_soup_email_thread, resolve_soup_updates,
};
use macro_authorization::{
InternalAuthConfig, MacroAuthorizationService, MacroAuthorizationServiceImpl,
@@ -752,6 +753,23 @@ where
.await
}
+ /// Fetch one accessible agent session by id, with its protocol log
+ /// reachable through `log`.
+ async fn agent_session(
+ &self,
+ ctx: &Context<'_>,
+ session_id: ID,
+ ) -> async_graphql::Result<Option<GraphqlSoupAgentSession<SoupEdges<NR, PR, ER, FR, AR, AcR>>>>
+ {
+ let session_id = parse_id(session_id, "sessionId")?;
+ resolve_soup_agent_session::<SoupEdges<NR, PR, ER, FR, AR, AcR>>(
+ ctx,
+ self.user_id.clone(),
+ session_id,
+ )
+ .await
+ }
+
/// Fetch Soup items nested into grouping bins.
async fn group_soup(
&self,
diff --git a/crates/graphql_entity_mutation/src/mutations/test.rs b/crates/graphql_entity_mutation/src/mutations/test.rs
index 5c139905a2..ebf24a0e25 100644
--- a/crates/graphql_entity_mutation/src/mutations/test.rs
+++ b/crates/graphql_entity_mutation/src/mutations/test.rs
@@ -62,7 +62,10 @@ impl SoupEntityEdges for TestSoupEdges {
Ok(None)
}
- fn agent_session_edges(_bot_id: uuid::Uuid) -> Self::AgentSessionEdges {
+ fn agent_session_edges(
+ _session_id: uuid::Uuid,
+ _bot_id: uuid::Uuid,
+ ) -> Self::AgentSessionEdges {
TestAgentSessionEdges { available: true }
}
diff --git a/crates/graphql_favorite/src/mutations/test.rs b/crates/graphql_favorite/src/mutations/test.rs
index ca40dceed9..97f9ed7051 100644
--- a/crates/graphql_favorite/src/mutations/test.rs
+++ b/crates/graphql_favorite/src/mutations/test.rs
@@ -66,7 +66,7 @@ impl SoupEntityEdges for TestSoupEdges {
Ok(None)
}
- fn agent_session_edges(_bot_id: Uuid) -> Self::AgentSessionEdges {
+ fn agent_session_edges(_session_id: Uuid, _bot_id: Uuid) -> Self::AgentSessionEdges {
TestAgentSessionEdges { available: true }
}
diff --git a/crates/graphql_initiative/src/test.rs b/crates/graphql_initiative/src/test.rs
index 21d84319ae..89e7724084 100644
--- a/crates/graphql_initiative/src/test.rs
+++ b/crates/graphql_initiative/src/test.rs
@@ -110,7 +110,10 @@ impl SoupEntityEdges for TestSoupEdges {
Ok(None)
}
- fn agent_session_edges(_bot_id: uuid::Uuid) -> Self::AgentSessionEdges {
+ fn agent_session_edges(
+ _session_id: uuid::Uuid,
+ _bot_id: uuid::Uuid,
+ ) -> Self::AgentSessionEdges {
TestAgentSessionEdges { available: true }
}
diff --git a/crates/graphql_soup/src/lib.rs b/crates/graphql_soup/src/lib.rs
index 97b9685b2a..081b1e8123 100644
--- a/crates/graphql_soup/src/lib.rs
+++ b/crates/graphql_soup/src/lib.rs
@@ -27,14 +27,14 @@ pub use mutation_thread::{
EmailMutationThreadLoader, EmailMutationThreadReader, email_mutation_thread_loader,
};
pub use objects::{
- GraphqlSoupBin, GraphqlSoupCall, GraphqlSoupChannel, GraphqlSoupChannelMessage,
- GraphqlSoupChannelMessagePreview, GraphqlSoupChat, GraphqlSoupCrmCompany,
- GraphqlSoupDatabaseRow, GraphqlSoupDocument, GraphqlSoupDocumentSubType,
+ GraphqlSoupAgentSession, GraphqlSoupBin, GraphqlSoupCall, GraphqlSoupChannel,
+ GraphqlSoupChannelMessage, GraphqlSoupChannelMessagePreview, GraphqlSoupChat,
+ GraphqlSoupCrmCompany, GraphqlSoupDatabaseRow, GraphqlSoupDocument, GraphqlSoupDocumentSubType,
GraphqlSoupEmailThread, GraphqlSoupEntity, GraphqlSoupForeignEntity, GraphqlSoupInitiative,
GraphqlSoupProject, GroupedSoup, SoupCacheProjection, SoupEntityEdges, SoupPage, SoupPatch,
SoupUpdated,
};
pub use resolvers::{
- SoupEmailThreadMutationOutput, resolve_grouped_soup, resolve_soup, resolve_soup_email_thread,
- resolve_soup_updates,
+ SoupEmailThreadMutationOutput, resolve_grouped_soup, resolve_soup, resolve_soup_agent_session,
+ resolve_soup_email_thread, resolve_soup_updates,
};
diff --git a/crates/graphql_soup/src/objects.rs b/crates/graphql_soup/src/objects.rs
index b630b78afe..53c9047101 100644
--- a/crates/graphql_soup/src/objects.rs
+++ b/crates/graphql_soup/src/objects.rs
@@ -112,7 +112,7 @@ pub trait SoupEntityEdges: ObjectType + Clone + Send + Sync + 'static {
type AgentSessionEdges: ObjectType + Clone + Send + Sync + 'static;
/// Construct the agent-session-specific edge object.
- fn agent_session_edges(bot_id: Uuid) -> Self::AgentSessionEdges;
+ fn agent_session_edges(session_id: Uuid, bot_id: Uuid) -> Self::AgentSessionEdges;
/// Resolve properties assigned to this entity.
fn resolve_properties(
@@ -1228,7 +1228,7 @@ where
#[graphql(flatten)]
/// Fields hydrated through the bot domain.
async fn agent_session_edges(&self) -> E::AgentSessionEdges {
- E::agent_session_edges(self.0.bot_id)
+ E::agent_session_edges(self.0.id, self.0.bot_id)
}
/// The runtime snapshotted when the session was created.
diff --git a/crates/graphql_soup/src/resolvers.rs b/crates/graphql_soup/src/resolvers.rs
index fe7dd70e34..8bff7c8d9f 100644
--- a/crates/graphql_soup/src/resolvers.rs
+++ b/crates/graphql_soup/src/resolvers.rs
@@ -25,8 +25,8 @@ use crate::{
inputs::{GroupedSoupInput, SoupInput},
loaders::SoupItemDataLoader,
objects::{
- GraphqlSoupEmailThread, GraphqlSoupEntity, GroupedSoup, SoupEntityEdges, SoupPage,
- SoupPatch,
+ GraphqlSoupAgentSession, GraphqlSoupEmailThread, GraphqlSoupEntity, GroupedSoup,
+ SoupEntityEdges, SoupPage, SoupPatch,
},
};
@@ -125,6 +125,31 @@ where
}
}
+/// Fetch one agent session the viewer can see, through the same access-
+/// filtered loader the Soup list uses, so a session outside their grants
+/// reads as absent rather than as an error.
+pub async fn resolve_soup_agent_session<Edges>(
+ ctx: &Context<'_>,
+ user_id: MacroUserIdStr<'static>,
+ session_id: uuid::Uuid,
+) -> async_graphql::Result<Option<GraphqlSoupAgentSession<Edges>>>
+where
+ Edges: SoupEntityEdges,
+{
+ let loader = ctx.data::<SoupItemDataLoader>()?;
+ let entity = EntityType::AgentSession.with_entity_string(session_id.to_string());
+ let Some(item) = loader.load_one((user_id, entity)).await? else {
+ return Ok(None);
+ };
+
+ match GraphqlSoupEntity::<Edges>::new_with_projection(item) {
+ GraphqlSoupEntity::AgentSession(session) => Ok(Some(session)),
+ _ => Err(async_graphql::Error::new(
+ "Soup returned a non-agent-session entity for an agent-session request",
+ )),
+ }
+}
+
/// Mutation-output adapter that reloads the canonical Soup email-thread object.
pub struct SoupEmailThreadMutationOutput<Edges>(PhantomData<fn() -> Edges>);
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index 2f513b2424..4ff7833305 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -1,4 +1,5 @@
use crate::api::context::{ApiContext, AuthorizationService};
+use agent_session::outbound::postgres::PgAgentSessionRepo;
use async_graphql::{
Data,
http::{ALL_WEBSOCKET_PROTOCOLS, GraphiQLSource},
@@ -14,6 +15,8 @@ use axum::{
use axum_extra::extract::Cached;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use complete_graph::GraphqlRequestParts;
+use entity_registry::OwnerGrantPolicy;
+use entity_registry_db_utils::OwnedEntityRegistrar;
use graphql_soup::{email_mutation_thread_loader, soup_item_loader};
use macro_authorization::{
OptionalMacroAuthorizationExtractor, UserOrInternalService, UserOrInternalServiceAuthorization,
@@ -189,6 +192,14 @@ fn insert_graphql_context_data(
data.insert(complete_graph::agent_session_bot_loader(PgBotsRepo::new(
state.readonly_db.0.clone(),
)));
+ data.insert(complete_graph::agent_session_log_loader(
+ PgAgentSessionRepo::new(
+ state.readonly_db.0.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(
+ state.readonly_db.0.clone(),
+ ))),
+ ),
+ ));
data.insert(complete_graph::entity_properties_loader(
macro_user_id.clone(),
property_reader,
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 2a3b76e38e..28a9d5bc49 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -741,6 +741,70 @@ input GraphqlAgentSessionLiteral @oneOf {
owner: String
}
+"""
+One session's raw protocol log and the agent whose messages it derives.
+"""
+type GraphqlAgentSessionLog {
+ """
+ The bot the session runs as: the sender of every agent message.
+ """
+ bot: GraphqlAgentSessionLogBot!
+ """
+ Effective history in ascending `(createdAt, id)` order. The first row
+ is the inclusive history boundary; a reader reconciles overlap by id.
+ """
+ entries: [GraphqlAgentSessionLogEntry!]!
+}
+
+"""
+The bot as the log's reader needs it, handle included.
+"""
+type GraphqlAgentSessionLogBot {
+ """
+ The bot's id. A message it sent has `"bot|{id}"` as its sender.
+ """
+ id: ID!
+ """
+ Display name.
+ """
+ name: String!
+ """
+ Stable `@` handle, without a leading `@`.
+ """
+ handle: String!
+ """
+ Avatar, when it has one.
+ """
+ avatarUrl: String
+}
+
+"""
+One logged frame, in the shape the fold reads: the transport row's
+identity and time beside the frame's own `direction` and `content`.
+"""
+type GraphqlAgentSessionLogEntry {
+ """
+ Durable transport row identity; with `createdAt`, its order cursor.
+ """
+ id: ID!
+ """
+ When the log recorded the frame.
+ """
+ createdAt: String!
+ """
+ The user whose action produced the frame, absent when no user did.
+ """
+ userId: String
+ """
+ Which way the frame travelled: `to_server` or `to_runtime`.
+ """
+ direction: String!
+ """
+ The protocol envelope, verbatim.
+ """
+ content: JSON!
+}
+
"""
Metadata for being named in a prompt to an agent session.
"""
@@ -5008,6 +5072,12 @@ type GraphqlSoupAgentSession implements GraphqlSoupEntity {
"""
bot: GraphqlSessionBot
"""
+ The session's raw protocol log: what the client folds into messages.
+ Served whole, in log order, the same rows the harness's REST log
+ endpoint serves.
+ """
+ log: GraphqlAgentSessionLog!
+ """
The runtime snapshotted when the session was created.
"""
harness: String!
@@ -7155,6 +7225,11 @@ type GraphqlUser {
"""
emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread
"""
+ Fetch one accessible agent session by id, with its protocol log
+ reachable through `log`.
+ """
+ agentSession(sessionId: ID!): GraphqlSoupAgentSession
+ """
Fetch Soup items nested into grouping bins.
"""
groupSoup(input: GroupedSoupInput!): GroupedSoup!