Skip to content

An open-source, faster Devin alternative

TypeScript

dashboard: the memory editor addresses the target it read; resources from the inventory

Igor Zalutski05e75035a824
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index e249ed40..50c8c903 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -1179,6 +1179,8 @@ export default function ManagedAgentDetail({
key={environment}
projectId={project.project.id}
environment={environment}
+ // One environment row per project agent: every member's active
+ // deployment there, for the declarations fallback.
deploymentIds={[
...new Set(
project.project.environments
diff --git a/web/src/managed-agents/Memory.test.tsx b/web/src/managed-agents/Memory.test.tsx
new file mode 100644
index 00000000..9a8fdf14
--- /dev/null
+++ b/web/src/managed-agents/Memory.test.tsx
@@ -0,0 +1,258 @@
+// @vitest-environment happy-dom
+
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type {
+ ManagedMemoryDocument,
+ ManagedMemoryDocumentRead,
+ ManagedMemoryDocumentTarget,
+} from './api'
+
+const api = vi.hoisted(() => ({
+ getManagedMemoryResources: vi.fn(),
+ getManagedMemoryDocuments: vi.fn(),
+ getManagedMemoryDocument: vi.fn(),
+ replaceManagedMemoryDocument: vi.fn(),
+ createManagedMemoryDocument: vi.fn(),
+ deleteManagedMemoryDocument: vi.fn(),
+ patchManagedMemoryDocument: vi.fn(),
+ getManagedAgentDeployment: vi.fn(),
+}))
+vi.mock('./api', () => api)
+
+// Imported after the mock so the component sees the fakes.
+const { ManagedProjectMemory } = await import('./Memory')
+
+function documentIn(resource: string, text: string): ManagedMemoryDocument {
+ return {
+ id: 'workshop',
+ title: `${resource} workshop`,
+ text,
+ summary: '',
+ agentWrites: 'enabled',
+ // The same id and revision in both resources: a save addressed to the
+ // wrong resource would pass its revision check.
+ revision: 'rev-1',
+ bytes: text.length,
+ maxBytes: 8192,
+ updatedAt: '2026-09-10T12:00:00.000Z',
+ writer: { kind: 'owner' },
+ }
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => {
+ resolve = done
+ })
+ return { promise, resolve }
+}
+
+function button(scope: ParentNode, label: string): HTMLButtonElement {
+ const match = [...scope.querySelectorAll('button')].find(
+ (element) => element.textContent?.trim() === label,
+ )
+ if (!(match instanceof HTMLButtonElement))
+ throw new Error(`Button not found: ${label}`)
+ return match
+}
+
+async function settle(until: () => boolean, label: string) {
+ for (let attempt = 0; attempt < 50; attempt += 1) {
+ if (until()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ }
+ throw new Error(`Timed out waiting for ${label}`)
+}
+
+function typeInto(
+ input: HTMLInputElement | HTMLTextAreaElement,
+ value: string,
+) {
+ const prototype =
+ input instanceof HTMLTextAreaElement
+ ? HTMLTextAreaElement.prototype
+ : HTMLInputElement.prototype
+ Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+}
+
+describe('ManagedProjectMemory editor target', () => {
+ let container: HTMLDivElement
+ let root: Root
+ let client: QueryClient
+
+ beforeEach(() => {
+ ;(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true
+ container = document.createElement('div')
+ document.body.append(container)
+ root = createRoot(container)
+ client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+ api.getManagedMemoryResources.mockReset()
+ api.getManagedMemoryDocuments.mockReset()
+ api.getManagedMemoryDocument.mockReset()
+ api.replaceManagedMemoryDocument.mockReset()
+ })
+
+ afterEach(() => {
+ act(() => root.unmount())
+ client.clear()
+ container.remove()
+ document.body.replaceChildren()
+ })
+
+ it('drops a read that resolves after the resource changed and saves to the target it read', async () => {
+ api.getManagedMemoryResources.mockResolvedValue({
+ resources: [
+ {
+ id: 'notes',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ documents: 1,
+ },
+ {
+ id: 'requirements',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ documents: 1,
+ },
+ ],
+ })
+ api.getManagedMemoryDocuments.mockImplementation(
+ (input: { resource: string }) => {
+ const meta: Partial<ManagedMemoryDocument> = documentIn(
+ input.resource,
+ '',
+ )
+ delete meta.text
+ return Promise.resolve({ documents: [meta], nextCursor: null })
+ },
+ )
+ const notesRead = deferred<ManagedMemoryDocumentRead>()
+ api.getManagedMemoryDocument.mockImplementation(
+ (target: ManagedMemoryDocumentTarget) =>
+ target.resource === 'notes'
+ ? notesRead.promise
+ : Promise.resolve({
+ document: documentIn(target.resource, 'Requirements text.'),
+ etag: '"rev-1"',
+ }),
+ )
+ api.replaceManagedMemoryDocument.mockImplementation(
+ (input: ManagedMemoryDocumentTarget & { text: string }) =>
+ Promise.resolve({
+ document: {
+ ...documentIn(input.resource, input.text),
+ revision: 'rev-2',
+ },
+ etag: '"rev-2"',
+ }),
+ )
+
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter>
+ <ManagedProjectMemory
+ projectId="prj_1"
+ environment="development"
+ deploymentIds={[]}
+ />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
+
+ // The first resource, notes, is selected; open its document.
+ await settle(
+ () => container.textContent?.includes('notes workshop') ?? false,
+ 'the notes documents',
+ )
+ act(() => button(container, 'Edit').click())
+ await settle(
+ () => api.getManagedMemoryDocument.mock.calls.length > 0,
+ 'the notes read',
+ )
+ expect(api.getManagedMemoryDocument).toHaveBeenCalledWith({
+ projectId: 'prj_1',
+ resource: 'notes',
+ id: 'workshop',
+ environment: 'development',
+ })
+
+ // Switch to requirements while that read is still in flight.
+ const other = container.querySelector<HTMLInputElement>(
+ 'input[aria-label="Other resource ID"]',
+ )!
+ act(() => typeInto(other, 'requirements'))
+ act(() => {
+ other
+ .closest('form')!
+ .dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
+ })
+ await settle(
+ () => container.textContent?.includes('requirements workshop') ?? false,
+ 'the requirements documents',
+ )
+
+ // The stale read lands now: no editor opens, nothing of it is shown.
+ await act(async () => {
+ notesRead.resolve({
+ document: documentIn('notes', 'Notes text.'),
+ etag: '"rev-1"',
+ })
+ await notesRead.promise
+ })
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+ expect(document.body.querySelector('#memory-edit-text')).toBeNull()
+ expect(document.body.textContent).not.toContain('Notes text.')
+
+ // Editing the requirements document saves to requirements, with the
+ // revision that read returned, never to the resource read first.
+ act(() => button(container, 'Edit').click())
+ await settle(
+ () => document.body.querySelector('#memory-edit-text') !== null,
+ 'the requirements editor',
+ )
+ const text =
+ document.body.querySelector<HTMLTextAreaElement>('#memory-edit-text')!
+ expect(text.value).toBe('Requirements text.')
+ act(() => typeInto(text, 'Requirements text, edited.'))
+ act(() => button(document.body, 'Save').click())
+ await settle(
+ () => api.replaceManagedMemoryDocument.mock.calls.length > 0,
+ 'the save',
+ )
+
+ expect(api.replaceManagedMemoryDocument).toHaveBeenCalledTimes(1)
+ expect(api.replaceManagedMemoryDocument).toHaveBeenCalledWith({
+ projectId: 'prj_1',
+ resource: 'requirements',
+ id: 'workshop',
+ environment: 'development',
+ etag: '"rev-1"',
+ text: 'Requirements text, edited.',
+ summary: '',
+ })
+ expect(
+ api.replaceManagedMemoryDocument.mock.calls.some(
+ (call: unknown[]) =>
+ (call[0] as ManagedMemoryDocumentTarget).resource === 'notes',
+ ),
+ ).toBe(false)
+ })
+})
diff --git a/web/src/managed-agents/Memory.tsx b/web/src/managed-agents/Memory.tsx
index 10bd799e..b09f9c1c 100644
--- a/web/src/managed-agents/Memory.tsx
+++ b/web/src/managed-agents/Memory.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import {
useInfiniteQuery,
useMutation,
- useQueries,
+ useQuery,
useQueryClient,
} from '@tanstack/react-query'
import { Link } from 'react-router-dom'
@@ -42,19 +42,23 @@ import {
getManagedAgentDeployment,
getManagedMemoryDocument,
getManagedMemoryDocuments,
+ getManagedMemoryResources,
patchManagedMemoryDocument,
replaceManagedMemoryDocument,
type ManagedMemoryDocument,
type ManagedMemoryDocumentMeta,
type ManagedMemoryDocumentRead,
+ type ManagedMemoryDocumentTarget,
type ManagedMemoryEnvironment,
} from './api'
import {
- declaredMemoryResources,
formatMemoryBytes,
isOverMemoryLimit,
+ listMemoryResources,
memoryExportFile,
+ memoryResourceHint,
memoryWriterLabel,
+ type MemoryResourceSummary,
} from './memory-documents'
function formatDate(value: string) {
@@ -83,9 +87,13 @@ function WriterCell({
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").
+// The editor carries the complete target it read (resource, document id,
+// revision) from the read through editing, saving and conflict handling; a
+// save addresses that target, never whatever the selector shows by then. A
+// save that loses the race shows the current document instead of
+// overwriting it (document-memory.mdx, "Conflicts").
type EditorState = {
+ target: ManagedMemoryDocumentTarget
meta: ManagedMemoryDocumentMeta
base: ManagedMemoryDocumentRead
text: string
@@ -100,26 +108,164 @@ export function ManagedProjectMemory({
}: {
projectId: string
environment: ManagedMemoryEnvironment
- /** Active deployments of this environment; their declarations name the resources. */
+ /** Active deployments of every project member in this environment; their declarations name the resources when the backend has no inventory. */
deploymentIds: string[]
}) {
- const queryClient = useQueryClient()
- const deployments = useQueries({
- queries: deploymentIds.map((deploymentId) => ({
- queryKey: ['managed-agent-deployment', deploymentId],
- queryFn: () => getManagedAgentDeployment(deploymentId),
- })),
+ const inventory = useQuery({
+ queryKey: [
+ 'managed-memory-resources',
+ projectId,
+ environment,
+ deploymentIds,
+ ],
+ queryFn: () =>
+ listMemoryResources({
+ inventory: () => getManagedMemoryResources({ projectId, environment }),
+ declarations: () =>
+ Promise.all(deploymentIds.map(getManagedAgentDeployment)),
+ }),
})
- const declared = declaredMemoryResources(
- deployments.map((deployment) => deployment.data),
- )
+ const known = inventory.data?.resources ?? []
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) => ({
+ const resource = selectedResource ?? known[0]?.id
+ const summary = known.find((candidate) => candidate.id === resource)
+
+ 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>
+ </PanelHeader>
+ <PanelContent className="grid gap-4 md:grid-cols-[minmax(0,20rem)_1fr] md:items-end">
+ <Field
+ label="Resource"
+ htmlFor="memory-resource"
+ description={
+ summary && !summary.declared
+ ? 'No active deployment declares this resource; its documents are kept until you delete them.'
+ : inventory.data?.source === 'declarations'
+ ? 'Listed from active deployments; undeclared resources are not shown here. Open one by ID.'
+ : known.length || inventory.isLoading
+ ? undefined
+ : 'No memory resources here yet; open one by ID.'
+ }
+ >
+ {known.length || resource ? (
+ <Select
+ id="memory-resource"
+ value={resource ?? ''}
+ onValueChange={setSelectedResource}
+ options={[
+ ...known.map((candidate) => ({
+ value: candidate.id,
+ label: candidate.id,
+ ...(memoryResourceHint(candidate)
+ ? { hint: memoryResourceHint(candidate) }
+ : {}),
+ })),
+ // A resource opened by ID that the inventory does not list.
+ ...(resource && !summary
+ ? [{ value: resource, label: resource, hint: 'not listed' }]
+ : []),
+ ]}
+ placeholder="Choose a resource"
+ />
+ ) : (
+ <Input
+ id="memory-resource"
+ value=""
+ readOnly
+ placeholder={
+ inventory.isLoading
+ ? 'Loading resources'
+ : '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>
+ {inventory.isError ? (
+ <PanelContent className="border-t">
+ <EmptyState
+ icon={BookOpen}
+ title="Couldn't list memory resources"
+ description={
+ inventory.error instanceof Error
+ ? inventory.error.message
+ : 'Try loading this page again.'
+ }
+ />
+ </PanelContent>
+ ) : resource ? (
+ // Keyed by the selection: switching resources remounts the documents
+ // panel, so drafts, dialogs and in-flight reads belong to the resource
+ // they were started for, and a read that resolves after the switch
+ // has nowhere to land.
+ <MemoryResourceDocuments
+ key={`${environment}:${resource}`}
+ projectId={projectId}
+ environment={environment}
+ resource={resource}
+ summary={summary}
+ />
+ ) : (
+ <PanelContent className="border-t">
+ <EmptyState
+ icon={BookOpen}
+ title="Choose a resource"
+ description="Resources come from the deployments that declare them and from the documents already saved here."
+ />
+ </PanelContent>
+ )}
+ </Panel>
+ )
+}
+
+function MemoryResourceDocuments({
+ projectId,
+ environment,
+ resource,
+ summary,
+}: {
+ projectId: string
+ environment: ManagedMemoryEnvironment
+ resource: string
+ summary?: MemoryResourceSummary
+}) {
+ const queryClient = useQueryClient()
+ const target = (id: string): ManagedMemoryDocumentTarget => ({
projectId,
- resource: resource ?? '',
+ resource,
id,
environment,
})
@@ -131,12 +277,11 @@ export function ManagedProjectMemory({
queryFn: ({ pageParam }) =>
getManagedMemoryDocuments({
projectId,
- resource: resource ?? '',
+ resource,
environment,
...(pageParam ? { cursor: pageParam } : {}),
}),
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
- enabled: Boolean(resource),
})
const rows = documents.data?.pages.flatMap((page) => page.documents) ?? []
@@ -151,7 +296,13 @@ export function ManagedProjectMemory({
const [editor, setEditor] = useState<EditorState>()
const [removing, setRemoving] = useState<ManagedMemoryDocumentMeta>()
- const invalidate = () => queryClient.invalidateQueries({ queryKey: listKey })
+ const invalidate = () =>
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: listKey }),
+ queryClient.invalidateQueries({
+ queryKey: ['managed-memory-resources', projectId, environment],
+ }),
+ ])
const create = useMutation({
mutationFn: () =>
@@ -171,12 +322,16 @@ export function ManagedProjectMemory({
onError: (error) => notifyError("Couldn't create that document.", error),
})
+ // The read's variables are the target; the editor opens on exactly that.
const openEditor = useMutation({
- mutationFn: (meta: ManagedMemoryDocumentMeta) =>
- getManagedMemoryDocument(target(meta.id)),
- onSuccess: (base, meta) =>
+ mutationFn: (input: {
+ target: ManagedMemoryDocumentTarget
+ meta: ManagedMemoryDocumentMeta
+ }) => getManagedMemoryDocument(input.target),
+ onSuccess: (base, input) =>
setEditor({
- meta,
+ target: input.target,
+ meta: input.meta,
base,
text: base.document.text,
summary: base.document.summary,
@@ -188,14 +343,14 @@ export function ManagedProjectMemory({
mutationFn: async (state: EditorState) => {
try {
return await replaceManagedMemoryDocument({
- ...target(state.meta.id),
+ ...state.target,
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))
+ const conflict = await getManagedMemoryDocument(state.target)
setEditor({ ...state, conflict })
return undefined
}
@@ -258,7 +413,6 @@ export function ManagedProjectMemory({
const exportResource = useMutation({
mutationFn: async () => {
- if (!resource) return undefined
const all: ManagedMemoryDocument[] = []
let cursor: string | undefined
do {
@@ -289,11 +443,8 @@ export function ManagedProjectMemory({
URL.revokeObjectURL(url)
return all.length
},
- onSuccess: (count) => {
- if (count !== undefined) {
- notifySuccess(`Exported ${count} document${count === 1 ? '' : 's'}.`)
- }
- },
+ onSuccess: (count) =>
+ notifySuccess(`Exported ${count} document${count === 1 ? '' : 's'}.`),
onError: (error) => notifyError("Couldn't export that resource.", error),
})
@@ -366,7 +517,9 @@ export function ManagedProjectMemory({
size="sm"
variant="outline"
disabled={openEditor.isPending}
- onClick={() => openEditor.mutate(document)}
+ onClick={() =>
+ openEditor.mutate({ target: target(document.id), meta: document })
+ }
>
Edit
</Button>
@@ -400,165 +553,92 @@ export function ManagedProjectMemory({
const conflictWriter = editor?.conflict
? memoryWriterLabel(editor.conflict.document.writer)
: undefined
+ const maxBytes = summary?.provider.maxBytes
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.')
- }
+ <PanelContent className="flex flex-wrap items-center justify-between gap-3 border-t">
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{resource}</p>
+ <p className="text-muted-foreground mt-0.5 text-xs">
+ {summary
+ ? [
+ summary.declared ? undefined : 'Not declared',
+ maxBytes !== undefined
+ ? `${formatMemoryBytes(maxBytes)} per document`
+ : undefined,
+ summary.documents !== undefined
+ ? `${summary.documents} ${summary.documents === 1 ? 'document' : 'documents'}`
+ : undefined,
+ ]
+ .filter((part) => part !== undefined)
+ .join(' · ')
+ : 'Opened by ID.'}
+ </p>
+ </div>
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={exportResource.isPending}
+ onClick={() => exportResource.mutate()}
>
- {declared.length || resource ? (
- <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) }
- : {}),
- })),
- // A resource opened by ID that no active deployment declares.
- ...(resource && !declaration
- ? [
- {
- value: resource,
- label: resource,
- hint: 'not declared',
- },
- ]
- : []),
- ]}
- placeholder="Choose a resource"
- />
+ {exportResource.isPending ? (
+ <Loader2 className="animate-spin" />
) : (
- <Input
- id="memory-resource"
- value=""
- readOnly
- placeholder="No resource selected"
- />
+ <Download />
)}
- </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>
+ Export
+ </Button>
+ <Button size="sm" onClick={() => setCreating(true)}>
+ <Plus /> Create document
+ </Button>
+ </div>
+ </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>
- {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>
+ ) : (
+ <PanelContent className="border-t p-0">
+ <ResourceTable
+ columns={columns}
+ rows={rows}
+ rowKey={(document) => document.id}
+ loading={documents.isLoading}
+ empty={
+ <EmptyState
+ icon={BookOpen}
+ title={`No ${environment} documents in ${resource}`}
+ description="Create one here or with `opencomputer memory create`. A session can only bind to a document that exists."
+ />
+ }
+ />
+ </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}
<Dialog open={creating} onOpenChange={setCreating}>
<DialogContent className="max-w-2xl">
@@ -620,8 +700,8 @@ export function ManagedProjectMemory({
label="Text"
htmlFor="memory-create-text"
description={
- declaration?.provider.maxBytes
- ? `Up to ${formatMemoryBytes(declaration.provider.maxBytes)} of UTF-8.`
+ maxBytes !== undefined
+ ? `Up to ${formatMemoryBytes(maxBytes)} of UTF-8.`
: undefined
}
>
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 509ae306..ccf4302a 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -550,6 +550,26 @@ const memoryDocumentPageSchema = z.object({
nextCursor: z.string().nullable(),
})
+// The environment's durable resource inventory. Storage outlives code, so a
+// resource stays listed while it holds documents after every deployment
+// stopped declaring it (`declared: false`).
+const memoryResourceSchema = z.object({
+ id: z.string(),
+ provider: z
+ .object({
+ kind: z.string().optional().default('document'),
+ maxBytes: z.number().optional(),
+ })
+ .optional()
+ .default({ kind: 'document' }),
+ declared: z.boolean(),
+ documents: z.number(),
+})
+
+const memoryResourceInventorySchema = z.object({
+ resources: z.array(memoryResourceSchema),
+})
+
const projectOverviewSchema = z.object({
project: projectSchema,
templateSource: z
@@ -581,6 +601,7 @@ 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>
+export type ManagedMemoryResource = z.infer<typeof memoryResourceSchema>
/** A document with the ETag the next conditional request must send back verbatim. */
export type ManagedMemoryDocumentRead = {
document: ManagedMemoryDocument
@@ -1278,13 +1299,28 @@ export async function getManagedAgentSession(sessionId: string) {
export type ManagedMemoryEnvironment = 'development' | 'production'
-type MemoryDocumentTarget = {
+/** The complete address of one document; every read and write names it in full. */
+export type ManagedMemoryDocumentTarget = {
projectId: string
resource: string
id: string
environment: ManagedMemoryEnvironment
}
+type MemoryDocumentTarget = ManagedMemoryDocumentTarget
+
+export async function getManagedMemoryResources(input: {
+ projectId: string
+ environment: ManagedMemoryEnvironment
+}) {
+ const query = new URLSearchParams({ environment: input.environment })
+ return apiFetch(
+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/memory?${query.toString()}`,
+ undefined,
+ memoryResourceInventorySchema,
+ )
+}
+
function memoryDocumentsPath(input: {
projectId: string
resource: string
diff --git a/web/src/managed-agents/memory-documents.test.ts b/web/src/managed-agents/memory-documents.test.ts
index d5790844..fae5b4bd 100644
--- a/web/src/managed-agents/memory-documents.test.ts
+++ b/web/src/managed-agents/memory-documents.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, it } from 'vitest'
+import { ApiError } from '@/api/client'
import {
- declaredMemoryResources,
formatMemoryBytes,
isOverMemoryLimit,
+ listMemoryResources,
memoryExportFile,
+ memoryResourceHint,
+ memoryResourcesFromDeclarations,
memoryWriterLabel,
} from './memory-documents'
@@ -13,27 +16,122 @@ const requirements = {
provider: { kind: 'document', maxBytes: 8192 },
}
-describe('declaredMemoryResources', () => {
- it('merges declarations across deployments by id, first wins, sorted', () => {
+describe('memoryResourcesFromDeclarations', () => {
+ it('merges declarations across every member deployment by id, first wins, sorted', () => {
expect(
- declaredMemoryResources([
+ memoryResourcesFromDeclarations([
{ memory: [{ ...requirements, id: 'notes' }, requirements] },
undefined,
{
memory: [
- { ...requirements, description: 'A later duplicate.' },
+ { ...requirements, provider: { kind: 'document', maxBytes: 16 } },
{ ...requirements, id: 'budget' },
],
},
- ]).map((declaration) => [declaration.id, declaration.description]),
+ ]),
).toEqual([
- ['budget', 'Verified requirements.'],
- ['notes', 'Verified requirements.'],
- ['requirements', 'Verified requirements.'],
+ {
+ id: 'budget',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ },
+ {
+ id: 'notes',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ },
+ {
+ id: 'requirements',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ },
])
})
})
+describe('listMemoryResources', () => {
+ const inventory = [
+ {
+ id: 'scratch',
+ provider: { kind: 'document', maxBytes: 4096 },
+ declared: false,
+ documents: 2,
+ },
+ {
+ id: 'requirements',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ documents: 3,
+ },
+ ]
+
+ it('prefers the durable inventory, undeclared resources included', async () => {
+ let declarationsAsked = false
+ const listing = await listMemoryResources({
+ inventory: () => Promise.resolve({ resources: inventory }),
+ declarations: () => {
+ declarationsAsked = true
+ return Promise.resolve([])
+ },
+ })
+ expect(listing.source).toBe('inventory')
+ expect(listing.resources.map((resource) => resource.id)).toEqual([
+ 'requirements',
+ 'scratch',
+ ])
+ expect(declarationsAsked).toBe(false)
+ })
+
+ it('falls back to every active deployment declaration when the route is missing', async () => {
+ const listing = await listMemoryResources({
+ inventory: () => Promise.reject(new ApiError('Not found', 404)),
+ declarations: () =>
+ Promise.resolve([
+ { memory: [requirements] },
+ { memory: [{ ...requirements, id: 'worker-notes' }] },
+ ]),
+ })
+ expect(listing).toEqual({
+ source: 'declarations',
+ resources: [
+ {
+ id: 'requirements',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ },
+ {
+ id: 'worker-notes',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ },
+ ],
+ })
+ })
+
+ it('surfaces any other inventory failure', async () => {
+ await expect(
+ listMemoryResources({
+ inventory: () => Promise.reject(new ApiError('Forbidden', 403)),
+ declarations: () => Promise.resolve([]),
+ }),
+ ).rejects.toMatchObject({ status: 403 })
+ })
+
+ it('notes limit, declaration and document count in the selector hint', () => {
+ expect(memoryResourceHint(inventory[1])).toBe('8.0 KiB · 3 documents')
+ expect(memoryResourceHint(inventory[0])).toBe(
+ 'not declared · 4.0 KiB · 2 documents',
+ )
+ expect(
+ memoryResourceHint({
+ id: 'x',
+ provider: { kind: 'document' },
+ declared: true,
+ }),
+ ).toBe('')
+ })
+})
+
describe('document presentation', () => {
it('marks a document over its resource limit', () => {
expect(isOverMemoryLimit({ bytes: 8193, maxBytes: 8192 })).toBe(true)
diff --git a/web/src/managed-agents/memory-documents.ts b/web/src/managed-agents/memory-documents.ts
index d7f8874e..06e96820 100644
--- a/web/src/managed-agents/memory-documents.ts
+++ b/web/src/managed-agents/memory-documents.ts
@@ -1,30 +1,94 @@
+import { ApiError } from '@/api/client'
import type {
ManagedMemoryDeclaration,
ManagedMemoryDocument,
ManagedMemoryDocumentMeta,
ManagedMemoryEnvironment,
+ ManagedMemoryResource,
} from './api'
+/**
+ * A resource of the environment as the owner sees it: from the durable
+ * inventory when the backend has it, else from deployment declarations, in
+ * which case undeclared resources and document counts are unknown.
+ */
+export type MemoryResourceSummary = {
+ id: string
+ provider: { kind: string; maxBytes?: number }
+ declared: boolean
+ documents?: number
+}
+
+export type MemoryResourceListing = {
+ resources: MemoryResourceSummary[]
+ source: 'inventory' | 'declarations'
+}
+
+function byId(left: { id: string }, right: { id: string }) {
+ return left.id.localeCompare(right.id)
+}
+
/**
* 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.
+ * id across every project member. Agents of one project share a resource by
+ * id, so the first declaration seen describes it.
*/
-export function declaredMemoryResources(
+export function memoryResourcesFromDeclarations(
deployments: ReadonlyArray<
{ memory: ManagedMemoryDeclaration[] } | undefined
>,
-): ManagedMemoryDeclaration[] {
- const byId = new Map<string, ManagedMemoryDeclaration>()
+): MemoryResourceSummary[] {
+ const byResource = new Map<string, MemoryResourceSummary>()
for (const deployment of deployments) {
for (const declaration of deployment?.memory ?? []) {
- if (!byId.has(declaration.id)) byId.set(declaration.id, declaration)
+ if (byResource.has(declaration.id)) continue
+ byResource.set(declaration.id, {
+ id: declaration.id,
+ provider: declaration.provider,
+ declared: true,
+ })
}
}
- return [...byId.values()].sort((left, right) =>
- left.id.localeCompare(right.id),
- )
+ return [...byResource.values()].sort(byId)
+}
+
+/**
+ * The environment's resources: the inventory route first, since it is the
+ * only complete list (a resource only a worker declares, or one nothing
+ * declares any more but that still holds documents); the declarations of
+ * every active project member when an older backend answers 404.
+ */
+export async function listMemoryResources(input: {
+ inventory: () => Promise<{ resources: ManagedMemoryResource[] }>
+ declarations: () => Promise<
+ ReadonlyArray<{ memory: ManagedMemoryDeclaration[] } | undefined>
+ >
+}): Promise<MemoryResourceListing> {
+ try {
+ const { resources } = await input.inventory()
+ return { resources: [...resources].sort(byId), source: 'inventory' }
+ } catch (error) {
+ if (!(error instanceof ApiError && error.status === 404)) throw error
+ }
+ return {
+ resources: memoryResourcesFromDeclarations(await input.declarations()),
+ source: 'declarations',
+ }
+}
+
+/** The selector's right-aligned note: limit, then whether the resource is still declared and what it holds. */
+export function memoryResourceHint(resource: MemoryResourceSummary) {
+ return [
+ resource.declared ? undefined : 'not declared',
+ resource.provider.maxBytes !== undefined
+ ? formatMemoryBytes(resource.provider.maxBytes)
+ : undefined,
+ resource.documents !== undefined
+ ? `${resource.documents} ${resource.documents === 1 ? 'document' : 'documents'}`
+ : undefined,
+ ]
+ .filter((part) => part !== undefined)
+ .join(' · ')
}
/** A document larger than the resource's current limit must shrink on its next save. */