+ )
+}
+
+/** Settings, Memories: what the platform's memory service holds about the signed-in person, each of which they can delete. */
+export function Memories() {
+ const memories = useMemories()
+ const list = memories.data ?? []
+ return (
+
+
+
What your coding agents remember about you. {HINT}
+
+ )
+}
diff --git a/ui/src/features/settings/Settings.tsx b/ui/src/features/settings/Settings.tsx
index be7b356a..a333da87 100644
--- a/ui/src/features/settings/Settings.tsx
+++ b/ui/src/features/settings/Settings.tsx
@@ -335,6 +335,10 @@ export function Settings() {
Secrets
+
+
+ Memories
+
{admin &&
ADMIN.map((a) => (
diff --git a/ui/src/lib/queries.ts b/ui/src/lib/queries.ts
index 95ab7879..4b063a59 100644
--- a/ui/src/lib/queries.ts
+++ b/ui/src/lib/queries.ts
@@ -4,7 +4,9 @@ import {
authOptions,
createSecret,
createToken,
+ deleteMemory,
deleteSecret,
+ listMemories,
listSecrets,
listEnvironments,
setWorkspaceEnv,
@@ -60,6 +62,7 @@ import {
type SecretCreateInputBody,
type SecretUpdateInputBody,
type SecretView,
+ type MemoryView,
type LaunchBody,
type PreviewsBody,
type SharingInputBody,
@@ -110,6 +113,7 @@ const keys = {
previewApps: (name: string) => ['workspaces', name, 'previews', 'apps'] as const,
tokens: ['tokens'] as const,
secrets: ['secrets'] as const,
+ memories: ['memories'] as const,
info: ['info'] as const,
environments: ['environments'] as const,
}
@@ -683,6 +687,29 @@ export function useSecrets({ enabled = true }: { enabled?: boolean } = {}) {
})
}
+/** What the memory service holds about the user, newest first. It answers 404 when memory is off on the platform. */
+export function useMemories() {
+ return useQuery({
+ queryKey: keys.memories,
+ retry: false,
+ queryFn: async () => (await listMemories({ throwOnError: true })).data ?? [],
+ })
+}
+
+/** Delete one memory: its row leaves the list at once, then the list is read again. */
+export function useDeleteMemory(id: string) {
+ const qc = useQueryClient()
+ return useMutation({
+ mutationFn: async () => {
+ await deleteMemory({ path: { id }, throwOnError: true })
+ },
+ onSuccess: () => {
+ qc.setQueryData(keys.memories, (list) => list?.filter((m) => m.id !== id))
+ void qc.invalidateQueries({ queryKey: keys.memories, exact: true })
+ },
+ })
+}
+
/** Store a secret. Its value goes to the server once and is never kept here. */
export function useCreateSecret() {
const qc = useQueryClient()
From dc63b26a4e20213bb9bf9891e42c13b46513c709 Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Fri, 27 Nov 2026 14:12:09 +0100
Subject: [PATCH 06/11] docs: memory recall, learning and the Memories page
The admin memory page now describes what memory does: recall into the
admin's agent model calls, learning, "remember that ...", the SSN
refusal, the Memories page and API, memory.recallTimeout, every
memory.* log line, and the limits. It also fixes the start check
description, which now retries. The members' Ask AI page gains a
Memories section, and the Helm values example shows recallTimeout.
---
deploy/helm/javo/values.yaml | 1 +
site/src/content/docs/admin/memory.md | 51 ++++++++++++++++++++++-----
site/src/content/docs/using/ask-ai.md | 8 +++++
3 files changed, 51 insertions(+), 9 deletions(-)
diff --git a/deploy/helm/javo/values.yaml b/deploy/helm/javo/values.yaml
index d657f843..800b8056 100644
--- a/deploy/helm/javo/values.yaml
+++ b/deploy/helm/javo/values.yaml
@@ -685,6 +685,7 @@ config:
# url: http://mem0-nebari-mem0.mem0.svc:8000 # the mem0 pack's Service
# timeout: 10s # search, list, get and delete calls
# addTimeout: 120s # add calls, which run model extraction inline
+ # recallTimeout: 2s # the search before an agent's model call
# apiKeySecret:
# namespace: mem0 # required: the namespace the mem0 pack is installed in
# name: mem0-admin-key
diff --git a/site/src/content/docs/admin/memory.md b/site/src/content/docs/admin/memory.md
index 65f41927..e541b964 100644
--- a/site/src/content/docs/admin/memory.md
+++ b/site/src/content/docs/admin/memory.md
@@ -1,17 +1,27 @@
---
title: Memory
-description: Optional. Connect Tapas to the mem0 pack so the gateway can keep memory for people's agents. Today this is setup and a start check only.
+description: Optional. Connect Tapas to the mem0 pack so the admin's agent model remembers what people tell their coding agents, and people can see and delete it under Settings > Memories.
sidebar:
order: 10.5
---
-Memory is kept by [mem0](https://github.com/mem0ai/mem0), which the [mem0 pack](https://github.com/nebari-dev/mem0-pack) runs in its own namespace. With memory on, the gateway builds the memory service at start and checks that mem0 answers.
+Memory is kept by [mem0](https://github.com/mem0ai/mem0), which the [mem0 pack](https://github.com/nebari-dev/mem0-pack) runs in its own namespace. With memory on, the gateway builds the memory service at start, checks that mem0 answers, and gives the admin's agent model a memory of each person.
-## What memory does today
+## What memory does
-This release does the setup only. The gateway reads mem0's key, builds the client and logs at start whether mem0 answers. It does not yet put memories into prompts, learn from answers or offer a memories API; those come in later releases. Turning memory on today changes nothing people see.
+Memory works only on calls to the admin's agent model (`ai.agent`, see [AI](/admin/ai/)), which coding-agent apps such as pi reach through the gateway. Off (the default), the gateway never talks to mem0 and never reads its key.
-Off (the default), the gateway never talks to mem0 and never reads its key.
+- **Recall.** Before an agent's model call, the gateway searches the person's memories for their latest message (on every call, including the agent's steps after a tool result). It adds up to 5 matches (each cut to 500 characters, 2500 in all) to the call's system message as a note that tells the model to use them when relevant and not to mention the note. Results are kept for 2 minutes per person and query, so the repeated steps of one agent turn search once. A search waits at most `recallTimeout`; if it fails or runs out of time, the call goes on without memories.
+- **Learning.** After a call that answers something the person typed, the gateway sends the typed text and the start of the answer (at most 4000 characters) to mem0 in the background, and mem0 keeps only lasting facts about the person: their name, role, team, skills, preferred tools and languages, how they like answers written, and standing instructions. Nothing is kept about the task, code, file contents, errors or command output. A step where the agent continues after a tool result, with no new typed text, is not learned from.
+- **"Remember that ...".** A message that starts with `remember that ...` or `remember: ...` is stored as it is, without extraction. A sentence longer than 1000 characters is skipped.
+- **Social Security numbers.** A write whose text holds a US Social Security number is refused; the number is never stored or logged.
+- **The Memories page.** Each person sees their memories under **Settings > Memories**, newest first, and can delete any of them. Deleting also clears that person's cached recall results on that gateway. The page is served by `GET /api/memories` and `DELETE /api/memories/{id}`, which browser sessions and personal API tokens can call; an app's or a job's own token is refused with 403, except the token of a coding agent whose owner has let it act without asking. With memory off both answer 404 "Memory is off on this platform."; when mem0 cannot be reached they answer 502 "Memory could not be reached; try again later." and the gateway logs the cause.
+
+A coding agent running on a person's own key (**Settings > Secrets > AI agent**) bypasses the gateway, so it gets no recall and learns nothing. Only the admin's agent model has memory. The suggestions in New app's **Describe it** box, Explain more and the other model features do not use memory either.
+
+A call is also left alone, with no recall and no learning, when its first system message is pi's own summarization prompt ("You are a context summarization assistant.") or the typed text is longer than 8000 characters, such as a large paste.
+
+Learning runs at most 4 calls at a time per gateway; a turn that finds all 4 busy is not learned from.
## Install the mem0 pack with Tapas as its caller
@@ -43,6 +53,7 @@ config:
url: http://mem0-nebari-mem0.mem0.svc:8000
timeout: 10s
addTimeout: 120s
+ recallTimeout: 2s
apiKeySecret:
namespace: mem0
name: mem0-admin-key
@@ -55,24 +66,46 @@ config:
| `url` | none | The mem0 pack's Service address, `http` or `https` with a host, and no user name, password, query or fragment. Required when memory is on. |
| `timeout` | `10s` | How long a search, list, get or delete call may take. Must not be negative; 0 or unset uses the default. |
| `addTimeout` | `120s` | How long an add call may take. It is longer because mem0 runs model extraction inline. Must not be negative; 0 or unset uses the default. |
+| `recallTimeout` | `2s` | How long the search before an agent's model call may take. A slow mem0 delays the agent's reply by at most this long. Must not be negative; 0 or unset uses the default. |
| `apiKeySecret.namespace` | none | The namespace of mem0's admin key Secret, which is the namespace the mem0 pack is installed in. Required when memory is on. |
| `apiKeySecret.name` | `mem0-admin-key` | The Secret's name, a valid Kubernetes Secret name. This is the pack's default; change it if you set `adminKey.secretName` or `adminKey.existingSecret` in the pack. |
| `apiKeySecret.key` | `api-key` | The key inside the Secret that holds the admin key, a valid Secret data key. The key inside the Secret the mem0 pack makes is always `api-key` (the pack's chart fixes it), so change this only for a Secret you manage yourself. |
The chart passes this section into the config file as written and creates no Role in mem0's namespace. The gateway reads the key through the Role the mem0 pack creates for the accounts in `callers`.
-The gateway refuses to start with memory on when `url` is missing, is not an `http` or `https` address, or carries a user name, password, query or fragment, when `timeout` or `addTimeout` is negative, when `apiKeySecret.namespace` is missing or is not a valid namespace name, when `apiKeySecret.name` or `apiKeySecret.key` is not valid, or when `executor` is not `kubernetes`.
+The gateway refuses to start with memory on when `url` is missing, is not an `http` or `https` address, or carries a user name, password, query or fragment, when `timeout`, `addTimeout` or `recallTimeout` is negative, when `apiKeySecret.namespace` is missing or is not a valid namespace name, when `apiKeySecret.name` or `apiKeySecret.key` is not valid, or when `executor` is not `kubernetes`.
+
+## What the gateway logs
-## What the gateway logs at start
+The gateway never logs memory text, what people typed, answers, recall queries, Social Security numbers or the key. Each line carries the person (`user`) where one is involved.
+
+At start:
- Memory off: nothing about memory is logged.
-- `memory.ready` with `url`: the gateway asked mem0 for the memories of a reserved name (`tapas-start-check`, which belongs to no person) and mem0 answered.
-- `memory.unreachable` with `url` and `err`: mem0 did not answer correctly. The `err` text says why. `mem0 refused the key` means mem0 answered 401, so the key in the Secret is not the one mem0 uses (the Secret was replaced, or `apiKeySecret` names the wrong one). `GET /memories answered 404` means `url` does not point at the mem0 pack's Service: the pack answers 404 for routes it does not serve, so check the address and port. A message such as `GET /memories answered 503`, or a connection error, means mem0 is down, still starting or not reachable from the gateway, for example because the `callers` entry does not match the gateway pod. The gateway keeps running and does not retry; fix the cause and restart the gateway to check again.
+- `memory.ready` with `url`: the gateway asked mem0 for the memories of a reserved name (`tapas-start-check`, which belongs to no person) and mem0 answered. It is logged once.
+- `memory.unreachable` with `url` and `err`: mem0 did not answer correctly. The gateway checks in the background and keeps retrying, after 5 seconds and then at doubling waits up to one minute, until mem0 answers; it logs `memory.unreachable` again only when the `err` text changes, and `memory.ready` once when mem0 answers. The `err` text says why. `mem0 refused the key` means mem0 answered 401, so the key in the Secret is not the one mem0 uses (the Secret was replaced, or `apiKeySecret` names the wrong one); the key is read only at start, so restart the gateway after fixing it. `GET /memories answered 404` means `url` does not point at the mem0 pack's Service: the pack answers 404 for routes it does not serve, so check the address and port. A message such as `GET /memories answered 503`, or a connection error, means mem0 is down, still starting or not reachable from the gateway, for example because the `callers` entry does not match the gateway pod. The gateway keeps running while it waits.
- The start fails with `read the mem0 key Secret /` when the Secret is missing or the gateway may not read it (the `callers` entry is wrong). It fails with `Secret / has no ""` when the Secret has no such key or its value is empty. It fails when the value has leading or trailing whitespace, for example a trailing newline from `echo` or a file: mem0 compares the key exactly, so a padded value could never work, and Tapas refuses it rather than trim it. Store the key with no whitespace around it (`printf %s`, or `kubectl create secret ... --from-literal`). The error never contains the key.
+While agents run:
+
+| Line | Level | Meaning |
+|---|---|---|
+| `memory.recall_failed` (`err`) | warn | The search before a model call failed or took longer than `recallTimeout`. The call went on without memories, and the failure is not cached. |
+| `memory.learned` (`count`) | info | mem0 stored `count` memories from a turn. `count` is 0 when it found no lasting fact. |
+| `memory.learn_failed` (`err`) | warn | mem0 could not be reached or refused the add. Nothing was stored for that turn. |
+| `memory.learn_skipped` (`reason=busy`) | info | Four learn calls were already running on this gateway, so this turn was not learned from. |
+| `memory.learn_skipped` (`reason=too_long`) | info | A "remember that" sentence was longer than 1000 characters and was not stored. |
+| `memory.write_refused` (`reason=ssn`) | info | The text held a Social Security number, so nothing was sent to mem0. |
+| `memory.learn_panicked` (`stack`) | error | A bug in learning was caught. The person's request was already answered and the gateway kept running. Report it with the stack. |
+| `memory.list_failed`, `memory.delete_failed` (`err`) | warn | The Memories page could not reach mem0. The person saw the 502 message above. |
+
## Limits
- Memory needs the Kubernetes executor. With the Docker or process executor the gateway refuses to start when `memory` is set.
+- Memories are per person only. There is no team or shared memory, and one person's memories are never recalled for another.
+- The recall cache is kept in each gateway replica's memory. A memory deleted on one replica can still be recalled from another replica's cache for up to 2 minutes.
+- mem0 keeps every exchange it was sent in its own history database, even when it extracts no memory from it. Deleting a memory on the Memories page removes the memory, not that history.
+- pi's summarization calls and very long pastes (over 8000 characters) are skipped: nothing is recalled for them or learned from them.
- The key is read once, at start. After the key changes (a new Secret, or a rotation in mem0), restart the gateway so it reads the new one.
- The gateway needs mem0's key Secret to exist when it starts, and fails to start until it does. Install the mem0 pack first, or expect the gateway pod to restart until the Secret appears.
- Memories belong to the person's identity name, which is never given to anyone else. `javo user remove` leaves a person's memories in mem0, as it leaves their home files; if the same person comes back (`javo user add --reuse-person`), they get them again.
diff --git a/site/src/content/docs/using/ask-ai.md b/site/src/content/docs/using/ask-ai.md
index 36c2c4a9..bdfd7d2d 100644
--- a/site/src/content/docs/using/ask-ai.md
+++ b/site/src/content/docs/using/ask-ai.md
@@ -21,6 +21,14 @@ Each person has a daily allowance of model tokens (per UTC day). Every token a c
When your admin gives coding agents a model, or you stored your own key in **Settings > Secrets > AI agent**, the search palette offers **Build with pi: **. It starts a new pi app named after your request, gives pi your request as its first prompt, and opens the app's page; **Open** shows pi at work in its terminal. pi starts in your home folder, or in the folder your request names (such as `~/projects/sales-dashboard`) when it exists. It can write code there, deploy it as an app or a job, wait for it to run and read the startup logs when it fails. It cannot give an app secrets or API access, share it, or touch an app or job that holds a secret: it asks you to do that, or proposes a change for you to approve. The first prompt runs only on the app's first start.
+## Memories
+
+When your admin turns memory on and gives coding agents a model, the agents you start (such as pi) remember lasting things you tell them: your name and role, the tools and languages you prefer, how you like answers or code written, and standing instructions. They do not keep what a task was about, code, file contents, errors or command output. The next time you write to an agent, what is relevant is added to its prompt, even in a different app or conversation.
+
+To save something on purpose, start a message with `remember that ...` (or `remember: ...`), for example `remember that I prefer Polars over pandas`. It is stored as you wrote it. Text with a Social Security number is never stored.
+
+See what is remembered under **Settings > Memories**, newest first, and delete any of it with **Delete**; agents stop recalling it. The page says so when memory is off. Memories are yours alone: other people and their agents never see or recall them, and Tapas has no page that shows them to admins. (Whoever holds the memory service's admin key can read its store; see Limits on the [admin Memory page](/admin/memory/).) An agent running on your own key from **Settings > Secrets > AI agent** does not use or learn memories.
+
## Coding agents (MCP)
Agents such as Claude Code or Cursor can work with Tapas through its MCP endpoint at `/mcp` on the Tapas address. MCP needs no model and is on unless your admin turned it off.
From f9d24dd1b3e4cceed7f5b8628cde52e916ab2cc3 Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Mon, 30 Nov 2026 09:51:38 +0100
Subject: [PATCH 07/11] fix(agentproxy): log long typed messages skipped from
learning, and forget recall results after a learn
A typed message over 8,000 characters was skipped from learning without a
log line; it now logs memory.learn_skipped reason=too_long, as the spec
says. pi's own summarization calls are still skipped silently.
After mem0 stores at least one memory, the person's cached recall results
are dropped, so asking the same thing again within two minutes recalls
what was just stored.
---
internal/ai/agentproxy/agentproxy.go | 3 ++
internal/ai/agentproxy/learn_test.go | 74 ++++++++++++++++++++++++++++
internal/ai/agentproxy/memory.go | 16 ++++--
3 files changed, 89 insertions(+), 4 deletions(-)
diff --git a/internal/ai/agentproxy/agentproxy.go b/internal/ai/agentproxy/agentproxy.go
index 0ab07c8c..2f76c41e 100644
--- a/internal/ai/agentproxy/agentproxy.go
+++ b/internal/ai/agentproxy/agentproxy.go
@@ -170,6 +170,9 @@ func (p *Proxy) chat(w http.ResponseWriter, r *http.Request) {
if json.Unmarshal(body["messages"], &msgs) == nil && msgs != nil {
text, typed = lastUserText(msgs)
skipLearning = housekeeping(msgs, text)
+ if skipLearning && typed && !summarization(msgs) {
+ slog.Info("memory.learn_skipped", "user", person, "reason", "too_long")
+ }
if text != "" && !skipLearning {
if mems := p.recall(r.Context(), person, text); len(mems) > 0 {
if with := withNote(msgs, mems); len(with) != len(msgs) || !sameFirst(with, msgs) {
diff --git a/internal/ai/agentproxy/learn_test.go b/internal/ai/agentproxy/learn_test.go
index cbb6f68d..15f57696 100644
--- a/internal/ai/agentproxy/learn_test.go
+++ b/internal/ai/agentproxy/learn_test.go
@@ -423,3 +423,77 @@ func TestLearnSurvivesAPanicInTheMemoryService(t *testing.T) {
})
}
}
+
+// searchCounter finds one memory, stores one on every write, and counts the
+// searches it is asked for.
+type searchCounter struct {
+ mu sync.Mutex
+ searches int
+}
+
+func (f *searchCounter) Search(context.Context, string, string, string, int) ([]memory.Memory, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.searches++
+ return []memory.Memory{{ID: "1", Text: "I use Go"}}, nil
+}
+
+func (f *searchCounter) Add(context.Context, string, string, []memory.Message) ([]memory.Memory, error) {
+ return []memory.Memory{{ID: "2"}}, nil
+}
+
+func (f *searchCounter) Remember(context.Context, string, string) ([]memory.Memory, error) {
+ return []memory.Memory{{ID: "2"}}, nil
+}
+
+func (f *searchCounter) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.searches
+}
+
+func TestLearningSomethingNewClearsTheCachedRecallForThatPerson(t *testing.T) {
+ cases := []struct{ name, text string }{
+ {"an automatic add", "I use Go at work"},
+ {"an explicit remember", "remember that I use Go at work"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ mem := &searchCounter{}
+ p, h := learnProxy(scripted(t, 200, "application/json", notedJSON), mem)
+ p.Recall = agentproxy.NewRecallCache()
+ post(h, userTurn(tc.text, false))
+ agentproxy.WaitLearning(p)
+ post(h, userTurn(tc.text, false))
+ agentproxy.WaitLearning(p)
+ if n := mem.count(); n != 2 {
+ t.Fatalf("%d searches, want 2 (the second call must not be served a stale cached result)", n)
+ }
+ })
+ }
+}
+
+func TestLearnLogsWhenTypedTextIsTooLongToLearnFrom(t *testing.T) {
+ logs := captureLogs(t)
+ mem := &learnMemory{}
+ p, h := learnProxy(scripted(t, 200, "application/json", notedJSON), mem)
+ post(h, userTurn(strings.Repeat("a", 8001), false))
+ agentproxy.WaitLearning(p)
+ if !strings.Contains(logs.String(), "memory.learn_skipped user=alice reason=too_long") {
+ t.Fatalf("no too_long line: %s", logs)
+ }
+ if strings.Contains(logs.String(), "aaaa") {
+ t.Fatalf("the log carries the typed text: %s", logs)
+ }
+}
+
+func TestLearnDoesNotLogTooLongForPiSummarization(t *testing.T) {
+ logs := captureLogs(t)
+ mem := &learnMemory{}
+ p, h := learnProxy(scripted(t, 200, "application/json", notedJSON), mem)
+ post(h, `{"messages":[{"role":"system","content":"You are a context summarization assistant. Summarize."},{"role":"user","content":"`+strings.Repeat("a", 8001)+`"}]}`)
+ agentproxy.WaitLearning(p)
+ if strings.Contains(logs.String(), "learn_skipped") {
+ t.Fatalf("a summarization call logged a skip: %s", logs)
+ }
+}
diff --git a/internal/ai/agentproxy/memory.go b/internal/ai/agentproxy/memory.go
index 74bb16b8..cde1f29f 100644
--- a/internal/ai/agentproxy/memory.go
+++ b/internal/ai/agentproxy/memory.go
@@ -87,12 +87,16 @@ func lastUserText(msgs []json.RawMessage) (text string, typed bool) {
// housekeeping reports whether the call is the agent's own summarization or a
// very long paste, neither of which should be recalled for or learned from.
func housekeeping(msgs []json.RawMessage, userText string) bool {
+ return summarization(msgs) || utf8.RuneCountInString(userText) > housekeepingRunes
+}
+
+// summarization reports whether msgs is one of pi's own summarization calls.
+func summarization(msgs []json.RawMessage) bool {
if len(msgs) > 0 {
- if role, text := messageText(msgs[0]); role == "system" && strings.HasPrefix(text, piSummarizationPrompt) {
- return true
- }
+ role, text := messageText(msgs[0])
+ return role == "system" && strings.HasPrefix(text, piSummarizationPrompt)
}
- return utf8.RuneCountInString(userText) > housekeepingRunes
+ return false
}
// explicitRemember returns what follows "remember that" or "remember:" at the
@@ -391,5 +395,9 @@ func (p *Proxy) learn(ctx context.Context, person, text, capture string, explici
slog.Warn("memory.learn_failed", "user", person, "err", err)
default:
slog.Info("memory.learned", "user", person, "count", len(got))
+ // Drop cached recall results so the next call sees what was just stored.
+ if len(got) > 0 && p.Recall != nil {
+ p.Recall.Forget(person)
+ }
}
}
From a93c9ce62dcdfe9b709fc629893e1c27327aac53 Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Mon, 30 Nov 2026 09:51:38 +0100
Subject: [PATCH 08/11] fix(ui): show memory being off as information, not an
error
Memory off is an admin's choice, so the Memories page shows its banner in the info tone. Other errors stay red.
---
ui/src/features/settings/Memories.test.tsx | 15 +++++++++++++++
ui/src/features/settings/Memories.tsx | 4 ++--
2 files changed, 17 insertions(+), 2 deletions(-)
diff --git a/ui/src/features/settings/Memories.test.tsx b/ui/src/features/settings/Memories.test.tsx
index 2ef6f661..bf13c5d0 100644
--- a/ui/src/features/settings/Memories.test.tsx
+++ b/ui/src/features/settings/Memories.test.tsx
@@ -44,6 +44,21 @@ describe('Settings, Memories', () => {
expect(screen.queryByRole('list', { name: 'Memories' })).toBeNull()
})
+ it('shows the off state as information, not as an error', async () => {
+ setup({ 'GET /api/memories': { status: 404, body: { title: 'Memory is off on this platform.', status: 404 } } })
+ renderApp('/settings/memories')
+ const banner = (await screen.findByText('Memory is off on this platform.')).closest('.banner')
+ expect(banner?.classList.contains('info')).toBe(true)
+ expect(banner?.classList.contains('err')).toBe(false)
+ })
+
+ it('still shows other failures as errors', async () => {
+ setup({ 'GET /api/memories': { status: 502, body: { title: 'Memory could not be reached; try again later.', status: 502 } } })
+ renderApp('/settings/memories')
+ const banner = (await screen.findByText('Memory could not be reached; try again later.')).closest('.banner')
+ expect(banner?.classList.contains('err')).toBe(true)
+ })
+
it('deletes a memory after confirming and drops its row', async () => {
const api = setup({
'DELETE /api/memories/m1': { status: 204 },
diff --git a/ui/src/features/settings/Memories.tsx b/ui/src/features/settings/Memories.tsx
index 93d0231d..79cf240e 100644
--- a/ui/src/features/settings/Memories.tsx
+++ b/ui/src/features/settings/Memories.tsx
@@ -6,7 +6,7 @@ import { Button } from '../../components/Button'
import { Card } from '../../components/Card'
import { Confirm } from '../../components/Confirm'
import { EmptyState } from '../../components/EmptyState'
-import { problemText } from '../../lib/http'
+import { ApiError, problemText } from '../../lib/http'
import { useDeleteMemory, useMemories } from '../../lib/queries'
const HINT = 'Tell an agent "remember that ..." to add one.'
@@ -69,7 +69,7 @@ export function Memories() {
) : list.length === 0 ? (
From fecd7787c94e8ca262f733071c1c0ab3d47c70f3 Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Mon, 30 Nov 2026 09:51:38 +0100
Subject: [PATCH 09/11] feat(api): only a browser session can delete a memory
DELETE /api/memories/{id} now refuses every API token with 403, including
a coding agent's own token when its owner lets it act without asking, and
personal tokens. An agent can then never erase what is remembered about
its owner, even if a prompt talks it into trying. The route joins the
session-only routes in the token middleware, and the handler checks again.
Listing memories is unchanged.
---
internal/gateway/authn/authn.go | 10 +++++
internal/gateway/authn/authn_test.go | 13 ++++++
internal/gateway/memories/memories.go | 11 +++--
internal/gateway/memories_test.go | 61 +++++++++++++++++++++++++++
internal/reasons/messages.go | 4 ++
ui/openapi.json | 9 +++-
ui/src/api/sdk.gen.ts | 6 +--
7 files changed, 105 insertions(+), 9 deletions(-)
diff --git a/internal/gateway/authn/authn.go b/internal/gateway/authn/authn.go
index 37441685..995c0d14 100644
--- a/internal/gateway/authn/authn.go
+++ b/internal/gateway/authn/authn.go
@@ -421,6 +421,7 @@ var sessionOnlyRoutes = []struct {
{IsTrustChange, reasons.MsgTrustSessionOnly},
{IsFoldersChange, reasons.MsgFoldersOwnerOnly},
{IsDeviceDecision, reasons.MsgDeviceSessionOnly},
+ {IsMemoryDelete, reasons.MsgMemoryDeleteSessionOnly},
}
// SessionOnlyRefusal is the refusal an API token gets at path p, and true,
@@ -799,6 +800,15 @@ func IsTrustChange(p string) bool { return isAppRoute(p, "trust") }
// IsTrustChange.
func IsFoldersChange(p string) bool { return isAppRoute(p, "folders") }
+// IsMemoryDelete is true for the route that deletes one memory,
+// /api/memories/, which only a signed-in person in the browser may use:
+// no token, not even a coding agent's own, can erase what is remembered
+// about its owner. The path is cleaned first, as IsPlanDecision does.
+func IsMemoryDelete(p string) bool {
+ id, ok := strings.CutPrefix(path.Clean("/"+p), "/api/memories/")
+ return ok && id != "" && !strings.Contains(id, "/")
+}
+
// isAppRoute is true for the route /api/workspaces//, with the
// path cleaned first.
func isAppRoute(p, verb string) bool {
diff --git a/internal/gateway/authn/authn_test.go b/internal/gateway/authn/authn_test.go
index 773fa473..7d54c874 100644
--- a/internal/gateway/authn/authn_test.go
+++ b/internal/gateway/authn/authn_test.go
@@ -321,3 +321,16 @@ func TestIsTrustChangeCleansThePath(t *testing.T) {
}
}
}
+
+func TestIsMemoryDeleteCleansThePath(t *testing.T) {
+ for _, p := range []string{"/api/memories/a-1", "/api/memories//a-1", "/api/memories/x/../a-1", "api/memories/a-1/", "/api/memories/{id}"} {
+ if !authn.IsMemoryDelete(p) {
+ t.Errorf("%q is not a memory delete", p)
+ }
+ }
+ for _, p := range []string{"/api/memories", "/api/memories/", "/api/memories/a-1/x", "/api/memory/a-1", "/api/workspaces/memories/a-1"} {
+ if authn.IsMemoryDelete(p) {
+ t.Errorf("%q is a memory delete", p)
+ }
+ }
+}
diff --git a/internal/gateway/memories/memories.go b/internal/gateway/memories/memories.go
index 5db188d0..16e95fe4 100644
--- a/internal/gateway/memories/memories.go
+++ b/internal/gateway/memories/memories.go
@@ -85,12 +85,15 @@ func (a *API) Register(api huma.API) {
huma.Register(api, tagged(huma.Operation{
OperationID: "deleteMemory", Method: http.MethodDelete, Path: memoriesRoute + "/{id}",
- Summary: "Delete one of your memories",
- Description: "Another person's memory is a 404, the same as one that does not exist.",
+ Summary: "Delete one of your memories (browser session only)",
+ Description: "Only you, signed in in the browser, can delete a memory. No API token can, not even a " +
+ "coding agent's own, so this answers 403 to any token. Another person's memory is a 404, the same as " +
+ "one that does not exist.",
DefaultStatus: http.StatusNoContent,
+ Security: authn.SessionOnly,
}), func(ctx context.Context, in *idInput) (*struct{}, error) {
- if err := authn.NoAppTokens(ctx); err != nil {
- return nil, err
+ if authn.NoTokens(ctx) != nil {
+ return nil, problem.New(http.StatusForbidden, reasons.Msg(reasons.MsgMemoryDeleteSessionOnly))
}
if a.Memories == nil {
return nil, off()
diff --git a/internal/gateway/memories_test.go b/internal/gateway/memories_test.go
index 2b86ce62..0788fcda 100644
--- a/internal/gateway/memories_test.go
+++ b/internal/gateway/memories_test.go
@@ -6,14 +6,18 @@ import (
"errors"
"log/slog"
"net/http"
+ "net/http/httptest"
"strings"
"sync"
"testing"
"time"
+ "github.com/nebari-dev/javo/internal/auth/token"
"github.com/nebari-dev/javo/internal/gateway/apitest"
"github.com/nebari-dev/javo/internal/memory"
"github.com/nebari-dev/javo/internal/memory/memorytest"
+ "github.com/nebari-dev/javo/internal/model"
+ "github.com/nebari-dev/javo/internal/reasons"
)
const bobMemoryOwner = "bob-0000"
@@ -173,3 +177,60 @@ func TestMemoriesRefusesAppTokens(t *testing.T) {
t.Fatalf("an app token deleted %v", got)
}
}
+
+// Deleting a memory is the owner's act in the browser: no API token can,
+// whatever it may do elsewhere. Listing is not session-only.
+func TestMemoriesDeleteIsBrowserSessionOnly(t *testing.T) {
+ fake := memorytest.New(memory.Memory{ID: "a-1", Text: "likes tea", UserID: apitest.LocalAlice()})
+ cache := &recordingForgetter{}
+ f := newTrustFixture(t, apitest.Options{Memories: memory.NewService(fake, nil), MemoriesCache: cache})
+ personal, _, err := f.Tokens.Create(context.Background(), model.Actor{Person: apitest.LocalAlice()}, token.Token{
+ Name: "laptop", Owner: apitest.LocalAlice(), Scope: token.ScopeReadWrite,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.trust(f.alice, 8)
+ want := reasons.Msg(reasons.MsgMemoryDeleteSessionOnly)
+
+ tests := []struct {
+ name string
+ do func() *httptest.ResponseRecorder
+ }{
+ {"a trusted coding agent's own token cannot delete a memory", func() *httptest.ResponseRecorder {
+ return f.agent("DELETE", "/api/memories/a-1", "")
+ }},
+ {"a personal API token cannot delete a memory", func() *httptest.ResponseRecorder {
+ return f.Bearer("DELETE", "/api/memories/a-1", "", personal, nil)
+ }},
+ {"an ordinary app token cannot delete a memory", func() *httptest.ResponseRecorder {
+ g := newAgentFixtureWith(t, false, apitest.Options{Memories: memory.NewService(fake, nil), MemoriesCache: cache})
+ return g.agent("DELETE", "/api/memories/a-1", "")
+ }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ w := tc.do()
+ wantCode(t, tc.name, w, http.StatusForbidden)
+ if !strings.Contains(w.Body.String(), want) {
+ t.Errorf("body %s lacks %q", w.Body, want)
+ }
+ if got := memoryDeletes(fake); len(got) != 0 {
+ t.Errorf("the store was asked to delete %v", got)
+ }
+ if got := cache.got(); len(got) != 0 {
+ t.Errorf("recall cache forgot %v", got)
+ }
+ })
+ }
+
+ t.Run("a trusted coding agent's token can still list memories", func(t *testing.T) {
+ wantCode(t, "list", f.agent("GET", "/api/memories", ""), http.StatusOK)
+ })
+ t.Run("a browser session deletes a memory", func(t *testing.T) {
+ wantCode(t, "delete", f.Do("DELETE", "/api/memories/a-1", "", f.alice), http.StatusNoContent)
+ if got := memoryDeletes(fake); len(got) != 1 {
+ t.Errorf("deletes %v", got)
+ }
+ })
+}
diff --git a/internal/reasons/messages.go b/internal/reasons/messages.go
index cf598a19..18f5e1f3 100644
--- a/internal/reasons/messages.go
+++ b/internal/reasons/messages.go
@@ -272,6 +272,8 @@ const (
MsgMemoryUnreachable MessageCode = "MemoryUnreachable"
MsgMemoryNotFound MessageCode = "MemoryNotFound"
+ MsgMemoryDeleteSessionOnly MessageCode = "MemoryDeleteSessionOnly"
+
// Secrets.
MsgSecretNotFound MessageCode = "SecretNotFound"
MsgSecretNameInvalid MessageCode = "SecretNameInvalid"
@@ -602,6 +604,8 @@ var messages = map[MessageCode]string{
MsgMemoryUnreachable: "Memory could not be reached; try again later.",
MsgMemoryNotFound: "No memory with that id.",
+ MsgMemoryDeleteSessionOnly: "Only you, signed in in the browser, can delete a memory. No API token can, not even an agent's own.",
+
MsgSecretNotFound: "No secret with that name.",
MsgSecretNameInvalid: "Use a name of up to 100 letters, digits and underscores that does not start with a digit, such as OPENAI_API_KEY.",
MsgSecretNameTaken: "You already have a secret with this name. Pick another name, or change that secret's value.",
diff --git a/ui/openapi.json b/ui/openapi.json
index 32a7ca7e..ad542507 100644
--- a/ui/openapi.json
+++ b/ui/openapi.json
@@ -10991,7 +10991,7 @@
},
"/api/memories/{id}": {
"delete": {
- "description": "Another person's memory is a 404, the same as one that does not exist.",
+ "description": "Only you, signed in in the browser, can delete a memory. No API token can, not even a coding agent's own, so this answers 403 to any token. Another person's memory is a 404, the same as one that does not exist.",
"operationId": "deleteMemory",
"parameters": [
{
@@ -11070,7 +11070,12 @@
"description": "Bad Gateway"
}
},
- "summary": "Delete one of your memories",
+ "security": [
+ {
+ "session": []
+ }
+ ],
+ "summary": "Delete one of your memories (browser session only)",
"tags": [
"memories"
]
diff --git a/ui/src/api/sdk.gen.ts b/ui/src/api/sdk.gen.ts
index 1bd899d1..059e45ce 100644
--- a/ui/src/api/sdk.gen.ts
+++ b/ui/src/api/sdk.gen.ts
@@ -978,16 +978,16 @@ export const listMemories = (options?: Opt
});
/**
- * Delete one of your memories
+ * Delete one of your memories (browser session only)
*
- * Another person's memory is a 404, the same as one that does not exist.
+ * Only you, signed in in the browser, can delete a memory. No API token can, not even a coding agent's own, so this answers 403 to any token. Another person's memory is a 404, the same as one that does not exist.
*/
export const deleteMemory = (options: Options): RequestResult => (options.client ?? client).delete({
security: [{
in: 'cookie',
name: '__Host-javo_session',
type: 'apiKey'
- }, { scheme: 'bearer', type: 'http' }],
+ }],
url: '/api/memories/{id}',
...options
});
From 763d296c9ba3eccff35660975b87ccd22e0dbf38 Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Mon, 30 Nov 2026 09:51:38 +0100
Subject: [PATCH 10/11] docs: memory SSN check, browser-only delete and recall
delay
Say that only an SSN written with dashes is refused, that deleting a
memory works only from the browser, that recall of a deleted memory can
last a couple of minutes, and that long typed messages log too_long.
---
site/src/content/docs/admin/memory.md | 6 +++---
site/src/content/docs/using/ask-ai.md | 4 ++--
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/site/src/content/docs/admin/memory.md b/site/src/content/docs/admin/memory.md
index e541b964..a608c39c 100644
--- a/site/src/content/docs/admin/memory.md
+++ b/site/src/content/docs/admin/memory.md
@@ -14,8 +14,8 @@ Memory works only on calls to the admin's agent model (`ai.agent`, see [AI](/adm
- **Recall.** Before an agent's model call, the gateway searches the person's memories for their latest message (on every call, including the agent's steps after a tool result). It adds up to 5 matches (each cut to 500 characters, 2500 in all) to the call's system message as a note that tells the model to use them when relevant and not to mention the note. Results are kept for 2 minutes per person and query, so the repeated steps of one agent turn search once. A search waits at most `recallTimeout`; if it fails or runs out of time, the call goes on without memories.
- **Learning.** After a call that answers something the person typed, the gateway sends the typed text and the start of the answer (at most 4000 characters) to mem0 in the background, and mem0 keeps only lasting facts about the person: their name, role, team, skills, preferred tools and languages, how they like answers written, and standing instructions. Nothing is kept about the task, code, file contents, errors or command output. A step where the agent continues after a tool result, with no new typed text, is not learned from.
- **"Remember that ...".** A message that starts with `remember that ...` or `remember: ...` is stored as it is, without extraction. A sentence longer than 1000 characters is skipped.
-- **Social Security numbers.** A write whose text holds a US Social Security number is refused; the number is never stored or logged.
-- **The Memories page.** Each person sees their memories under **Settings > Memories**, newest first, and can delete any of them. Deleting also clears that person's cached recall results on that gateway. The page is served by `GET /api/memories` and `DELETE /api/memories/{id}`, which browser sessions and personal API tokens can call; an app's or a job's own token is refused with 403, except the token of a coding agent whose owner has let it act without asking. With memory off both answer 404 "Memory is off on this platform."; when mem0 cannot be reached they answer 502 "Memory could not be reached; try again later." and the gateway logs the cause.
+- **Social Security numbers.** A write whose text holds a US Social Security number written with dashes (`123-45-6789`) is refused; the number is never stored or logged. Other spellings, such as nine digits with no dashes or with spaces, are not detected and can be stored.
+- **The Memories page.** Each person sees their memories under **Settings > Memories**, newest first, and can delete any of them. Deleting also clears that person's cached recall results on that gateway. The page is served by `GET /api/memories` and `DELETE /api/memories/{id}`. Deleting works only from a signed-in browser session: any API token is refused with 403 "Only you, signed in in the browser, can delete a memory. No API token can, not even an agent's own.", whether it is a coding agent's own token (even one its owner has let act without asking), an app's or a job's token, or a person's personal API token. Listing is open to a browser session, to personal API tokens and to the token of a coding agent whose owner has let it act without asking, as it is for reading secrets; an app's or a job's own token is refused with 403. With memory off both answer 404 "Memory is off on this platform."; when mem0 cannot be reached they answer 502 "Memory could not be reached; try again later." and the gateway logs the cause.
A coding agent running on a person's own key (**Settings > Secrets > AI agent**) bypasses the gateway, so it gets no recall and learns nothing. Only the admin's agent model has memory. The suggestions in New app's **Describe it** box, Explain more and the other model features do not use memory either.
@@ -94,7 +94,7 @@ While agents run:
| `memory.learned` (`count`) | info | mem0 stored `count` memories from a turn. `count` is 0 when it found no lasting fact. |
| `memory.learn_failed` (`err`) | warn | mem0 could not be reached or refused the add. Nothing was stored for that turn. |
| `memory.learn_skipped` (`reason=busy`) | info | Four learn calls were already running on this gateway, so this turn was not learned from. |
-| `memory.learn_skipped` (`reason=too_long`) | info | A "remember that" sentence was longer than 1000 characters and was not stored. |
+| `memory.learn_skipped` (`reason=too_long`) | info | A "remember that" sentence was longer than 1000 characters, or the typed message was longer than 8000 characters, so it was not stored or learned from. |
| `memory.write_refused` (`reason=ssn`) | info | The text held a Social Security number, so nothing was sent to mem0. |
| `memory.learn_panicked` (`stack`) | error | A bug in learning was caught. The person's request was already answered and the gateway kept running. Report it with the stack. |
| `memory.list_failed`, `memory.delete_failed` (`err`) | warn | The Memories page could not reach mem0. The person saw the 502 message above. |
diff --git a/site/src/content/docs/using/ask-ai.md b/site/src/content/docs/using/ask-ai.md
index bdfd7d2d..5845bd1e 100644
--- a/site/src/content/docs/using/ask-ai.md
+++ b/site/src/content/docs/using/ask-ai.md
@@ -25,9 +25,9 @@ When your admin gives coding agents a model, or you stored your own key in **Set
When your admin turns memory on and gives coding agents a model, the agents you start (such as pi) remember lasting things you tell them: your name and role, the tools and languages you prefer, how you like answers or code written, and standing instructions. They do not keep what a task was about, code, file contents, errors or command output. The next time you write to an agent, what is relevant is added to its prompt, even in a different app or conversation.
-To save something on purpose, start a message with `remember that ...` (or `remember: ...`), for example `remember that I prefer Polars over pandas`. It is stored as you wrote it. Text with a Social Security number is never stored.
+To save something on purpose, start a message with `remember that ...` (or `remember: ...`), for example `remember that I prefer Polars over pandas`. It is stored as you wrote it. Text with a US Social Security number written with dashes (`123-45-6789`) is never stored; other spellings, such as no dashes or spaces, are not detected, so do not put one in a memory.
-See what is remembered under **Settings > Memories**, newest first, and delete any of it with **Delete**; agents stop recalling it. The page says so when memory is off. Memories are yours alone: other people and their agents never see or recall them, and Tapas has no page that shows them to admins. (Whoever holds the memory service's admin key can read its store; see Limits on the [admin Memory page](/admin/memory/).) An agent running on your own key from **Settings > Secrets > AI agent** does not use or learn memories.
+See what is remembered under **Settings > Memories**, newest first, and delete any of it with **Delete**. Deleting works only on that page, signed in in the browser: no API token can delete a memory, not even your coding agent's own, though an agent you have let act without asking can still list them. After a delete, agents stop recalling that memory, which can take a couple of minutes because each gateway replica keeps recall results for up to 2 minutes. The page says so when memory is off. Memories are yours alone: other people and their agents never see or recall them, and Tapas has no page that shows them to admins. (Whoever holds the memory service's admin key can read its store; see Limits on the [admin Memory page](/admin/memory/).) An agent running on your own key from **Settings > Secrets > AI agent** does not use or learn memories.
## Coding agents (MCP)
From 588244921536f0487d3070261ef137fdbf0d311a Mon Sep 17 00:00:00 2001
From: Chuck McAndrew <6248903+dcmcand@users.noreply.github.com>
Date: Tue, 1 Dec 2026 14:41:14 +0100
Subject: [PATCH 11/11] fix(agentproxy): don't learn an exchange the agent
didn't fully receive
When an agent disconnected mid-answer, the cancelled request context
ended the upstream read, but copyEvents ignored sc.Err() and returned
nil, so the cut-off answer was learned. The non-streamed path ignored
the io.ReadAll error the same way, learning the typed turn alone.
copyEvents now returns the error that ended reading, the non-streamed
path carries its read error, and learning also requires the request
context to be live, which catches an agent that went away as the last
bytes of a complete answer were written.
---
internal/ai/agentproxy/agentproxy.go | 14 ++-
internal/ai/agentproxy/learn_test.go | 162 +++++++++++++++++++++++++++
2 files changed, 172 insertions(+), 4 deletions(-)
diff --git a/internal/ai/agentproxy/agentproxy.go b/internal/ai/agentproxy/agentproxy.go
index 0ab07c8c..e0b6eda5 100644
--- a/internal/ai/agentproxy/agentproxy.go
+++ b/internal/ai/agentproxy/agentproxy.go
@@ -10,6 +10,7 @@ package agentproxy
import (
"bufio"
"bytes"
+ "cmp"
"context"
"encoding/json"
"errors"
@@ -215,8 +216,9 @@ func (p *Proxy) chat(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
in, outTok, _, werr = copyEvents(w, resp.Body, ans)
} else {
- b, _ := io.ReadAll(io.LimitReader(resp.Body, maxAnswerBytes))
+ b, rerr := io.ReadAll(io.LimitReader(resp.Body, maxAnswerBytes))
_, werr = w.Write(b)
+ werr = cmp.Or(rerr, werr)
in, outTok, _ = usageOf(b)
ans.addMessage(b)
}
@@ -225,7 +227,10 @@ func (p *Proxy) chat(w http.ResponseWriter, r *http.Request) {
result = fmt.Sprintf("status %d", resp.StatusCode)
}
audit(person, model, in, outTok, result)
- if ans != nil && resp.StatusCode/100 == 2 && werr == nil {
+ // werr covers a failed read or write; the context covers an agent that went
+ // away while every write still succeeded. Either way the agent did not get
+ // the whole answer, so the exchange is not learned.
+ if ans != nil && resp.StatusCode/100 == 2 && werr == nil && r.Context().Err() == nil {
p.startLearning(r.Context(), person, text, ans.String())
}
}
@@ -316,7 +321,8 @@ func (p *Proxy) client(up Upstream) *http.Client {
// copyEvents passes a server-sent event stream through line by line,
// flushing each event, and reads the usage the last events report. When ans
// is not nil it collects the answer text the events carry. err is the first
-// error writing to w, after which copying stops.
+// error writing to w, after which copying stops, or else the error that ended
+// reading r early.
func copyEvents(w http.ResponseWriter, r io.Reader, ans *answer) (in, out int, found bool, err error) {
f, _ := w.(http.Flusher)
sc := bufio.NewScanner(r)
@@ -340,7 +346,7 @@ func copyEvents(w http.ResponseWriter, r io.Reader, ans *answer) (in, out int, f
if f != nil {
f.Flush()
}
- return in, out, found, nil
+ return in, out, found, sc.Err()
}
// usageOf reads the usage of an answer or an event.
diff --git a/internal/ai/agentproxy/learn_test.go b/internal/ai/agentproxy/learn_test.go
index cbb6f68d..5711adc8 100644
--- a/internal/ai/agentproxy/learn_test.go
+++ b/internal/ai/agentproxy/learn_test.go
@@ -249,6 +249,115 @@ func (b *brokenWriter) Write(p []byte) (int, error) {
return b.ResponseRecorder.Write(p)
}
+// stalled is a provider that sends part of an answer, then waits until the
+// proxy gives up on the call. The status is 200 and a non-streamed answer
+// claims more bytes than it sends, so the proxy keeps reading.
+func stalled(t *testing.T, contentType, part string) *httptest.Server {
+ t.Helper()
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.Copy(io.Discard, r.Body)
+ w.Header().Set("Content-Type", contentType)
+ if contentType != "text/event-stream" {
+ w.Header().Set("Content-Length", "4096")
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, part)
+ w.(http.Flusher).Flush()
+ <-r.Context().Done()
+ }))
+ t.Cleanup(s.Close)
+ return s
+}
+
+// dropped is a provider that sends part of an answer, then closes the
+// connection without ending it. A non-streamed answer claims more bytes than
+// it sends.
+func dropped(t *testing.T, contentType, part string) *httptest.Server {
+ t.Helper()
+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = io.Copy(io.Discard, r.Body)
+ w.Header().Set("Content-Type", contentType)
+ if contentType != "text/event-stream" {
+ w.Header().Set("Content-Length", "4096")
+ }
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, part)
+ w.(http.Flusher).Flush()
+ conn, _, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ _ = conn.Close()
+ }))
+ t.Cleanup(s.Close)
+ return s
+}
+
+// serveUntilCancelled sends body to h and cancels the request's context once
+// the first bytes of the answer reach the agent, as a disconnect does.
+func serveUntilCancelled(t *testing.T, h http.Handler, body string) {
+ t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r := httptest.NewRequest("POST", agentproxy.Route+"/chat/completions", strings.NewReader(body)).WithContext(ctx)
+ r.Header.Set("Content-Type", "application/json")
+ w := &firstWrite{ResponseRecorder: httptest.NewRecorder(), seen: make(chan struct{})}
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ h.ServeHTTP(w, r)
+ }()
+ select {
+ case <-w.seen:
+ case <-done:
+ t.Fatal("the handler returned before the answer started")
+ case <-time.After(5 * time.Second):
+ t.Fatal("the answer never started")
+ }
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the handler did not return after the cancel")
+ }
+}
+
+// firstWrite is an agent whose writes all succeed; seen closes on the first
+// one, or on WriteHeader for an answer whose body has not arrived yet.
+type firstWrite struct {
+ *httptest.ResponseRecorder
+ seen chan struct{}
+ once sync.Once
+}
+
+func (f *firstWrite) WriteHeader(code int) {
+ f.ResponseRecorder.WriteHeader(code)
+ f.once.Do(func() { close(f.seen) })
+}
+
+func (f *firstWrite) Write(p []byte) (int, error) {
+ n, err := f.ResponseRecorder.Write(p)
+ f.once.Do(func() { close(f.seen) })
+ return n, err
+}
+
+// cancelOn is an agent whose writes all succeed; it calls cancel once a write
+// holds marker.
+type cancelOn struct {
+ *httptest.ResponseRecorder
+ marker string
+ cancel context.CancelFunc
+}
+
+func (c *cancelOn) Write(p []byte) (int, error) {
+ n, err := c.ResponseRecorder.Write(p)
+ if strings.Contains(string(p), c.marker) {
+ c.cancel()
+ }
+ return n, err
+}
+
func TestLearnSkipsFailedAnswers(t *testing.T) {
t.Run("upstream 500", func(t *testing.T) {
mem := &learnMemory{}
@@ -271,6 +380,59 @@ func TestLearnSkipsFailedAnswers(t *testing.T) {
t.Fatalf("adds %+v, want none", adds)
}
})
+ // A real disconnect cancels the request's context, which ends the upstream
+ // read while writes to the agent still succeed (unlike brokenWriter).
+ t.Run("client context cancelled mid-stream", func(t *testing.T) {
+ mem := &learnMemory{}
+ p, h := learnProxy(stalled(t, "text/event-stream", events(`{"choices":[{"delta":{"role":"assistant","content":"No"}}]}`)), mem)
+ serveUntilCancelled(t, h, userTurn("I use Go 1.25 at work", true))
+ agentproxy.WaitLearning(p)
+ if adds, _ := mem.calls(); len(adds) != 0 {
+ t.Fatalf("adds %+v, want none", adds)
+ }
+ })
+ t.Run("client context cancelled during a non-streamed answer", func(t *testing.T) {
+ mem := &learnMemory{}
+ p, h := learnProxy(stalled(t, "application/json", `{"choices":[{"message":{"role":"assistant","content":"No`), mem)
+ serveUntilCancelled(t, h, userTurn("I use Go 1.25 at work", false))
+ agentproxy.WaitLearning(p)
+ if adds, _ := mem.calls(); len(adds) != 0 {
+ t.Fatalf("adds %+v, want none", adds)
+ }
+ })
+ t.Run("upstream connection drops mid-stream", func(t *testing.T) {
+ mem := &learnMemory{}
+ p, h := learnProxy(dropped(t, "text/event-stream", events(`{"choices":[{"delta":{"role":"assistant","content":"No"}}]}`)), mem)
+ post(h, userTurn("I use Go 1.25 at work", true))
+ agentproxy.WaitLearning(p)
+ if adds, _ := mem.calls(); len(adds) != 0 {
+ t.Fatalf("adds %+v, want none", adds)
+ }
+ })
+ t.Run("upstream connection drops during a non-streamed answer", func(t *testing.T) {
+ mem := &learnMemory{}
+ p, h := learnProxy(dropped(t, "application/json", `{"choices":[{"message":{"role":"assistant","content":"No`), mem)
+ post(h, userTurn("I use Go 1.25 at work", false))
+ agentproxy.WaitLearning(p)
+ if adds, _ := mem.calls(); len(adds) != 0 {
+ t.Fatalf("adds %+v, want none", adds)
+ }
+ })
+ // The provider finished, but the agent went away as the last bytes were
+ // written; only the request's context shows it.
+ t.Run("client context cancelled at the end of a complete stream", func(t *testing.T) {
+ mem := &learnMemory{}
+ p, h := learnProxy(scripted(t, 200, "text/event-stream", notedStream()), mem)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r := httptest.NewRequest("POST", agentproxy.Route+"/chat/completions", strings.NewReader(userTurn("I use Go 1.25 at work", true))).WithContext(ctx)
+ r.Header.Set("Content-Type", "application/json")
+ h.ServeHTTP(&cancelOn{ResponseRecorder: httptest.NewRecorder(), marker: "[DONE]", cancel: cancel}, r)
+ agentproxy.WaitLearning(p)
+ if adds, _ := mem.calls(); len(adds) != 0 {
+ t.Fatalf("adds %+v, want none", adds)
+ }
+ })
t.Run("client gone before a non-streamed answer", func(t *testing.T) {
mem := &learnMemory{}
p, h := learnProxy(scripted(t, 200, "application/json", notedJSON), mem)