Skip to content

An open-source, faster Devin alternative

TypeScript

web: memory dialogs carry their full target and outlive no project switch

Igor Zalutskic51694a1c8e3
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index 50c8c903..cbdce947 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -1176,7 +1176,7 @@ export default function ManagedAgentDetail({
{activeTab === 'memory' && project ? (
<ManagedProjectMemory
- key={environment}
+ key={`${project.project.id}:${environment}`}
projectId={project.project.id}
environment={environment}
// One environment row per project agent: every member's active
diff --git a/web/src/managed-agents/Memory.test.tsx b/web/src/managed-agents/Memory.test.tsx
index 9a8fdf14..ecfc71c9 100644
--- a/web/src/managed-agents/Memory.test.tsx
+++ b/web/src/managed-agents/Memory.test.tsx
@@ -5,6 +5,7 @@ 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 { ApiError } from '@/api/client'
import type {
ManagedMemoryDocument,
ManagedMemoryDocumentRead,
@@ -45,10 +46,12 @@ function documentIn(resource: string, text: string): ManagedMemoryDocument {
function deferred<T>() {
let resolve!: (value: T) => void
- const promise = new Promise<T>((done) => {
+ let reject!: (cause: unknown) => void
+ const promise = new Promise<T>((done, fail) => {
resolve = done
+ reject = fail
})
- return { promise, resolve }
+ return { promise, resolve, reject }
}
function button(scope: ParentNode, label: string): HTMLButtonElement {
@@ -113,6 +116,240 @@ describe('ManagedProjectMemory editor target', () => {
document.body.replaceChildren()
})
+ function render(projectId: string) {
+ act(() => {
+ root.render(
+ <QueryClientProvider client={client}>
+ <MemoryRouter>
+ <ManagedProjectMemory
+ projectId={projectId}
+ environment="development"
+ deploymentIds={[]}
+ />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+ })
+ }
+
+ function oneResourceWithWorkshop() {
+ api.getManagedMemoryResources.mockResolvedValue({
+ resources: [
+ {
+ id: 'notes',
+ provider: { kind: 'document', maxBytes: 8192 },
+ declared: true,
+ documents: 1,
+ },
+ ],
+ })
+ api.getManagedMemoryDocuments.mockImplementation(
+ (input: { projectId: string; resource: string }) => {
+ const meta: Partial<ManagedMemoryDocument> = documentIn(
+ `${input.projectId} ${input.resource}`,
+ '',
+ )
+ delete meta.text
+ return Promise.resolve({ documents: [meta], nextCursor: null })
+ },
+ )
+ api.getManagedMemoryDocument.mockImplementation(
+ (target: ManagedMemoryDocumentTarget) =>
+ Promise.resolve({
+ document: documentIn(
+ `${target.projectId} ${target.resource}`,
+ `${target.projectId} text.`,
+ ),
+ etag: '"rev-1"',
+ }),
+ )
+ }
+
+ // Review reproduction (U2): the delete confirmation opened for one
+ // project's document must not survive into another project.
+ it('closes an open delete confirmation when the project changes and deletes only the captured target', async () => {
+ oneResourceWithWorkshop()
+ api.deleteManagedMemoryDocument.mockReset()
+ api.deleteManagedMemoryDocument.mockResolvedValue(undefined)
+
+ // B was visited before, so its inventory and documents are cached and a
+ // return to it renders at once.
+ render('prj_b')
+ await settle(
+ () => container.textContent?.includes('prj_b notes workshop') ?? false,
+ "project B's documents",
+ )
+ render('prj_a')
+ await settle(
+ () => container.textContent?.includes('prj_a notes workshop') ?? false,
+ "project A's documents",
+ )
+ act(() => button(container, 'Delete').click())
+ await settle(
+ () => document.body.textContent?.includes('Delete workshop?') ?? false,
+ "A's confirmation",
+ )
+
+ // Navigate to the cached project with the same resource and document id.
+ render('prj_b')
+ await settle(
+ () => container.textContent?.includes('prj_b notes workshop') ?? false,
+ "project B's documents",
+ )
+ expect(document.body.textContent).not.toContain('Delete workshop?')
+ expect(
+ [...document.body.querySelectorAll('button')].some(
+ (element) => element.textContent?.trim() === 'Delete document',
+ ),
+ ).toBe(false)
+ expect(api.deleteManagedMemoryDocument).not.toHaveBeenCalled()
+
+ // A confirmation opened in B deletes B's document, with B's revision.
+ act(() => button(container, 'Delete').click())
+ await settle(
+ () => document.body.textContent?.includes('Delete workshop?') ?? false,
+ "B's confirmation",
+ )
+ act(() => button(document.body, 'Delete document').click())
+ await settle(
+ () => api.deleteManagedMemoryDocument.mock.calls.length > 0,
+ 'the delete',
+ )
+ expect(api.deleteManagedMemoryDocument).toHaveBeenCalledTimes(1)
+ expect(api.deleteManagedMemoryDocument).toHaveBeenCalledWith({
+ projectId: 'prj_b',
+ resource: 'notes',
+ id: 'workshop',
+ environment: 'development',
+ etag: '"rev-1"',
+ })
+ })
+
+ async function openEditorAndType(text: string) {
+ act(() => button(container, 'Edit').click())
+ await settle(
+ () => document.body.querySelector('#memory-edit-text') !== null,
+ 'the editor',
+ )
+ const area =
+ document.body.querySelector<HTMLTextAreaElement>('#memory-edit-text')!
+ act(() => typeInto(area, text))
+ return area
+ }
+
+ // Review reproduction (U7): text typed while a save is pending belongs to
+ // the next save, on the revision the pending save produced.
+ it('keeps edits typed during a pending save and saves them on the new revision', async () => {
+ oneResourceWithWorkshop()
+ const held = deferred<ManagedMemoryDocumentRead>()
+ api.replaceManagedMemoryDocument
+ .mockImplementationOnce(() => held.promise)
+ .mockImplementation(
+ (input: ManagedMemoryDocumentTarget & { text: string }) =>
+ Promise.resolve({
+ document: { ...documentIn('notes', input.text), revision: 'rev-3' },
+ etag: '"rev-3"',
+ }),
+ )
+
+ render('prj_a')
+ await settle(
+ () => container.textContent?.includes('prj_a notes workshop') ?? false,
+ 'the documents',
+ )
+ const area = await openEditorAndType('First edit')
+ act(() => button(document.body, 'Save').click())
+ await settle(
+ () => api.replaceManagedMemoryDocument.mock.calls.length === 1,
+ 'the first save',
+ )
+ expect(api.replaceManagedMemoryDocument.mock.calls[0][0]).toMatchObject({
+ etag: '"rev-1"',
+ text: 'First edit',
+ })
+
+ // The response is outstanding; the user keeps typing.
+ act(() => typeInto(area, 'Second edit'))
+ await act(async () => {
+ held.resolve({
+ document: { ...documentIn('notes', 'First edit'), revision: 'rev-2' },
+ etag: '"rev-2"',
+ })
+ await held.promise
+ })
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ })
+
+ // The editor stays open with the newer text, now on revision rev-2.
+ const stillOpen =
+ document.body.querySelector<HTMLTextAreaElement>('#memory-edit-text')
+ expect(stillOpen).not.toBeNull()
+ expect(stillOpen!.value).toBe('Second edit')
+ expect(document.body.textContent).toContain('rev-2')
+
+ act(() => button(document.body, 'Save').click())
+ await settle(
+ () => api.replaceManagedMemoryDocument.mock.calls.length === 2,
+ 'the second save',
+ )
+ expect(api.replaceManagedMemoryDocument.mock.calls[1][0]).toMatchObject({
+ etag: '"rev-2"',
+ text: 'Second edit',
+ })
+ await settle(
+ () => document.body.querySelector('#memory-edit-text') === null,
+ 'the editor closing',
+ )
+ })
+
+ it('keeps edits typed during a save that ends in a conflict', async () => {
+ oneResourceWithWorkshop()
+ const held = deferred<ManagedMemoryDocumentRead>()
+ api.replaceManagedMemoryDocument.mockImplementationOnce(() => held.promise)
+
+ render('prj_a')
+ await settle(
+ () => container.textContent?.includes('prj_a notes workshop') ?? false,
+ 'the documents',
+ )
+ const area = await openEditorAndType('First edit')
+ act(() => button(document.body, 'Save').click())
+ await settle(
+ () => api.replaceManagedMemoryDocument.mock.calls.length === 1,
+ 'the save',
+ )
+ act(() => typeInto(area, 'Second edit'))
+
+ // Someone else saved meanwhile: the read for the conflict shows their text.
+ api.getManagedMemoryDocument.mockResolvedValue({
+ document: { ...documentIn('notes', 'Their text.'), revision: 'rev-9' },
+ etag: '"rev-9"',
+ })
+ await act(async () => {
+ held.reject(
+ new ApiError('Precondition failed', 412, 'precondition_failed'),
+ )
+ await held.promise.catch(() => undefined)
+ })
+ await settle(
+ () =>
+ document.body.textContent?.includes(
+ 'This document changed while you were editing',
+ ) ?? false,
+ 'the conflict',
+ )
+ expect(
+ document.body.querySelector<HTMLTextAreaElement>('#memory-edit-text')!
+ .value,
+ ).toBe('Second edit')
+ expect(
+ document.body.querySelector<HTMLTextAreaElement>(
+ 'textarea[aria-label="Current text"]',
+ )!.value,
+ ).toBe('Their text.')
+ })
+
it('drops a read that resolves after the resource changed and saves to the target it read', async () => {
api.getManagedMemoryResources.mockResolvedValue({
resources: [
diff --git a/web/src/managed-agents/Memory.tsx b/web/src/managed-agents/Memory.tsx
index b09f9c1c..0c19f0d3 100644
--- a/web/src/managed-agents/Memory.tsx
+++ b/web/src/managed-agents/Memory.tsx
@@ -65,6 +65,18 @@ function formatDate(value: string) {
return new Date(value).toLocaleString()
}
+function sameTarget(
+ left: ManagedMemoryDocumentTarget,
+ right: ManagedMemoryDocumentTarget,
+) {
+ return (
+ left.projectId === right.projectId &&
+ left.environment === right.environment &&
+ left.resource === right.resource &&
+ left.id === right.id
+ )
+}
+
const DOCUMENT_ID = /^[A-Za-z0-9_-]{1,128}$/
function WriterCell({
@@ -227,12 +239,12 @@ export function ManagedProjectMemory({
/>
</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.
+ // Keyed by the whole target: switching projects, environments or
+ // resources remounts the documents panel, so drafts, dialogs and
+ // in-flight reads belong to the target they were started for, and a
+ // read that resolves after the switch has nowhere to land.
<MemoryResourceDocuments
- key={`${environment}:${resource}`}
+ key={`${projectId}:${environment}:${resource}`}
projectId={projectId}
environment={environment}
resource={resource}
@@ -294,7 +306,12 @@ function MemoryResourceDocuments({
agentWrites: true,
})
const [editor, setEditor] = useState<EditorState>()
- const [removing, setRemoving] = useState<ManagedMemoryDocumentMeta>()
+ // Every destructive action carries the complete target it was opened on;
+ // nothing is rebuilt from the props current when it is confirmed.
+ const [removing, setRemoving] = useState<{
+ target: ManagedMemoryDocumentTarget
+ meta: ManagedMemoryDocumentMeta
+ }>()
const invalidate = () =>
Promise.all([
@@ -339,27 +356,43 @@ function MemoryResourceDocuments({
onError: (error) => notifyError("Couldn't open that document.", error),
})
+ // A save submits the draft as it was when Save was pressed. The editor
+ // stays live meanwhile; what is typed during the request belongs to the
+ // next save, on the revision this one produces (or, on a conflict, next
+ // to the current text), and is never replaced by the submitted draft.
const save = useMutation({
- mutationFn: async (state: EditorState) => {
+ mutationFn: async (submitted: EditorState) => {
try {
return await replaceManagedMemoryDocument({
- ...state.target,
- etag: state.base.etag,
- text: state.text,
- summary: state.summary,
+ ...submitted.target,
+ etag: submitted.base.etag,
+ text: submitted.text,
+ summary: submitted.summary,
})
} catch (error) {
if (error instanceof ApiError && error.status === 412) {
- const conflict = await getManagedMemoryDocument(state.target)
- setEditor({ ...state, conflict })
+ const conflict = await getManagedMemoryDocument(submitted.target)
+ setEditor((current) =>
+ current && sameTarget(current.target, submitted.target)
+ ? { ...current, conflict }
+ : current,
+ )
return undefined
}
throw error
}
},
- onSuccess: async (saved) => {
+ onSuccess: async (saved, submitted) => {
if (!saved) return
- setEditor(undefined)
+ setEditor((current) => {
+ if (!current || !sameTarget(current.target, submitted.target)) {
+ return current
+ }
+ const unchanged =
+ current.text === submitted.text &&
+ current.summary === submitted.summary
+ return unchanged ? undefined : { ...current, base: saved }
+ })
notifySuccess(
`Saved ${saved.document.id}.`,
`Revision ${saved.document.revision}.`,
@@ -373,12 +406,12 @@ function MemoryResourceDocuments({
// the ETag verbatim rather than a revision reassembled from the list.
const setAgentWrites = useMutation({
mutationFn: async (input: {
- meta: ManagedMemoryDocumentMeta
+ target: ManagedMemoryDocumentTarget
agentWrites: 'enabled' | 'disabled'
}) => {
- const current = await getManagedMemoryDocument(target(input.meta.id))
+ const current = await getManagedMemoryDocument(input.target)
return patchManagedMemoryDocument({
- ...target(input.meta.id),
+ ...input.target,
etag: current.etag,
agentWrites: input.agentWrites,
})
@@ -396,16 +429,16 @@ function MemoryResourceDocuments({
})
const remove = useMutation({
- mutationFn: async (meta: ManagedMemoryDocumentMeta) => {
- const current = await getManagedMemoryDocument(target(meta.id))
+ mutationFn: async (input: { target: ManagedMemoryDocumentTarget }) => {
+ const current = await getManagedMemoryDocument(input.target)
await deleteManagedMemoryDocument({
- ...target(meta.id),
+ ...input.target,
etag: current.etag,
})
},
- onSuccess: async (_, meta) => {
+ onSuccess: async (_, input) => {
setRemoving(undefined)
- notifySuccess(`Deleted ${meta.id}.`, 'Its ID stays reserved.')
+ notifySuccess(`Deleted ${input.target.id}.`, 'Its ID stays reserved.')
await invalidate()
},
onError: (error) => notifyError("Couldn't delete that document.", error),
@@ -529,7 +562,7 @@ function MemoryResourceDocuments({
disabled={setAgentWrites.isPending}
onClick={() =>
setAgentWrites.mutate({
- meta: document,
+ target: target(document.id),
agentWrites:
document.agentWrites === 'enabled' ? 'disabled' : 'enabled',
})
@@ -540,7 +573,9 @@ function MemoryResourceDocuments({
<Button
size="sm"
variant="ghost"
- onClick={() => setRemoving(document)}
+ onClick={() =>
+ setRemoving({ target: target(document.id), meta: document })
+ }
>
Delete
</Button>
@@ -867,7 +902,7 @@ function MemoryResourceDocuments({
<ConfirmDialog
open={Boolean(removing)}
onOpenChange={(open) => !open && setRemoving(undefined)}
- title={`Delete ${removing?.id}?`}
+ title={`Delete ${removing?.meta.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