Skip to content

Commit 940f716

Browse files
committed
test: isolate shared /tmp state in reply, channel, and boot suites
Fixtures handed real session-store, agent, transcript, and workspace paths under shared /tmp, so a stale machine-wide openclaw-agent.sqlite made unrelated suites fail through the real SQLite accessor. Route them through the existing test/helpers/temp-dir tracker instead, and wait on the actual CLI progress callbacks rather than a one-second polling deadline. Production LOC unchanged.
1 parent 80e4dd3 commit 940f716

14 files changed

Lines changed: 160 additions & 108 deletions

‎src/auto-reply/reply.block-streaming.test.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
/** Tests block streaming behavior for auto-reply output delivery. */
2-
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
2+
import path from "node:path";
3+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
4+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
35
import type { OpenClawConfig } from "../config/config.js";
46
import { withFastReplyConfig } from "./reply/get-reply-fast-path.test-support.js";
57
import { loadGetReplyModuleForTest } from "./reply/get-reply.test-loader.js";
68
import { createMockTypingController } from "./reply/reply.test-helpers.js";
79
import type { MsgContext } from "./templating.js";
810

11+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
12+
913
const mocks = vi.hoisted(() => ({
14+
rootDir: "",
1015
resolveReplyDirectives: vi.fn(),
1116
handleInlineActions: vi.fn(),
1217
initSessionState: vi.fn(),
@@ -19,8 +24,8 @@ vi.mock("../agents/agent-scope.js", async () => {
1924
);
2025
return {
2126
...actual,
22-
resolveAgentDir: vi.fn(() => "/tmp/agent"),
23-
resolveAgentWorkspaceDir: vi.fn(() => "/tmp/workspace"),
27+
resolveAgentDir: vi.fn(() => path.join(mocks.rootDir, "agent")),
28+
resolveAgentWorkspaceDir: vi.fn(() => path.join(mocks.rootDir, "workspace")),
2429
resolveSessionAgentId: vi.fn(() => "main"),
2530
resolveAgentSkillsFilter: vi.fn(() => undefined),
2631
};
@@ -39,7 +44,7 @@ vi.mock("../agents/timeout.js", () => ({
3944
}));
4045
vi.mock("../agents/workspace.js", () => ({
4146
DEFAULT_AGENT_WORKSPACE_DIR: "/tmp/workspace",
42-
ensureAgentWorkspace: vi.fn(async () => ({ dir: "/tmp/workspace" })),
47+
ensureAgentWorkspace: vi.fn(async () => ({ dir: path.join(mocks.rootDir, "workspace") })),
4348
}));
4449
vi.mock("../channels/model-overrides.js", () => ({
4550
resolveChannelModelOverride: vi.fn(() => undefined),
@@ -109,7 +114,7 @@ function createReplyConfig(streamMode?: "block"): OpenClawConfig {
109114
agents: {
110115
defaults: {
111116
model: { primary: "anthropic/claude-opus-4-6" },
112-
workspace: "/tmp/workspace",
117+
workspace: path.join(mocks.rootDir, "workspace"),
113118
},
114119
},
115120
channels: {
@@ -118,7 +123,7 @@ function createReplyConfig(streamMode?: "block"): OpenClawConfig {
118123
...(streamMode ? { streaming: { mode: streamMode } } : {}),
119124
},
120125
},
121-
session: { store: "/tmp/sessions.json" },
126+
session: { store: path.join(mocks.rootDir, "sessions.json") },
122127
} as OpenClawConfig);
123128
}
124129

@@ -178,6 +183,7 @@ describe("block streaming", () => {
178183
});
179184

180185
beforeEach(() => {
186+
mocks.rootDir = tempDirs.make("openclaw-block-streaming-");
181187
vi.stubEnv("OPENCLAW_TEST_FAST", "1");
182188
mocks.resolveReplyDirectives.mockReset();
183189
mocks.handleInlineActions.mockReset();
@@ -204,7 +210,7 @@ describe("block streaming", () => {
204210
resetTriggered: false,
205211
systemSent: false,
206212
abortedLastRun: false,
207-
storePath: "/tmp/sessions.json",
213+
storePath: path.join(mocks.rootDir, "sessions.json"),
208214
sessionScope: "per-sender",
209215
groupResolution: undefined,
210216
isGroup: false,

‎src/auto-reply/reply/agent-runner-direct-runtime-config.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ describe("runReplyAgent runtime config", () => {
318318
expect(createReplyMediaContextMock).toHaveBeenCalledWith({
319319
cfg: freshCfg,
320320
sessionKey: undefined,
321-
workspaceDir: "/tmp",
321+
workspaceDir: followupRun.run.workspaceDir,
322322
messageProvider: "telegram",
323323
accountId: undefined,
324324
groupId: undefined,

‎src/auto-reply/reply/agent-runner-execution-cli-progress.test.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { describe, expect, it, vi } from "vitest";
1+
import { describe, expect, it, onTestFinished, vi } from "vitest";
2+
import { createDeferred } from "../../../test/helpers/promise.js";
23
import { createCliJsonlStreamingParser } from "../../agents/cli-output-stream.js";
34
import type { TemplateContext } from "../templating.js";
45
import type { GetReplyOptions } from "../types.js";
@@ -282,6 +283,7 @@ describe("executeAgentTurn: CLI progress bridging", () => {
282283
const typingSignals = createMockTypingSignaler();
283284
vi.mocked(typingSignals.signalTextDelta).mockReturnValue(typingPending);
284285
const callbackOrder: string[] = [];
286+
const toolStarted = createDeferred();
285287
const executeAgentTurn = await getExecuteAgentTurnForTest();
286288
const followupRun = createFollowupRun();
287289
followupRun.run.provider = "claude-cli";
@@ -297,6 +299,7 @@ describe("executeAgentTurn: CLI progress bridging", () => {
297299
},
298300
onToolStart: () => {
299301
callbackOrder.push("tool");
302+
toolStarted.resolve();
300303
},
301304
},
302305
typingSignals,
@@ -313,11 +316,13 @@ describe("executeAgentTurn: CLI progress bridging", () => {
313316
getActiveSessionEntry: () => undefined,
314317
resolvedVerboseLevel: "off",
315318
});
319+
onTestFinished(async () => {
320+
releaseTyping?.();
321+
await runPromise;
322+
});
316323

317324
try {
318-
await vi.waitFor(() => {
319-
expect(callbackOrder).toContain("tool");
320-
});
325+
await Promise.race([toolStarted.promise, runPromise]);
321326
expect(callbackOrder).toEqual([
322327
"partial:answer before tool",
323328
"partial:answer before tool 2",
@@ -374,6 +379,7 @@ describe("executeAgentTurn: CLI progress bridging", () => {
374379
const typingSignals = createMockTypingSignaler();
375380
vi.mocked(typingSignals.signalToolStart).mockReturnValue(typingPending);
376381
const callbackOrder: string[] = [];
382+
const partialReplyStarted = createDeferred();
377383
const executeAgentTurn = await getExecuteAgentTurnForTest();
378384
const followupRun = createFollowupRun();
379385
followupRun.run.provider = "claude-cli";
@@ -386,6 +392,7 @@ describe("executeAgentTurn: CLI progress bridging", () => {
386392
preserveProgressCallbackStartOrder: true,
387393
onPartialReply: (payload) => {
388394
callbackOrder.push(`partial:${payload.text}`);
395+
partialReplyStarted.resolve();
389396
},
390397
onToolStart: (payload) => {
391398
callbackOrder.push(`tool:${payload.phase}`);
@@ -405,11 +412,13 @@ describe("executeAgentTurn: CLI progress bridging", () => {
405412
getActiveSessionEntry: () => undefined,
406413
resolvedVerboseLevel: "off",
407414
});
415+
onTestFinished(async () => {
416+
releaseTyping?.();
417+
await runPromise;
418+
});
408419

409420
try {
410-
await vi.waitFor(() => {
411-
expect(callbackOrder).toContain("partial:answer after tool");
412-
});
421+
await Promise.race([partialReplyStarted.promise, runPromise]);
413422
expect(callbackOrder).toEqual(["tool:start", "tool:update", "partial:answer after tool"]);
414423
} finally {
415424
releaseTyping?.();

‎src/auto-reply/reply/agent-runner-execution.test-support.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Shared mocks and fixtures for agent-runner execution tests.
2-
import { afterEach, beforeEach, expect, vi } from "vitest";
2+
import path from "node:path";
3+
import { afterEach, beforeEach, expect, onTestFinished, vi } from "vitest";
4+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
35
import { testing as cliBackendsTesting } from "../../agents/cli-backends.test-support.js";
46
import type { runEmbeddedAgentEntry } from "../../agents/embedded-agent-runner/run-entry.js";
57
import type { DeferredEmbeddedRunLifecycleOwner } from "../../agents/embedded-agent-runner/run/deferred-lifecycle-owner.js";
@@ -473,18 +475,19 @@ export function createMockTypingSignaler(): TypingSignaler {
473475
}
474476

475477
export function createFollowupRun(): FollowupRun {
478+
const rootDir = useAutoCleanupTempDirTracker(onTestFinished).make("openclaw-agent-execution-");
476479
return {
477480
prompt: "hello",
478481
summaryLine: "hello",
479482
enqueuedAt: Date.now(),
480483
run: {
481484
agentId: "main",
482-
agentDir: "/tmp/agent",
485+
agentDir: path.join(rootDir, "agent"),
483486
sessionId: "session",
484487
sessionKey: "main",
485488
messageProvider: "whatsapp",
486-
sessionFile: "/tmp/session.jsonl",
487-
workspaceDir: "/tmp",
489+
sessionFile: path.join(rootDir, "session.jsonl"),
490+
workspaceDir: rootDir,
488491
config: {},
489492
skillsSnapshot: {},
490493
provider: "anthropic",

‎src/auto-reply/reply/agent-runner.media-paths.test.ts‎

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
// Tests media path handling and sandbox staging inside agent runner inputs.
2-
import { mkdtemp, rm, writeFile } from "node:fs/promises";
3-
import os from "node:os";
2+
import { writeFile } from "node:fs/promises";
43
import path from "node:path";
54
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
66
import type { EmbeddedAgentQueueMessageOutcome } from "../../agents/embedded-agent-runner/runs.js";
77
import {
88
runInitialModelFallbackAttempt,
@@ -22,6 +22,9 @@ import {
2222
createMockTypingController,
2323
} from "./test-helpers.js";
2424

25+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
26+
let testWorkspaceDir: string;
27+
2528
const runEmbeddedAgentMock = vi.fn();
2629
const runWithModelFallbackMock = vi.fn();
2730
const abortEmbeddedAgentRunMock = vi.fn();
@@ -304,16 +307,15 @@ function makeRunReplyAgentParams(
304307
): Parameters<typeof runReplyAgent>[0] {
305308
const provider = overrides.provider ?? "whatsapp";
306309
const prompt = overrides.prompt ?? "generate chart";
307-
const workspaceDir = overrides.workspaceDir ?? "/tmp/workspace";
310+
const runWorkspaceDir = overrides.workspaceDir ?? testWorkspaceDir;
308311
const followupRun =
309312
overrides.followupRun ??
310313
createMockFollowupRun({
311314
prompt,
312315
run: {
313316
agentId: "main",
314-
agentDir: "/tmp/agent",
315317
messageProvider: provider,
316-
workspaceDir,
318+
workspaceDir: runWorkspaceDir,
317319
},
318320
});
319321
const replyOperation =
@@ -394,9 +396,8 @@ function makeRunReplyAgentParams(
394396
}
395397

396398
describe("runReplyAgent media path normalization", () => {
397-
const cleanupPaths: string[] = [];
398-
399399
beforeEach(() => {
400+
testWorkspaceDir = tempDirs.make("openclaw-agent-media-workspace-");
400401
runEmbeddedAgentMock.mockReset();
401402
runWithModelFallbackMock.mockReset();
402403
abortEmbeddedAgentRunMock.mockReset();
@@ -455,8 +456,6 @@ describe("runReplyAgent media path normalization", () => {
455456
operation.complete();
456457
}
457458
vi.useRealTimers();
458-
const paths = cleanupPaths.splice(0);
459-
return Promise.all(paths.map((entry) => rm(entry, { recursive: true, force: true })));
460459
});
461460

462461
it("normalizes final MEDIA replies against the run workspace", async () => {
@@ -483,9 +482,9 @@ describe("runReplyAgent media path normalization", () => {
483482
mediaUrls: ["/tmp/outbound-media/generated.png"],
484483
});
485484
expect(resolveOutboundAttachmentFromUrlMock).toHaveBeenCalledWith(
486-
path.join("/tmp/workspace", "out", "generated.png"),
485+
path.join(testWorkspaceDir, "out", "generated.png"),
487486
5 * 1024 * 1024,
488-
{ mediaAccess: expect.objectContaining({ workspaceDir: "/tmp/workspace" }) },
487+
{ mediaAccess: expect.objectContaining({ workspaceDir: testWorkspaceDir }) },
489488
);
490489
expect(runEmbeddedAgentMock).toHaveBeenCalledOnce();
491490
expect(createReplyMediaContextRuntimeMock).not.toHaveBeenCalled();
@@ -716,7 +715,7 @@ describe("runReplyAgent media path normalization", () => {
716715
const mediaContext = createReplyMediaContext({
717716
cfg: {},
718717
sessionKey: "main",
719-
workspaceDir: "/tmp/workspace",
718+
workspaceDir: testWorkspaceDir,
720719
messageProvider: "telegram",
721720
accountId: "default",
722721
});
@@ -762,7 +761,7 @@ describe("runReplyAgent media path normalization", () => {
762761
run: {
763762
provider: "ollama",
764763
model: "gemma4:latest",
765-
workspaceDir: "/tmp/workspace",
764+
workspaceDir: testWorkspaceDir,
766765
config: {},
767766
},
768767
}),
@@ -818,7 +817,7 @@ describe("runReplyAgent media path normalization", () => {
818817
run: {
819818
provider: "anthropic",
820819
model: "claude",
821-
workspaceDir: "/tmp/workspace",
820+
workspaceDir: testWorkspaceDir,
822821
config: {},
823822
},
824823
});
@@ -868,8 +867,7 @@ describe("runReplyAgent media path normalization", () => {
868867
});
869868

870869
it("passes current inbound media paths as native OpenClaw images", async () => {
871-
const tmpDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-native-agent-media-"));
872-
cleanupPaths.push(tmpDir);
870+
const tmpDir = tempDirs.make("openclaw-native-agent-media-");
873871
const imagePath = path.join(tmpDir, "photo.png");
874872
await writeFile(
875873
imagePath,
@@ -918,8 +916,7 @@ describe("runReplyAgent media path normalization", () => {
918916
});
919917

920918
it("does not pass recent history images as unlabeled native OpenClaw images", async () => {
921-
const tmpDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-native-agent-history-"));
922-
cleanupPaths.push(tmpDir);
919+
const tmpDir = tempDirs.make("openclaw-native-agent-history-");
923920
const imagePath = path.join(tmpDir, "recent.png");
924921
await writeFile(
925922
imagePath,
@@ -972,8 +969,7 @@ describe("runReplyAgent media path normalization", () => {
972969
});
973970

974971
it("retains resolved current images and skips unresolved attachments", async () => {
975-
const tmpDir = await mkdtemp(path.join(os.tmpdir(), "openclaw-native-agent-partial-"));
976-
cleanupPaths.push(tmpDir);
972+
const tmpDir = tempDirs.make("openclaw-native-agent-partial-");
977973
const imagePath = path.join(tmpDir, "present.png");
978974
await writeFile(
979975
imagePath,

0 commit comments

Comments
 (0)