Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/fix-auto-index-tenant-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@voltagent/core": patch
---

fix(core): defer WorkspaceSearch auto-index to support tenant-aware filesystems

Auto-indexing now runs lazily on the first `search()` or `init()` call instead of eagerly in the constructor. This ensures tenant-aware filesystem backends that require `operationContext` (e.g. `conversationId`) receive the context from the caller. If auto-indexing fails (e.g. missing context), subsequent calls with valid context will retry automatically.

Fixes #1252
105 changes: 104 additions & 1 deletion packages/core/src/workspace/search/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import { Workspace } from "..";
import type { EmbeddingAdapter } from "../../memory/adapters/embedding/types";
import { InMemoryVectorAdapter } from "../../memory/adapters/vector/in-memory";
import { WorkspaceFilesystem } from "../filesystem";
import { InMemoryFilesystemBackend, WorkspaceFilesystem } from "../filesystem";
import { WorkspaceSearch, createWorkspaceSearchToolkit } from "./index";

const createExecuteOptions = () => ({
Expand Down Expand Up @@ -200,6 +200,109 @@ describe("WorkspaceSearch", () => {
expect(modelOutput?.value).toContain("bm25=");
});

it("defers auto-index until search provides context for tenant-aware filesystem", async () => {
const files = {
"/workspace/a.ts": buildFileData("export const tenant = 'a';"),
};
const dirs = new Set(["/workspace/"]);

let callCount = 0;
const tenantBackend = (ctx: any) => {
callCount++;
const cid = ctx?.operationContext?.conversationId;
if (!cid) {
throw new Error("Tenant filesystem requires operationContext.conversationId");
}
return new InMemoryFilesystemBackend(files, dirs);
};

const filesystem = new WorkspaceFilesystem({ backend: tenantBackend as any });
const search = new WorkspaceSearch({
filesystem,
autoIndexPaths: [{ path: "/workspace", glob: "**/*.ts" }],
});

// Constructor should NOT have called the backend
expect(callCount).toBe(0);

// Search with proper context should trigger auto-index and succeed
const results = await search.search("tenant", {
path: "/workspace",
context: {
operationContext: { conversationId: "conv-a" } as any,
},
});

expect(callCount).toBeGreaterThan(0);
expect(results.length).toBe(1);
expect(results[0].path).toBe("/workspace/a.ts");
});

it("retries auto-index when previous attempt failed without context", async () => {
const files = {
"/workspace/b.ts": buildFileData("export const value = 2;"),
};
const dirs = new Set(["/workspace/"]);

let attempt = 0;
const tenantBackend = (ctx: any) => {
attempt++;
const cid = ctx?.operationContext?.conversationId;
if (!cid) {
throw new Error("Missing conversationId");
}
return new InMemoryFilesystemBackend(files, dirs);
};

const filesystem = new WorkspaceFilesystem({ backend: tenantBackend as any });
const search = new WorkspaceSearch({
filesystem,
autoIndexPaths: [{ path: "/workspace", glob: "**/*.ts" }],
});

// First search without context — auto-index should fail and allow retry
const empty = await search.search("value", { path: "/workspace" });
expect(empty.length).toBe(0);

// Second search with context — should retry auto-index and succeed
const results = await search.search("value", {
path: "/workspace",
context: {
operationContext: { conversationId: "conv-b" } as any,
},
});

expect(results.length).toBe(1);
expect(results[0].path).toBe("/workspace/b.ts");
});

it("does not re-run auto-index after successful completion", async () => {
let indexCallCount = 0;
const filesystem = new WorkspaceFilesystem({
files: {
"/workspace/c.ts": buildFileData("export const c = 3;"),
},
});

const search = new WorkspaceSearch({
filesystem,
autoIndexPaths: [{ path: "/workspace", glob: "**/*.ts" }],
});

const origIndexPaths = search.indexPaths.bind(search);
search.indexPaths = async (...args: any[]) => {
indexCallCount++;
return origIndexPaths(...args);
};

await search.search("c", { path: "/workspace" });
const firstCount = indexCallCount;

await search.search("c", { path: "/workspace" });
// indexPaths should not have been called again
expect(indexCallCount).toBe(firstCount);
});

it("can return snippet-only output when include_content is false", async () => {
const workspace = new Workspace({ search: {} });
const toolkit = workspace.createSearchToolkit();
Expand Down
29 changes: 19 additions & 10 deletions packages/core/src/workspace/search/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ export class WorkspaceSearch {
private readonly defaultMode: WorkspaceSearchMode;
private readonly defaultWeights: { lexicalWeight: number; vectorWeight: number };
private autoIndexPromise?: Promise<void>;
private autoIndexDone = false;
status: WorkspaceComponentStatus = "idle";

constructor(options: WorkspaceSearchConfig & { filesystem: WorkspaceFilesystem }) {
Expand All @@ -232,14 +233,9 @@ export class WorkspaceSearch {
vectorWeight: options.hybrid?.vectorWeight ?? DEFAULT_HYBRID_VECTOR_WEIGHT,
};

if (this.autoIndexPaths && this.autoIndexPaths.length > 0) {
this.autoIndexPromise = this.indexPaths(this.autoIndexPaths)
.then(() => undefined)
.catch((error) => {
console.error("Workspace search auto-index failed:", error);
return undefined;
});
}
// Auto-indexing is deferred to ensureAutoIndex() so that
// tenant-aware filesystems receive the operationContext
// supplied by the first search() or init() call.
}

async init(): Promise<void> {
Expand Down Expand Up @@ -275,12 +271,25 @@ export class WorkspaceSearch {
if (!this.autoIndexPaths || this.autoIndexPaths.length === 0) {
return;
}
if (this.autoIndexDone) {
return;
}
if (!this.autoIndexPromise) {
this.autoIndexPromise = this.indexPaths(this.autoIndexPaths, { context })
.then(() => undefined)
.then((summary) => {
// Mark complete only if something was indexed or no errors occurred.
// When all paths error (e.g. missing context for tenant FS),
// allow retry on the next call with potentially valid context.
if (summary.indexed > 0 || summary.errors.length === 0) {
this.autoIndexDone = true;
} else {
this.autoIndexPromise = undefined;
}
})
.catch((error) => {
console.error("Workspace search auto-index failed:", error);
return undefined;
// Allow retry on next call with potentially valid context
this.autoIndexPromise = undefined;
});
}
await this.autoIndexPromise;
Expand Down