Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(pi): avoid blocking user message rendering on recall (#3233)

pppobear5a6a1a0a0386
diff --git a/examples/pi-coding-agent-extension/DESIGN.md b/examples/pi-coding-agent-extension/DESIGN.md
index 742213390..76edfe505 100644
--- a/examples/pi-coding-agent-extension/DESIGN.md
+++ b/examples/pi-coding-agent-extension/DESIGN.md
@@ -282,7 +282,7 @@ The `context` event fires before each LLM call with a mutable deep copy of messa
3. If not injected: prepend `<relevant-memories>` block to the user message content
4. If already injected: skip (cached from first context call for this prompt)
-The recall search itself only runs once per prompt (cached in `before_agent_start`). The `context` handler just re-injects the cached block on each LLM iteration.
+The recall search itself only runs once per prompt. `before_agent_start` queues the current prompt without network I/O; the first `context` call consumes it and performs the synchronous search after Pi has rendered the user message. Later LLM iterations reuse the cached block.
```typescript
class RecallManager {
@@ -292,8 +292,11 @@ class RecallManager {
constructor(client: OVClient);
- // Called in before_agent_start — runs the actual triple-scope search + profiling + ranking
- async searchAndCache(userQuery: string): Promise<string | null>;
+ // Called in before_agent_start — records the current prompt without I/O
+ queueSearch(userQuery: string): void;
+
+ // Called on the first context event — runs search and caches the result
+ async searchPending(): Promise<string | null>;
// Called in context event — injects cached block into messages
injectRecall(messages: Message[]): Message[];
@@ -623,8 +626,8 @@ Main entry point. Wires everything together.
| Event | Handler | What it does |
|-------|---------|-------------|
| `session_start` | Init + Resume + Profile | Health check OV, check bypass, create/reuse session, **inject user profile** (profile.md + preferences/ + entities/ listing, capped at `profileBudget`), on resume: fetch archive overview, build memory index, register tools |
-| `before_agent_start` | Recall + System prompt | Synchronous recall search, inject memory index + tool ad into system prompt |
-| `context` | Recall injection | Prepend `<relevant-memories>` to user message (re-inject cached block on each LLM iteration) |
+| `before_agent_start` | Recall queue + System prompt | Queue current prompt without I/O, inject memory index + tool ad into system prompt |
+| `context` | Recall search + injection | Search after user-message rendering, then prepend `<relevant-memories>` (reuse cached block on later LLM iterations) |
| `turn_end` | Sync | Strip all injected blocks, **capture filter (shouldCapture)**, **preserve tool USE inputs + tool summary line**, drop tool RESULTS, **enqueue to write queue** (auto-flushes at threshold/interval), track pending tokens, check commit threshold |
| `session_before_compact` | Pre-compact commit + rehydration | Synchronous `commit(wait=true)` before pi rewrites the transcript, then fetch new archive overview and cache for next `before_agent_start` injection — content about to be compacted is preserved in OV and rehydrated after compaction |
| `session_shutdown` | Final commit | Commit OV session (blocking), rebuild index, optionally mirror MEMORY.md |
@@ -727,20 +730,23 @@ A `/viking commit` command (or a `viking_commit` tool) triggers a synchronous `c
```
1. before_agent_start fires
a. Extract user prompt text
- b. recall.searchAndCache(prompt) ← SYNCHRONOUS OV search (~50-200ms)
+ b. recall.queueSearch(prompt) ← no network I/O
c. Compose system prompt: event.systemPrompt + profileBlock + archiveOverview + indexBuilder.getIndex() + toolAdBlock
- Profile block: cached from session_start (or empty if OV has no profile)
- Archive overview: cached from session_start resume, or from pre-compact rehydration
d. Return { systemPrompt: composed }
-2. [For each LLM iteration within this prompt:]
+2. Pi renders the submitted user message.
+
+3. [For each LLM iteration within this prompt:]
a. context event fires
- b. recall.injectRecall(event.messages) ← prepend cached <relevant-memories> to user message
- c. Return { messages: modified }
+ b. recall.searchPending() ← first iteration only; synchronous OV search for the current prompt
+ c. recall.injectRecall(event.messages) ← prepend cached <relevant-memories> to user message
+ d. Return { messages: modified }
-3. [Turns execute — LLM may call viking_search, etc.]
+4. [Turns execute — LLM may call viking_search, etc.]
-4. agent_end fires
+5. agent_end fires
a. recall.invalidate() ← clear cached block
```
diff --git a/examples/pi-coding-agent-extension/README.md b/examples/pi-coding-agent-extension/README.md
index df00156ba..60fadf6e0 100644
--- a/examples/pi-coding-agent-extension/README.md
+++ b/examples/pi-coding-agent-extension/README.md
@@ -179,15 +179,15 @@ The extension is a single directory of TypeScript files loaded by pi's `jiti` tr
| Pi Event | Extension Action |
|------------------------|----------------------------------------------------------------------------------|
| `session_start` | Health check → derive OV session → build profile context → restore takeover state |
-| `before_agent_start` | Idempotent startup for `pi -c` + synchronous recall search |
-| `context` | Takeover overview injection, then recall injection into the latest user turn |
+| `before_agent_start` | Idempotent startup for `pi -c` + queue the current prompt for recall |
+| `context` | Run current-prompt recall after UI rendering, then inject takeover and recall context |
| `turn_end` | Extract branch entries → write or pending-queue OV messages → maybe advance boundary |
| `session_before_compact`| Takeover mode returns OV overview as pi compaction summary; otherwise commits pending messages |
| `session_shutdown` | Persist takeover state or final non-takeover commit |
### Recall: Synchronous, Not Stale
-Unlike Hermes's stale prefetch (recall from previous turn's query, injected one turn late), this extension searches OpenViking with the **current** user prompt via pi's `context` event. Results are injected into the same turn as `<openviking-context>` blocks. This means:
+Unlike Hermes's stale prefetch (recall from previous turn's query, injected one turn late), this extension searches OpenViking with the **current** user prompt via pi's `context` event. Pi renders the submitted user message before this hook, so recall latency does not hold the message off-screen. Results are still injected into the same model turn as `<openviking-context>` blocks. This means:
- **First turn** of a session gets relevant context immediately
- **Topic switches** within a session get correct recall
diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.ts
index f1a2ef88c..ad8366d29 100644
--- a/examples/pi-coding-agent-extension/index.ts
+++ b/examples/pi-coding-agent-extension/index.ts
@@ -137,8 +137,9 @@ export default async function (pi: ExtensionAPI) {
if (!connected || bypassed) return;
- // Synchronous recall
- await recall.searchAndCache(event.prompt);
+ // Queue recall for the context hook. Pi renders the user message before
+ // that hook, so recall latency does not delay the message appearing.
+ recall.queueSearch(event.prompt);
// Compose system prompt additions
const parts: string[] = [];
@@ -159,6 +160,11 @@ export default async function (pi: ExtensionAPI) {
// --- context ---
pi.on("context", async (event, _ctx) => {
if (!connected || bypassed) return;
+
+ // Keep recall synchronous with the provider request so the current prompt
+ // still receives current-query memory, without blocking user-message UI.
+ await recall.searchPending();
+
const afterTakeover = config.takeoverEnabled
? takeover.transformContext(event.messages as any)
: event.messages;
diff --git a/examples/pi-coding-agent-extension/recall.ts b/examples/pi-coding-agent-extension/recall.ts
index bf76fc99e..89846fff8 100644
--- a/examples/pi-coding-agent-extension/recall.ts
+++ b/examples/pi-coding-agent-extension/recall.ts
@@ -11,14 +11,24 @@ export class RecallManager {
private client: OVClient;
private config: OVConfig;
private cache: RecallCache = { block: null, promptText: "" };
+ private pendingPrompt = "";
constructor(client: OVClient, config: OVConfig) {
this.client = client;
this.config = config;
}
- async searchAndCache(userQuery: string): Promise<string | null> {
+ queueSearch(userQuery: string): void {
+ this.pendingPrompt = userQuery;
+ }
+
+ async searchPending(): Promise<string | null> {
+ if (!this.pendingPrompt) return this.cache.block;
+
+ const userQuery = this.pendingPrompt;
+ this.pendingPrompt = "";
if (userQuery.trim().length < this.config.minQueryLength) {
+ this.cache = { block: null, promptText: userQuery };
return null;
}
@@ -68,5 +78,6 @@ export class RecallManager {
invalidate(): void {
this.cache = { block: null, promptText: "" };
+ this.pendingPrompt = "";
}
}
diff --git a/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs b/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs
new file mode 100644
index 000000000..f5d0220da
--- /dev/null
+++ b/examples/pi-coding-agent-extension/tests/recall-deferred.test.mjs
@@ -0,0 +1,64 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { RecallManager } from "../recall.ts";
+
+function config(overrides = {}) {
+ return {
+ minQueryLength: 3,
+ recallLimit: 6,
+ recallMaxContentChars: 500,
+ recallTokenBudget: 2000,
+ scoreThreshold: 0.35,
+ peerId: "",
+ ...overrides,
+ };
+}
+
+test("queued recall waits for the context phase and still injects current-query memory", async () => {
+ const calls = [];
+ const client = {
+ fetchJSON: async (path, init) => {
+ calls.push({ path, init });
+ return {
+ ok: true,
+ result: { rendered: "- current prompt memory" },
+ };
+ },
+ };
+ const recall = new RecallManager(client, config());
+
+ recall.queueSearch("current prompt");
+ assert.equal(calls.length, 0, "queueing in before_agent_start must not perform I/O");
+
+ await recall.searchPending();
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].path, "/api/v1/search/recall");
+
+ const messages = [{ role: "user", content: "current prompt" }];
+ const injected = recall.injectRecall(messages);
+ assert.match(injected[0].content, /current prompt memory/);
+ assert.match(injected[0].content, /current prompt$/);
+
+ await recall.searchPending();
+ assert.equal(calls.length, 1, "later context iterations must reuse the cached recall");
+});
+
+test("a queued short prompt clears the previous recall block", async () => {
+ const client = {
+ fetchJSON: async () => ({
+ ok: true,
+ result: { rendered: "- stale memory" },
+ }),
+ };
+ const recall = new RecallManager(client, config());
+
+ recall.queueSearch("long enough prompt");
+ await recall.searchPending();
+
+ recall.queueSearch("x");
+ await recall.searchPending();
+
+ const messages = [{ role: "user", content: "x" }];
+ assert.deepEqual(recall.injectRecall(messages), messages);
+ assert.equal(messages[0].content, "x");
+});