Skip to content

Commit a2bf4c0

Browse files
fix: disable FFF background scans in managed OpenCode engines (#298)
## Summary An ordinary chat can make the bundled OpenCode engine read project files while FFF initializes, even when the agent calls no tools. On OneDrive this can trigger unwanted downloads. Set `OPENCODE_DISABLE_FFF=true` for LegalWork-managed engines: desktop/embedded server, standalone server, host orchestrator, and container orchestrator. Keep the reported execution environment consistent with the child process. ## Why FFF is an optional backend for OpenCode's filesystem-search service. Filename/folder suggestions retain its existing ripgrep + fuzzy-search fallback. The agent's built-in `glob` and `grep` tools already use ripgrep directly; explicit `read` also works without FFF. ## Issue Related upstream reports: [FFF automatically downloading OneDrive files](dmtrKovalenko/fff#363), [OpenCode scanning OneDrive at startup](anomalyco/opencode#31747). ## Scope - Disable FFF at each managed engine launch, including inherited/caller environment overrides in the server launcher. - Add a process-level regression and a bundled-engine integration test for filename/folder suggestions and actual agent `glob`, `grep`, and `read` calls. - Run the integration test in the existing Linux/macOS shipped-engine CI step. ## Out of scope Explicit agent content reads/searches, Git snapshots, and LegalWork's separate document-content search/sync can still read files. Externally managed OpenCode servers are outside this launch policy. ## Testing ### Ran Set `LEGALWORK_TEST_OPENCODE_BIN` to the bundled OpenCode 1.18.29 executable for engine tests. - `pnpm --filter legalwork-server exec bun test src/managed-opencode.test.ts src/managed-opencode.search.e2e.test.ts src/embedded.test.ts` — 7 passed, 33 assertions. - `pnpm exec bun test --preload ./apps/server/test-preload.ts --timeout 180000 apps/server/src/scheduled-tasks/engine.test.ts apps/server/src/managed-opencode.search.e2e.test.ts` — 2 passed, 109 assertions. - `pnpm --filter legalwork-server exec node node_modules/typescript/bin/tsc -p tsconfig.json --noEmit` — passed. - `pnpm --filter legalwork-orchestrator exec node node_modules/typescript/bin/tsc -p tsconfig.typecheck.json` — passed. - Additional native macOS read-trace reproduction through the actual LegalWork server and bundled engine — 4 passed, 19 assertions. - `git diff --check` — passed. ### Result The process regression failed before the fix: the child inherited `OPENCODE_DISABLE_FFF=false`. It passes after the fix and verifies the execution details report the effective value. Native read tracing with synthetic fixtures: | Action | After fix | | --- | --- | | Ordinary chat, no tools, 40 text files | 0/40 document files read (40/40 before) | | Filename/folder suggestions and filename-only glob | Successful results; no document content reads | | Explicit single-file read | Only the requested document read | | Agent content grep | Expected positive matches returned | The trace is not exhaustive for native child-process grep reads; no zero-read claim is made for content search. ## CI status Pending GitHub checks at PR creation. Local checks above passed. ## Manual verification 1. Restart a LegalWork-managed engine and check execution details for `OPENCODE_DISABLE_FFF=true`. 2. Type `@` followed by a filename or folder name; suggestions should still appear. 3. Ask the agent to find a file, search a clause, and read it. The committed bundled-engine test exercises these tools with a local model fixture, without paid model calls. ## Evidence The native read trace and engine integration checks above cover background file access. No UI video/screenshot was captured because the behavior is background I/O. Windows OneDrive placeholder hydration has not been tested; the reproduced fix is removal of FFF's automatic content reads on macOS. ## Risk Filename ranking/performance may differ with the fallback. Existing engine processes need a restart for the launch policy to take effect. ## Rollback Revert this commit to restore FFF initialization. ## Contribution rights DCO sign-off included. No third-party source code copied and no new dependencies added. Signed-off-by: Johann Machemer <[email protected]>
1 parent 103e2fe commit a2bf4c0

5 files changed

Lines changed: 118 additions & 2 deletions

File tree

‎.github/workflows/ci-tests.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,10 +118,10 @@ jobs:
118118
- name: Run server unit tests
119119
run: pnpm --filter legalwork-server test
120120

121-
- name: Verify scheduling with the shipped engine
121+
- name: Verify scheduling and file search with the shipped engine
122122
run: |
123123
pnpm --filter legalwork-server build
124-
LEGALWORK_TEST_OPENCODE_BIN="$(command -v opencode)" bun test --preload ./apps/server/test-preload.ts --timeout 180000 apps/server/src/scheduled-tasks/engine.test.ts
124+
LEGALWORK_TEST_OPENCODE_BIN="$(command -v opencode)" bun test --preload ./apps/server/test-preload.ts --timeout 180000 apps/server/src/scheduled-tasks/engine.test.ts apps/server/src/managed-opencode.search.e2e.test.ts
125125
126126
- name: Verify built draft routes load in Node
127127
run: pnpm test:drafts:build

‎apps/orchestrator/src/cli.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3827,6 +3827,8 @@ async function startOpencode(options: {
38273827
...process.env,
38283828
...(options.stateLayout?.env ?? {}),
38293829
OPENCODE_CLIENT: "legalwork-orchestrator",
3830+
// Avoid FFF reading cloud-only documents during background filename indexing.
3831+
OPENCODE_DISABLE_FFF: "true",
38303832
OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS: process.env.OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS ?? "true",
38313833
OPENCODE_MODELS_URL: options.modelCatalogUrl ?? "https://platform.eigenweltlabs.com/api/public/model-catalog",
38323834
LEGALWORK: "1",
@@ -4354,6 +4356,7 @@ async function writeSandboxEntrypoint(options: {
43544356
`if [ -d ${shQuote(hostOpencodeDataDir)} ]; then cp ${shQuote(`${hostOpencodeDataDir}/auth.json`)} \"$XDG_DATA_HOME/opencode/auth.json\" 2>/dev/null || true; cp ${shQuote(`${hostOpencodeDataDir}/mcp-auth.json`)} \"$XDG_DATA_HOME/opencode/mcp-auth.json\" 2>/dev/null || true; fi`,
43554357
`export OPENCODE_URL=${shQuote(`http://127.0.0.1:${SANDBOX_INTERNAL_OPENCODE_PORT}`)}`,
43564358
`export OPENCODE_CLIENT=legalwork-orchestrator`,
4359+
"export OPENCODE_DISABLE_FFF=true",
43574360
`export OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=${shQuote(process.env.OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS ?? "true")}`,
43584361
`export OPENCODE_MODELS_URL=${shQuote(`http://127.0.0.1:${SANDBOX_INTERNAL_LEGALWORK_PORT}/model-catalog`)}`,
43594362
`export OPENCODE_HOT_RELOAD=${shQuote(options.opencode.hotReload.enabled ? "1" : "0")}`,
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { expect, test } from "bun:test";
2+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
6+
import { z } from "zod";
7+
import { createManagedOpencodeServer } from "./managed-opencode.js";
8+
9+
const binary = process.env.LEGALWORK_TEST_OPENCODE_BIN;
10+
11+
test.skipIf(!binary)("filename mentions and agent file tools work without FFF in the shipped engine", async () => {
12+
const root = await mkdtemp(join(tmpdir(), "legalwork-search-engine-"));
13+
const directory = join(root, "matter");
14+
const contract = join(directory, "Matter-A", "contract.txt");
15+
const tools = [
16+
{ name: "glob", args: { pattern: "Matter-A/*.txt", path: directory } },
17+
{ name: "grep", args: { pattern: "fixture-clause", path: directory, include: "Matter-A/*.txt" } },
18+
{ name: "read", args: { filePath: contract } },
19+
];
20+
let nextTool = 0;
21+
let engine: Awaited<ReturnType<typeof createManagedOpencodeServer>> | undefined;
22+
const model = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) {
23+
const input = z.object({ tools: z.array(z.object({ function: z.object({ name: z.string() }) })).optional() }).parse(await request.json());
24+
const selected = input.tools?.length ? tools[nextTool] : undefined;
25+
if (selected) {
26+
expect(input.tools?.some(tool => tool.function.name === selected.name)).toBe(true);
27+
nextTool += 1;
28+
}
29+
const delta = selected ? { tool_calls: [{ index: 0, id: `fixture-${nextTool}`, type: "function", function: {
30+
name: selected.name, arguments: JSON.stringify(selected.args),
31+
} }] } : { content: "Search check complete." };
32+
const chunk = (value: unknown, finish: string | null) => `data: ${JSON.stringify({
33+
id: "fixture", object: "chat.completion.chunk", created: 1, model: "fixture",
34+
choices: [{ index: 0, delta: value, finish_reason: finish }],
35+
})}\n\n`;
36+
return new Response(chunk({ role: "assistant", ...delta }, null)
37+
+ chunk({}, selected ? "tool_calls" : "stop") + "data: [DONE]\n\n", {
38+
headers: { "content-type": "text/event-stream" },
39+
});
40+
} });
41+
try {
42+
await mkdir(join(directory, "Matter-A"), { recursive: true });
43+
await writeFile(contract, "The fixture-clause permits assignment.\n");
44+
const config = join(root, "opencode.json");
45+
await writeFile(config, JSON.stringify({
46+
plugin: [], permission: { "*": "allow" },
47+
provider: { fixture: { npm: "@ai-sdk/openai-compatible", name: "Fixture", options: {
48+
baseURL: model.url.origin + "/v1", apiKey: "fixture",
49+
}, models: { fixture: { name: "Fixture", limit: { context: 128000, output: 4096 } } } } },
50+
enabled_providers: ["fixture"], model: "fixture/fixture", small_model: "fixture/fixture",
51+
share: "disabled", autoupdate: false, lsp: false, formatter: false,
52+
}));
53+
engine = await createManagedOpencodeServer({ bin: binary, cwd: directory, env: {
54+
OPENCODE_CONFIG: config, OPENCODE_CONFIG_CONTENT: "", OPENCODE_CONFIG_DIR: join(root, "policy"),
55+
OPENCODE_TEST_HOME: join(root, "home"), OPENCODE_DB: join(root, "engine.db"),
56+
XDG_CONFIG_HOME: join(root, "config"), XDG_DATA_HOME: join(root, "data"),
57+
XDG_CACHE_HOME: join(root, "cache"), XDG_STATE_HOME: join(root, "state"),
58+
OPENCODE_DISABLE_DEFAULT_PLUGINS: "true", OPENCODE_DISABLE_CLAUDE_CODE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true",
59+
} });
60+
const client = createOpencodeClient({ baseUrl: engine.url, directory,
61+
headers: { authorization: `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}` },
62+
});
63+
// The filename index fills in the background; use the same SDK call as the composer.
64+
let matches: string[] = [];
65+
for (let attempt = 0; attempt < 100 && !matches.length; attempt += 1) {
66+
const result = await client.find.files({ query: "contract", dirs: "true", limit: 50 }, { throwOnError: true });
67+
matches = result.data ?? [];
68+
if (!matches.length) await Bun.sleep(50);
69+
}
70+
expect(matches.map(path => path.replaceAll("\\", "/"))).toContain("Matter-A/contract.txt");
71+
const folders = await client.find.files({ query: "Matter-A", type: "directory", limit: 50 }, { throwOnError: true });
72+
expect(folders.data?.map(path => path.replaceAll("\\", "/"))).toContain("Matter-A/");
73+
74+
const session = (await client.session.create({ title: "Search fallback check" }, { throwOnError: true })).data;
75+
if (!session) throw new Error("Engine did not return a session");
76+
await client.session.prompt({ sessionID: session.id, model: { providerID: "fixture", modelID: "fixture" },
77+
parts: [{ type: "text", text: "Find the contract and read its assignment clause." }],
78+
}, { throwOnError: true });
79+
const history = await client.session.messages({ sessionID: session.id }, { throwOnError: true });
80+
const calls = history.data?.flatMap(message => message.parts).filter(part => part.type === "tool") ?? [];
81+
expect(nextTool).toBe(3);
82+
expect(calls.map(call => call.tool)).toEqual(["glob", "grep", "read"]);
83+
for (const call of calls) {
84+
expect(call.state.status).toBe("completed");
85+
if (call.state.status === "completed") expect(call.state.output).toContain(call.tool === "glob" ? "contract.txt" : "fixture-clause");
86+
}
87+
} finally {
88+
await engine?.close();
89+
model.stop(true);
90+
await rm(root, { recursive: true, force: true });
91+
}
92+
}, 60_000);

‎apps/server/src/managed-opencode.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ try { n = Number(fs.readFileSync(counter, "utf8")) || 0; } catch {}
1919
n += 1;
2020
fs.writeFileSync(counter, String(n));
2121
fs.writeFileSync(counter + ".skills", process.env.OPENCODE_DISABLE_EXTERNAL_SKILLS || "");
22+
fs.writeFileSync(counter + ".fff", process.env.OPENCODE_DISABLE_FFF || "");
2223
const portIdx = process.argv.indexOf("--port");
2324
const port = portIdx >= 0 ? process.argv[portIdx + 1] : "0";
2425
if (n <= failUntil) {
@@ -83,6 +84,23 @@ test("waits for the HTTP listener even when the child announces readiness early"
8384
}
8485
}, 20000);
8586

87+
test("keeps FFF disabled in the child and execution details even if caller env enables it", async () => {
88+
const { bin, counter } = fakeBin(0);
89+
const server = await createManagedOpencodeServer({
90+
bin,
91+
cwd: dir!,
92+
env: { FAKE_OPENCODE_COUNTER: counter, OPENCODE_DISABLE_FFF: "false" },
93+
});
94+
try {
95+
expect(readFileSync(counter + ".fff", "utf8")).toBe("true");
96+
expect(server.execution.env.find(entry => entry.name === "OPENCODE_DISABLE_FFF")).toEqual({
97+
name: "OPENCODE_DISABLE_FFF", value: "true", redacted: false,
98+
});
99+
} finally {
100+
await server.close();
101+
}
102+
}, 20000);
103+
86104
test("does NOT retry a non-lock start failure (fails fast)", async () => {
87105
// fail "forever" but with a lock message would retry; use a bin that exits
88106
// with a different error so the loop must give up on the first attempt.

‎apps/server/src/managed-opencode.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,12 +199,15 @@ export async function createManagedOpencodeServer(options: {
199199
...process.env,
200200
...features,
201201
...options.env,
202+
// FFF's background scan reads document contents; filename lookup can use ripgrep.
203+
OPENCODE_DISABLE_FFF: "true",
202204
OPENCODE_SERVER_USERNAME: username,
203205
OPENCODE_SERVER_PASSWORD: password,
204206
};
205207
const injectedEnv = Object.entries({
206208
...features,
207209
...(options.env ?? {}),
210+
OPENCODE_DISABLE_FFF: "true",
208211
OPENCODE_SERVER_USERNAME: username,
209212
OPENCODE_SERVER_PASSWORD: password,
210213
})

0 commit comments

Comments
 (0)