An open-source, faster Devin alternative
TypeScript
dashboard: project Memory tab and session memory bindings
Igor Zalutski8169c86c8b07
diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 3e04a332..e505a560 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -76,7 +76,7 @@ const API_BASE = '/api/dashboard'// dev (catches schema/backend drift during dev + against the preview mock), but// in prod falls back to the raw data so a slightly-off schema can't take a// screen down. Tighten to always-throw once the schemas are proven in prod.-function validate<T>(+export function validate<T>(schema: z.ZodType<T> | undefined,data: unknown,path: string,@@ -131,20 +131,13 @@ function errorDetails(body: unknown): Record<string, unknown> | undefined {: undefined}-export async function apiFetch<T>(+// The authenticated request with error normalization, returning the raw+// Response for callers that need headers (a memory document's ETag) as well+// as the body. `apiFetch` is the JSON-and-schema layer over it.+export async function apiFetchResponse(path: string,options: RequestInit = {},- schema?: z.ZodType<T>,-): Promise<T> {- // Opt-in, dev-only preview mode: serve canned data with no backend/auth so- // the dashboard can be rendered locally (VITE_PREVIEW=1 npm run dev). Require- // the exact value '1' so VITE_PREVIEW=0 / false don't accidentally serve- // mocks; the dynamic import keeps the mock out of normal builds.- if (import.meta.env.VITE_PREVIEW === '1') {- const { mockFetch } = await import('./mock')- return validate(schema, await mockFetch<unknown>(path, options), path)- }-+): Promise<Response> {const res = await fetch(`${API_BASE}${path}`, {...options,credentials: 'include',@@ -169,6 +162,24 @@ export async function apiFetch<T>(errorDetails(body),)}+ return res+}++export async function apiFetch<T>(+ path: string,+ options: RequestInit = {},+ schema?: z.ZodType<T>,+): Promise<T> {+ // Opt-in, dev-only preview mode: serve canned data with no backend/auth so+ // the dashboard can be rendered locally (VITE_PREVIEW=1 npm run dev). Require+ // the exact value '1' so VITE_PREVIEW=0 / false don't accidentally serve+ // mocks; the dynamic import keeps the mock out of normal builds.+ if (import.meta.env.VITE_PREVIEW === '1') {+ const { mockFetch } = await import('./mock')+ return validate(schema, await mockFetch<unknown>(path, options), path)+ }++ const res = await apiFetchResponse(path, options)if (res.status === 204) {return undefined as Tdiff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex a5032af1..e249ed40 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -76,6 +76,7 @@ import { ManagedTwilioWizard } from './TwilioWizard'import { ManagedAgentOutboxes } from './Outboxes'import { ManagedAgentSchedules } from './Schedules'import { ManagedAgentWebhooks } from './Webhooks'+import { ManagedProjectMemory } from './Memory'import { ManagedProjectBYOK } from './BYOK'import { AgentMarkdown } from './AgentMarkdown'import {@@ -91,6 +92,7 @@ type DetailTab =| 'outboxes'| 'schedules'| 'webhooks'+ | 'memory'| 'secrets'| 'byok'@@ -513,6 +515,7 @@ export default function ManagedAgentDetail({'outboxes','schedules','webhooks',+ 'memory','secrets','byok',])@@ -700,6 +703,7 @@ export default function ManagedAgentDetail({...(project ? ([{ id: 'outboxes', label: 'Outboxes' }] as const) : []),...(project ? ([{ id: 'schedules', label: 'Schedules' }] as const) : []),...(project ? ([{ id: 'webhooks', label: 'Webhooks' }] as const) : []),+ ...(project ? ([{ id: 'memory', label: 'Memory' }] as const) : []),...(project ? ([{ id: 'secrets', label: 'Secrets' }] as const) : []),...(project ? ([{ id: 'byok', label: 'BYOK' }] as const) : []),]@@ -1170,6 +1174,25 @@ export default function ManagedAgentDetail({/>) : null}+ {activeTab === 'memory' && project ? (+ <ManagedProjectMemory+ key={environment}+ projectId={project.project.id}+ environment={environment}+ deploymentIds={[+ ...new Set(+ project.project.environments+ .filter((candidate) => candidate.name === environment)+ .flatMap((candidate) =>+ candidate.activeDeploymentId+ ? [candidate.activeDeploymentId]+ : [],+ ),+ ),+ ]}+ />+ ) : null}+{activeTab === 'secrets' && project ? (<ManagedProjectSecretsprojectId={project.project.id}diff --git a/web/src/managed-agents/Memory.tsx b/web/src/managed-agents/Memory.tsxnew file mode 100644index 00000000..e1e2f784--- /dev/null+++ b/web/src/managed-agents/Memory.tsx@@ -0,0 +1,787 @@+import { useState } from 'react'+import {+ useInfiniteQuery,+ useMutation,+ useQueries,+ useQueryClient,+} from '@tanstack/react-query'+import { Link } from 'react-router-dom'+import { BookOpen, Download, Loader2, Plus } from 'lucide-react'+import { ApiError } from '@/api/client'+import { ConfirmDialog } from '@/components/confirm-dialog'+import { EmptyState } from '@/components/empty-state'+import { Field, Select, Textarea } from '@/components/form'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelFooter,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { ResourceTable, type Column } from '@/components/resource-table'+import { StatusBadge } from '@/components/status-badge'+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'+import { Badge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Switch } from '@/components/ui/switch'+import { notifyError, notifySuccess } from '@/lib/errors'+import {+ createManagedMemoryDocument,+ deleteManagedMemoryDocument,+ getManagedAgentDeployment,+ getManagedMemoryDocument,+ getManagedMemoryDocuments,+ patchManagedMemoryDocument,+ replaceManagedMemoryDocument,+ type ManagedMemoryDocument,+ type ManagedMemoryDocumentMeta,+ type ManagedMemoryDocumentRead,+ type ManagedMemoryEnvironment,+} from './api'+import {+ declaredMemoryResources,+ formatMemoryBytes,+ isOverMemoryLimit,+ memoryExportFile,+ memoryWriterLabel,+} from './memory-documents'++function formatDate(value: string) {+ return new Date(value).toLocaleString()+}++const DOCUMENT_ID = /^[A-Za-z0-9_-]{1,128}$/++function WriterCell({+ projectId,+ document,+}: {+ projectId: string+ document: ManagedMemoryDocumentMeta+}) {+ if (document.writer.kind === 'agent') {+ return (+ <Link+ className="text-xs underline-offset-4 hover:underline"+ to={`/projects/${encodeURIComponent(projectId)}/sessions/${encodeURIComponent(document.writer.sessionId)}`}+ >+ {memoryWriterLabel(document.writer)}+ </Link>+ )+ }+ return <span className="text-xs">{memoryWriterLabel(document.writer)}</span>+}++// The editor holds the revision it read; a save that loses the race shows the+// current document instead of overwriting it (document-memory.mdx, "Conflicts").+type EditorState = {+ meta: ManagedMemoryDocumentMeta+ base: ManagedMemoryDocumentRead+ text: string+ summary: string+ conflict?: ManagedMemoryDocumentRead+}++export function ManagedProjectMemory({+ projectId,+ environment,+ deploymentIds,+}: {+ projectId: string+ environment: ManagedMemoryEnvironment+ /** Active deployments of this environment; their declarations name the resources. */+ deploymentIds: string[]+}) {+ const queryClient = useQueryClient()+ const deployments = useQueries({+ queries: deploymentIds.map((deploymentId) => ({+ queryKey: ['managed-agent-deployment', deploymentId],+ queryFn: () => getManagedAgentDeployment(deploymentId),+ })),+ })+ const declared = declaredMemoryResources(+ deployments.map((deployment) => deployment.data),+ )+ const [selectedResource, setSelectedResource] = useState<string>()+ const [customResource, setCustomResource] = useState('')+ const resource = selectedResource ?? declared[0]?.id+ const declaration = declared.find((candidate) => candidate.id === resource)+ const target = (id: string) => ({+ projectId,+ resource: resource ?? '',+ id,+ environment,+ })+ const listKey = ['managed-memory-documents', projectId, environment, resource]++ const documents = useInfiniteQuery({+ queryKey: listKey,+ initialPageParam: undefined as string | undefined,+ queryFn: ({ pageParam }) =>+ getManagedMemoryDocuments({+ projectId,+ resource: resource ?? '',+ environment,+ ...(pageParam ? { cursor: pageParam } : {}),+ }),+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,+ enabled: Boolean(resource),+ })+ const rows = documents.data?.pages.flatMap((page) => page.documents) ?? []++ const [creating, setCreating] = useState(false)+ const [draft, setDraft] = useState({+ id: '',+ title: '',+ summary: '',+ text: '',+ agentWrites: true,+ })+ const [editor, setEditor] = useState<EditorState>()+ const [removing, setRemoving] = useState<ManagedMemoryDocumentMeta>()++ const invalidate = () => queryClient.invalidateQueries({ queryKey: listKey })++ const create = useMutation({+ mutationFn: () =>+ createManagedMemoryDocument({+ ...target(draft.id.trim()),+ title: draft.title.trim(),+ text: draft.text,+ ...(draft.summary.trim() ? { summary: draft.summary.trim() } : {}),+ ...(draft.agentWrites ? {} : { agentWrites: 'disabled' as const }),+ }),+ onSuccess: async ({ document }) => {+ setCreating(false)+ setDraft({ id: '', title: '', summary: '', text: '', agentWrites: true })+ notifySuccess(`Created ${document.id}.`)+ await invalidate()+ },+ onError: (error) => notifyError("Couldn't create that document.", error),+ })++ const openEditor = useMutation({+ mutationFn: (meta: ManagedMemoryDocumentMeta) =>+ getManagedMemoryDocument(target(meta.id)),+ onSuccess: (base, meta) =>+ setEditor({+ meta,+ base,+ text: base.document.text,+ summary: base.document.summary,+ }),+ onError: (error) => notifyError("Couldn't open that document.", error),+ })++ const save = useMutation({+ mutationFn: async (state: EditorState) => {+ try {+ return await replaceManagedMemoryDocument({+ ...target(state.meta.id),+ etag: state.base.etag,+ text: state.text,+ summary: state.summary,+ })+ } catch (error) {+ if (error instanceof ApiError && error.status === 412) {+ const conflict = await getManagedMemoryDocument(target(state.meta.id))+ setEditor({ ...state, conflict })+ return undefined+ }+ throw error+ }+ },+ onSuccess: async (saved) => {+ if (!saved) return+ setEditor(undefined)+ notifySuccess(+ `Saved ${saved.document.id}.`,+ `Revision ${saved.document.revision}.`,+ )+ await invalidate()+ },+ onError: (error) => notifyError("Couldn't save that document.", error),+ })++ // Freeze and unfreeze read the document first so the precondition carries+ // the ETag verbatim rather than a revision reassembled from the list.+ const setAgentWrites = useMutation({+ mutationFn: async (input: {+ meta: ManagedMemoryDocumentMeta+ agentWrites: 'enabled' | 'disabled'+ }) => {+ const current = await getManagedMemoryDocument(target(input.meta.id))+ return patchManagedMemoryDocument({+ ...target(input.meta.id),+ etag: current.etag,+ agentWrites: input.agentWrites,+ })+ },+ onSuccess: async ({ document }) => {+ notifySuccess(+ document.agentWrites === 'disabled'+ ? `Agent writes disabled for ${document.id}.`+ : `Agent writes enabled for ${document.id}.`,+ )+ await invalidate()+ },+ onError: (error) =>+ notifyError("Couldn't change that document's policy.", error),+ })++ const remove = useMutation({+ mutationFn: async (meta: ManagedMemoryDocumentMeta) => {+ const current = await getManagedMemoryDocument(target(meta.id))+ await deleteManagedMemoryDocument({+ ...target(meta.id),+ etag: current.etag,+ })+ },+ onSuccess: async (_, meta) => {+ setRemoving(undefined)+ notifySuccess(`Deleted ${meta.id}.`, 'Its ID stays reserved.')+ await invalidate()+ },+ onError: (error) => notifyError("Couldn't delete that document.", error),+ })++ const exportResource = useMutation({+ mutationFn: async () => {+ if (!resource) return undefined+ const all: ManagedMemoryDocument[] = []+ let cursor: string | undefined+ do {+ const page = await getManagedMemoryDocuments({+ projectId,+ resource,+ environment,+ ...(cursor ? { cursor } : {}),+ })+ for (const meta of page.documents) {+ all.push((await getManagedMemoryDocument(target(meta.id))).document)+ }+ cursor = page.nextCursor ?? undefined+ } while (cursor)+ const file = memoryExportFile({+ resource,+ environment,+ documents: all,+ exportedAt: new Date(),+ })+ const url = URL.createObjectURL(+ new Blob([file.body], { type: 'application/json' }),+ )+ const anchor = document.createElement('a')+ anchor.href = url+ anchor.download = file.name+ anchor.click()+ URL.revokeObjectURL(url)+ return all.length+ },+ onSuccess: (count) => {+ if (count !== undefined) {+ notifySuccess(`Exported ${count} document${count === 1 ? '' : 's'}.`)+ }+ },+ onError: (error) => notifyError("Couldn't export that resource.", error),+ })++ const columns: Column<ManagedMemoryDocumentMeta>[] = [+ {+ key: 'document',+ header: 'Document',+ cell: (document) => (+ <div className="min-w-0">+ <p className="text-sm font-medium">{document.title}</p>+ <p className="text-muted-foreground mt-0.5 font-mono text-xs">+ {document.id}+ </p>+ {document.summary ? (+ <p className="text-muted-foreground mt-1 max-w-xl truncate text-xs">+ {document.summary}+ </p>+ ) : null}+ </div>+ ),+ },+ {+ key: 'size',+ header: 'Size',+ cell: (document) => (+ <div className="flex items-center gap-2">+ <span className="text-xs tabular-nums">+ {formatMemoryBytes(document.bytes)} /{' '}+ {formatMemoryBytes(document.maxBytes)}+ </span>+ {isOverMemoryLimit(document) ? (+ <Badge variant="destructive">Over limit</Badge>+ ) : null}+ </div>+ ),+ },+ {+ key: 'agent-writes',+ header: 'Agent writes',+ cell: (document) => (+ <StatusBadge+ status={document.agentWrites === 'enabled' ? 'active' : 'paused'}+ label={document.agentWrites === 'enabled' ? 'Enabled' : 'Frozen'}+ />+ ),+ },+ {+ key: 'writer',+ header: 'Last writer',+ cell: (document) => (+ <WriterCell projectId={projectId} document={document} />+ ),+ },+ {+ key: 'updated',+ header: 'Updated',+ cell: (document) => (+ <span className="text-muted-foreground text-xs">+ {formatDate(document.updatedAt)}+ </span>+ ),+ },+ {+ key: 'actions',+ header: '',+ align: 'right',+ cell: (document) => (+ <div className="flex justify-end gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={openEditor.isPending}+ onClick={() => openEditor.mutate(document)}+ >+ Edit+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={setAgentWrites.isPending}+ onClick={() =>+ setAgentWrites.mutate({+ meta: document,+ agentWrites:+ document.agentWrites === 'enabled' ? 'disabled' : 'enabled',+ })+ }+ >+ {document.agentWrites === 'enabled' ? 'Freeze' : 'Unfreeze'}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => setRemoving(document)}+ >+ Delete+ </Button>+ </div>+ ),+ },+ ]++ const draftIdValid = DOCUMENT_ID.test(draft.id.trim())+ const conflictWriter = editor?.conflict+ ? memoryWriterLabel(editor.conflict.document.writer)+ : undefined++ return (+ <>+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Memory</PanelTitle>+ <PanelDescription>+ Documents saved in {environment}, per resource. Owner edits use+ the same revision checks as agent saves.+ </PanelDescription>+ </div>+ <div className="flex gap-2">+ <Button+ size="sm"+ variant="outline"+ disabled={!resource || exportResource.isPending}+ onClick={() => exportResource.mutate()}+ >+ {exportResource.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <Download />+ )}+ Export+ </Button>+ <Button+ size="sm"+ disabled={!resource}+ onClick={() => setCreating(true)}+ >+ <Plus /> Create document+ </Button>+ </div>+ </PanelHeader>+ <PanelContent className="grid gap-4 md:grid-cols-[minmax(0,20rem)_1fr] md:items-end">+ <Field+ label="Resource"+ htmlFor="memory-resource"+ description={+ declaration?.description ||+ (declared.length+ ? undefined+ : 'No active deployment declares memory here; open a resource by ID.')+ }+ >+ {declared.length ? (+ <Select+ id="memory-resource"+ value={resource ?? ''}+ onValueChange={setSelectedResource}+ options={declared.map((candidate) => ({+ value: candidate.id,+ label: candidate.id,+ ...(candidate.provider.maxBytes+ ? { hint: formatMemoryBytes(candidate.provider.maxBytes) }+ : {}),+ }))}+ placeholder="Choose a resource"+ />+ ) : (+ <Input+ id="memory-resource"+ value={resource ?? ''}+ readOnly+ placeholder="No resource selected"+ />+ )}+ </Field>+ <form+ className="flex gap-2"+ onSubmit={(event) => {+ event.preventDefault()+ const next = customResource.trim()+ if (!next) return+ setSelectedResource(next)+ setCustomResource('')+ }}+ >+ <Input+ aria-label="Other resource ID"+ value={customResource}+ placeholder="Other resource ID"+ onChange={(event) => setCustomResource(event.target.value)}+ />+ <Button+ type="submit"+ variant="outline"+ disabled={!customResource.trim()}+ >+ Open+ </Button>+ </form>+ </PanelContent>+ {documents.isError ? (+ <PanelContent className="border-t">+ <EmptyState+ icon={BookOpen}+ title={`Couldn't load ${resource}`}+ description={+ documents.error instanceof Error+ ? documents.error.message+ : 'Try loading this resource again.'+ }+ />+ </PanelContent>+ ) : (+ <PanelContent className="border-t p-0">+ <ResourceTable+ columns={columns}+ rows={rows}+ rowKey={(document) => document.id}+ loading={Boolean(resource) && documents.isLoading}+ empty={+ <EmptyState+ icon={BookOpen}+ title={+ resource+ ? `No ${environment} documents in ${resource}`+ : 'Choose a resource'+ }+ description={+ resource+ ? 'Create one here or with `opencomputer memory create`. A session can only bind to a document that exists.'+ : 'Resources come from the deployment that declares them.'+ }+ />+ }+ />+ </PanelContent>+ )}+ {documents.hasNextPage ? (+ <PanelFooter>+ <Button+ size="sm"+ variant="outline"+ disabled={documents.isFetchingNextPage}+ onClick={() => void documents.fetchNextPage()}+ >+ {documents.isFetchingNextPage ? (+ <Loader2 className="animate-spin" />+ ) : null}+ Load more+ </Button>+ </PanelFooter>+ ) : null}+ </Panel>++ <Dialog open={creating} onOpenChange={setCreating}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Create document</DialogTitle>+ <DialogDescription>+ A new document in {resource} ({environment}). A deleted ID cannot+ be reused, so choose IDs deliberately.+ </DialogDescription>+ </DialogHeader>+ <div className="grid gap-4 sm:grid-cols-2">+ <Field+ label="Document ID"+ htmlFor="memory-create-id"+ required+ error={+ draft.id && !draftIdValid+ ? 'Letters, digits, - and _ only; up to 128 characters.'+ : undefined+ }+ >+ <Input+ id="memory-create-id"+ value={draft.id}+ maxLength={128}+ placeholder="workshop"+ onChange={(event) =>+ setDraft({ ...draft, id: event.target.value })+ }+ />+ </Field>+ <Field label="Title" htmlFor="memory-create-title" required>+ <Input+ id="memory-create-title"+ value={draft.title}+ maxLength={240}+ placeholder="Workshop requirements"+ onChange={(event) =>+ setDraft({ ...draft, title: event.target.value })+ }+ />+ </Field>+ </div>+ <Field+ label="Summary"+ htmlFor="memory-create-summary"+ description="Shown in collection overviews. Up to 240 bytes."+ >+ <Input+ id="memory-create-summary"+ value={draft.summary}+ maxLength={240}+ onChange={(event) =>+ setDraft({ ...draft, summary: event.target.value })+ }+ />+ </Field>+ <Field+ label="Text"+ htmlFor="memory-create-text"+ description={+ declaration?.provider.maxBytes+ ? `Up to ${formatMemoryBytes(declaration.provider.maxBytes)} of UTF-8.`+ : undefined+ }+ >+ <Textarea+ id="memory-create-text"+ className="min-h-40 font-mono text-xs"+ value={draft.text}+ onChange={(event) =>+ setDraft({ ...draft, text: event.target.value })+ }+ />+ </Field>+ <div className="flex items-center gap-3">+ <Switch+ id="memory-create-agent-writes"+ checked={draft.agentWrites}+ onCheckedChange={(checked) =>+ setDraft({ ...draft, agentWrites: checked })+ }+ />+ <Label htmlFor="memory-create-agent-writes">+ Allow agent writes+ </Label>+ </div>+ <DialogFooter>+ <Button variant="outline" onClick={() => setCreating(false)}>+ Cancel+ </Button>+ <Button+ disabled={+ !draftIdValid || !draft.title.trim() || create.isPending+ }+ onClick={() => create.mutate()}+ >+ {create.isPending ? <Loader2 className="animate-spin" /> : null}+ Create+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog+ open={Boolean(editor)}+ onOpenChange={(open) =>+ !open && !save.isPending && setEditor(undefined)+ }+ >+ <DialogContent className="max-w-3xl">+ <DialogHeader>+ <DialogTitle>Edit {editor?.meta.title}</DialogTitle>+ <DialogDescription>+ Replaces the text and summary of {editor?.meta.id} at revision{' '}+ <span className="font-mono">+ {editor?.base.document.revision}+ </span>+ . The title and write policy are separate actions.+ </DialogDescription>+ </DialogHeader>+ {editor?.conflict ? (+ <Alert variant="destructive">+ <AlertTitle>+ This document changed while you were editing+ </AlertTitle>+ <AlertDescription>+ <p>+ {conflictWriter} saved revision{' '}+ <span className="font-mono">+ {editor.conflict.document.revision}+ </span>{' '}+ at {formatDate(editor.conflict.document.updatedAt)}. Your+ draft was not saved. The current text is shown below;+ reconcile it into your draft, or discard your draft and start+ from the current version.+ </p>+ <Textarea+ aria-label="Current text"+ readOnly+ className="mt-2 min-h-32 font-mono text-xs"+ value={editor.conflict.document.text}+ />+ <div className="mt-2 flex gap-2">+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ editor.conflict &&+ setEditor({+ ...editor,+ base: editor.conflict,+ conflict: undefined,+ })+ }+ >+ Keep my draft on the current revision+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ editor.conflict &&+ setEditor({+ ...editor,+ base: editor.conflict,+ text: editor.conflict.document.text,+ summary: editor.conflict.document.summary,+ conflict: undefined,+ })+ }+ >+ Discard my draft+ </Button>+ </div>+ </AlertDescription>+ </Alert>+ ) : null}+ {editor ? (+ <>+ <Field label="Summary" htmlFor="memory-edit-summary">+ <Input+ id="memory-edit-summary"+ value={editor.summary}+ maxLength={240}+ onChange={(event) =>+ setEditor({ ...editor, summary: event.target.value })+ }+ />+ </Field>+ <Field+ label="Text"+ htmlFor="memory-edit-text"+ description={`${formatMemoryBytes(new TextEncoder().encode(editor.text).byteLength)} of ${formatMemoryBytes(editor.base.document.maxBytes)}.`}+ >+ <Textarea+ id="memory-edit-text"+ className="min-h-64 font-mono text-xs"+ value={editor.text}+ onChange={(event) =>+ setEditor({ ...editor, text: event.target.value })+ }+ />+ </Field>+ </>+ ) : null}+ <DialogFooter>+ <Button+ variant="outline"+ disabled={save.isPending}+ onClick={() => setEditor(undefined)}+ >+ Cancel+ </Button>+ <Button+ disabled={!editor || Boolean(editor.conflict) || save.isPending}+ onClick={() => editor && save.mutate(editor)}+ >+ {save.isPending ? <Loader2 className="animate-spin" /> : null}+ Save+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <ConfirmDialog+ open={Boolean(removing)}+ onOpenChange={(open) => !open && setRemoving(undefined)}+ title={`Delete ${removing?.id}?`}+ description="Removes the saved text and summary. The ID stays reserved and cannot be recreated; sessions bound to this document fail their next recall."+ confirmLabel="Delete document"+ destructive+ pending={remove.isPending}+ onConfirm={() => removing && remove.mutate(removing)}+ />+ </>+ )+}diff --git a/web/src/managed-agents/Session.tsx b/web/src/managed-agents/Session.tsxindex 4e1a9047..1a815be2 100644--- a/web/src/managed-agents/Session.tsx+++ b/web/src/managed-agents/Session.tsx@@ -134,6 +134,43 @@ export default function ManagedSessionDetail() {</Panel></div>+ {session.data.memory.length ? (+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>Memory</PanelTitle>+ <PanelDescription className="mt-1">+ Bindings fixed when the session was created. Writable means the+ session's save can commit right now.+ </PanelDescription>+ </div>+ </PanelHeader>+ <div className="divide-y text-sm">+ {session.data.memory.map((binding) => (+ <div+ key={`${binding.resource}:${binding.scope}:${binding.id ?? ''}`}+ className="flex flex-wrap items-center gap-x-4 gap-y-1 px-5 py-3"+ >+ <span className="font-mono text-xs">{binding.resource}</span>+ <span className="text-muted-foreground text-xs">+ {binding.scope === 'document'+ ? `document ${binding.id ?? ''}`+ : 'collection'}+ </span>+ <span className="text-muted-foreground text-xs">+ {binding.access}+ </span>+ <StatusBadge+ className="ml-auto"+ status={binding.writable ? 'active' : 'paused'}+ label={binding.writable ? 'Writable' : 'Read-only now'}+ />+ </div>+ ))}+ </div>+ </Panel>+ ) : null}+<divrole="tablist"aria-label="Session detail"diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex 4ced26dd..509ae306 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -1,5 +1,5 @@import { z } from 'zod'-import { apiFetch } from '@/api/client'+import { apiFetch, apiFetchResponse, validate } from '@/api/client'const agentSchema = z.object({id: z.string(),@@ -11,6 +11,19 @@ const agentSchema = z.object({updatedAt: z.string(),})+// A memory resource the deployment declares (docs/agents/document-memory.mdx).+const memoryDeclarationSchema = z.object({+ id: z.string(),+ description: z.string().optional().default(''),+ provider: z+ .object({+ kind: z.string().optional().default('document'),+ maxBytes: z.number().optional(),+ })+ .optional()+ .default({ kind: 'document' }),+})+const deploymentSchema = z.object({id: z.string(),agentId: z.string(),@@ -18,6 +31,7 @@ const deploymentSchema = z.object({channels: z.array(z.string()),connections: z.array(z.string()),createdAt: z.string(),+ memory: z.array(memoryDeclarationSchema).optional().default([]),projectDeployment: z.object({id: z.string(),@@ -491,10 +505,51 @@ const sessionSchema = z.object({}),).default([]),+ // Memory bindings fixed at session creation; `writable` is false once the+ // session ended or while the document's agent writes are disabled.+ memory: z+ .array(+ z.object({+ resource: z.string(),+ scope: z.enum(['document', 'collection']),+ id: z.string().optional(),+ access: z.enum(['read', 'read-write']),+ writable: z.boolean(),+ }),+ )+ .optional()+ .default([]),})const sessionsResponseSchema = z.object({ sessions: z.array(sessionSchema) })+// Project memory documents (docs/agents/document-memory.mdx, "Management API").+const memoryWriterSchema = z.union([+ z.object({ kind: z.literal('owner') }),+ z.object({ kind: z.literal('agent'), sessionId: z.string() }),+])++const memoryDocumentMetaSchema = z.object({+ id: z.string(),+ title: z.string(),+ summary: z.string(),+ agentWrites: z.enum(['enabled', 'disabled']),+ revision: z.string(),+ bytes: z.number(),+ maxBytes: z.number(),+ updatedAt: z.string(),+ writer: memoryWriterSchema,+})++const memoryDocumentSchema = memoryDocumentMetaSchema.extend({+ text: z.string(),+})++const memoryDocumentPageSchema = z.object({+ documents: z.array(memoryDocumentMetaSchema),+ nextCursor: z.string().nullable(),+})+const projectOverviewSchema = z.object({project: projectSchema,templateSource: z@@ -521,6 +576,16 @@ export type ManagedAgentEvent = z.infer<typeof eventSchema>export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>export type ManagedAgentModelRoute = z.infer<typeof modelRouteSchema>export type ManagedAgentSession = z.infer<typeof sessionSchema>+export type ManagedSessionMemoryBinding = ManagedAgentSession['memory'][number]+export type ManagedMemoryDeclaration = z.infer<typeof memoryDeclarationSchema>+export type ManagedMemoryDocumentMeta = z.infer<typeof memoryDocumentMetaSchema>+export type ManagedMemoryDocument = z.infer<typeof memoryDocumentSchema>+export type ManagedMemoryDocumentPage = z.infer<typeof memoryDocumentPageSchema>+/** A document with the ETag the next conditional request must send back verbatim. */+export type ManagedMemoryDocumentRead = {+ document: ManagedMemoryDocument+ etag: string+}export type ManagedAgentConnection = z.infer<typeof connectionSchema>export type ManagedAgentChannel = z.infer<typeof channelSchema>export type ManagedAgentOutbox = z.infer<typeof outboxSchema>@@ -1211,6 +1276,123 @@ export async function getManagedAgentSession(sessionId: string) {)}+export type ManagedMemoryEnvironment = 'development' | 'production'++type MemoryDocumentTarget = {+ projectId: string+ resource: string+ id: string+ environment: ManagedMemoryEnvironment+}++function memoryDocumentsPath(input: {+ projectId: string+ resource: string+ environment: ManagedMemoryEnvironment+ id?: string+ cursor?: string+}) {+ const query = new URLSearchParams({ environment: input.environment })+ if (input.cursor) query.set('cursor', input.cursor)+ return (+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}` ++ `/memory/${encodeURIComponent(input.resource)}/documents` ++ (input.id !== undefined ? `/${encodeURIComponent(input.id)}` : '') ++ `?${query.toString()}`+ )+}++// Reads and writes return the document with its ETag, which the next+// conditional request (If-Match) sends back verbatim.+async function memoryDocumentRequest(+ path: string,+ options: RequestInit,+): Promise<ManagedMemoryDocumentRead> {+ const response = await apiFetchResponse(path, options)+ const document = validate(memoryDocumentSchema, await response.json(), path)+ return { document, etag: response.headers.get('etag') ?? '' }+}++export async function getManagedMemoryDocuments(input: {+ projectId: string+ resource: string+ environment: ManagedMemoryEnvironment+ cursor?: string+}) {+ return apiFetch(+ memoryDocumentsPath(input),+ undefined,+ memoryDocumentPageSchema,+ )+}++export async function getManagedMemoryDocument(input: MemoryDocumentTarget) {+ return memoryDocumentRequest(memoryDocumentsPath(input), {})+}++export async function createManagedMemoryDocument(+ input: MemoryDocumentTarget & {+ title: string+ text: string+ summary?: string+ agentWrites?: 'enabled' | 'disabled'+ },+) {+ return memoryDocumentRequest(memoryDocumentsPath(input), {+ method: 'PUT',+ headers: { 'If-None-Match': '*' },+ body: JSON.stringify({+ title: input.title,+ text: input.text,+ ...(input.summary !== undefined ? { summary: input.summary } : {}),+ ...(input.agentWrites ? { agentWrites: input.agentWrites } : {}),+ }),+ })+}++export async function replaceManagedMemoryDocument(+ input: MemoryDocumentTarget & {+ etag: string+ text: string+ summary?: string+ },+) {+ return memoryDocumentRequest(memoryDocumentsPath(input), {+ method: 'PUT',+ headers: { 'If-Match': input.etag },+ body: JSON.stringify({+ text: input.text,+ ...(input.summary !== undefined ? { summary: input.summary } : {}),+ }),+ })+}++export async function patchManagedMemoryDocument(+ input: MemoryDocumentTarget & {+ etag: string+ title?: string+ agentWrites?: 'enabled' | 'disabled'+ },+) {+ return memoryDocumentRequest(memoryDocumentsPath(input), {+ method: 'PATCH',+ headers: { 'If-Match': input.etag },+ body: JSON.stringify({+ ...(input.title !== undefined ? { title: input.title } : {}),+ ...(input.agentWrites ? { agentWrites: input.agentWrites } : {}),+ }),+ })+}++export async function deleteManagedMemoryDocument(+ input: MemoryDocumentTarget & { etag: string },+) {+ return apiFetch<void>(memoryDocumentsPath(input), {+ method: 'DELETE',+ headers: { 'If-Match': input.etag },+ })+}+async function sleep(milliseconds: number) {await new Promise((resolve) => setTimeout(resolve, milliseconds))}diff --git a/web/src/managed-agents/memory-documents.test.ts b/web/src/managed-agents/memory-documents.test.tsnew file mode 100644index 00000000..d5790844--- /dev/null+++ b/web/src/managed-agents/memory-documents.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest'+import {+ declaredMemoryResources,+ formatMemoryBytes,+ isOverMemoryLimit,+ memoryExportFile,+ memoryWriterLabel,+} from './memory-documents'++const requirements = {+ id: 'requirements',+ description: 'Verified requirements.',+ provider: { kind: 'document', maxBytes: 8192 },+}++describe('declaredMemoryResources', () => {+ it('merges declarations across deployments by id, first wins, sorted', () => {+ expect(+ declaredMemoryResources([+ { memory: [{ ...requirements, id: 'notes' }, requirements] },+ undefined,+ {+ memory: [+ { ...requirements, description: 'A later duplicate.' },+ { ...requirements, id: 'budget' },+ ],+ },+ ]).map((declaration) => [declaration.id, declaration.description]),+ ).toEqual([+ ['budget', 'Verified requirements.'],+ ['notes', 'Verified requirements.'],+ ['requirements', 'Verified requirements.'],+ ])+ })+})++describe('document presentation', () => {+ it('marks a document over its resource limit', () => {+ expect(isOverMemoryLimit({ bytes: 8193, maxBytes: 8192 })).toBe(true)+ expect(isOverMemoryLimit({ bytes: 8192, maxBytes: 8192 })).toBe(false)+ })++ it('names the last writer', () => {+ expect(memoryWriterLabel({ kind: 'owner' })).toBe('Owner')+ expect(memoryWriterLabel({ kind: 'agent', sessionId: 'ses_1' })).toBe(+ 'Agent ses_1',+ )+ })++ it('formats sizes', () => {+ expect(formatMemoryBytes(33)).toBe('33 B')+ expect(formatMemoryBytes(8192)).toBe('8.0 KiB')+ })+})++describe('memoryExportFile', () => {+ it('names the file by resource and environment and keeps document fields', () => {+ const document = {+ id: 'workshop',+ title: 'Workshop requirements',+ text: 'Node.js 22.',+ summary: '',+ agentWrites: 'enabled' as const,+ revision: 'rev-1',+ bytes: 11,+ maxBytes: 8192,+ updatedAt: '2026-09-10T12:00:00.000Z',+ writer: { kind: 'owner' as const },+ }+ const file = memoryExportFile({+ resource: 'requirements',+ environment: 'development',+ documents: [document],+ exportedAt: new Date('2026-09-10T13:00:00.000Z'),+ })+ expect(file.name).toBe('memory-requirements-development.json')+ expect(JSON.parse(file.body)).toEqual({+ resource: 'requirements',+ environment: 'development',+ exportedAt: '2026-09-10T13:00:00.000Z',+ documents: [document],+ })+ expect(file.body.endsWith('\n')).toBe(true)+ })+})diff --git a/web/src/managed-agents/memory-documents.ts b/web/src/managed-agents/memory-documents.tsnew file mode 100644index 00000000..d7f8874e--- /dev/null+++ b/web/src/managed-agents/memory-documents.ts@@ -0,0 +1,69 @@+import type {+ ManagedMemoryDeclaration,+ ManagedMemoryDocument,+ ManagedMemoryDocumentMeta,+ ManagedMemoryEnvironment,+} from './api'++/**+ * The memory resources an environment's active deployments declare, merged by+ * id. Agents of one project share a resource by id, so the first declaration+ * seen describes it; a resource the documents list knows but no deployment+ * declares is still reachable by typing its id.+ */+export function declaredMemoryResources(+ deployments: ReadonlyArray<+ { memory: ManagedMemoryDeclaration[] } | undefined+ >,+): ManagedMemoryDeclaration[] {+ const byId = new Map<string, ManagedMemoryDeclaration>()+ for (const deployment of deployments) {+ for (const declaration of deployment?.memory ?? []) {+ if (!byId.has(declaration.id)) byId.set(declaration.id, declaration)+ }+ }+ return [...byId.values()].sort((left, right) =>+ left.id.localeCompare(right.id),+ )+}++/** A document larger than the resource's current limit must shrink on its next save. */+export function isOverMemoryLimit(+ document: Pick<ManagedMemoryDocumentMeta, 'bytes' | 'maxBytes'>,+) {+ return document.bytes > document.maxBytes+}++export function memoryWriterLabel(writer: ManagedMemoryDocumentMeta['writer']) {+ return writer.kind === 'agent' ? `Agent ${writer.sessionId}` : 'Owner'+}++export function formatMemoryBytes(bytes: number) {+ return bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} KiB` : `${bytes} B`+}++/**+ * One resource's export: the file name and body the Memory page downloads.+ * Each document carries the same fields as a document read, so the file+ * matches what `opencomputer memory export` writes per document.+ */+export function memoryExportFile(input: {+ resource: string+ environment: ManagedMemoryEnvironment+ documents: ManagedMemoryDocument[]+ exportedAt: Date+}) {+ return {+ name: `memory-${input.resource}-${input.environment}.json`,+ body: `${JSON.stringify(+ {+ resource: input.resource,+ environment: input.environment,+ exportedAt: input.exportedAt.toISOString(),+ documents: input.documents,+ },+ null,+ 2,+ )}\n`,+ }+}diff --git a/web/src/managed-agents/session-history.test.ts b/web/src/managed-agents/session-history.test.tsindex 6dc2a7d7..a414e6a6 100644--- a/web/src/managed-agents/session-history.test.ts+++ b/web/src/managed-agents/session-history.test.ts@@ -23,6 +23,7 @@ function deployment(channels: [],connections: [],createdAt: '2026-08-15T00:00:00.000Z',+ memory: [],}}@@ -37,6 +38,7 @@ function session(id: string, deploymentId: string): ManagedAgentSession {createdAt: '2026-08-15T00:00:00.000Z',updatedAt: '2026-08-15T00:00:00.000Z',turns: [],+ memory: [],}}