File size: 5,289 Bytes
78d0c37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/**
 * Tests agent creation event emission from gateway agent methods.
 */
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { trackAsyncWork } from "../../shared/async-work-scope.js";
import {
  forgetActiveSessionForShutdown,
  listActiveSessionsForShutdown,
} from "../active-sessions-shutdown-tracker.js";

const configMocks = vi.hoisted(() => ({
  storePath: "",
  workspaceDir: "",
  getRuntimeConfig: vi.fn(() => ({
    agents: {
      defaults: {
        model: { primary: "anthropic/claude-opus-4-6" },
        workspace: configMocks.workspaceDir || "/tmp/openclaw-agent-create-event",
      },
    },
    session: {
      mainKey: "main",
      store: configMocks.storePath,
    },
  })),
}));

const agentIngressMocks = vi.hoisted(() => ({
  agentCommandFromIngress: vi.fn(async () => ({ ok: true })),
}));

vi.mock("../../config/config.js", () => ({
  getRuntimeConfig: configMocks.getRuntimeConfig,
}));

vi.mock("../../commands/agent.js", () => ({
  agentCommandFromGatewayIngress: agentIngressMocks.agentCommandFromIngress,
  agentCommandFromIngress: agentIngressMocks.agentCommandFromIngress,
}));

vi.mock("../../agents/prepared-model-runtime.js", () => ({
  acquireAgentRunPreparedModelRuntime: vi.fn(async () => ({
    [Symbol.asyncDispose]: vi.fn(async () => {}),
    snapshot: {},
  })),
  loadPublishedGatewayReplyDispatchRuntime: vi.fn(async ({ agentId }: { agentId: string }) => ({
    agentId,
    agentDir: configMocks.workspaceDir,
    config: configMocks.getRuntimeConfig(),
    pluginGeneration: { pluginMetadataSnapshot: {} },
    workspaceDir: configMocks.workspaceDir,
  })),
}));

vi.mock("../../runtime.js", () => ({
  defaultRuntime: {},
}));

vi.mock("../../tasks/detached-task-runtime.js", () => ({
  createRunningTaskRun: vi.fn(),
}));

import { agentHandlers } from "./agent.js";

function firstMockCall<T extends readonly unknown[]>(mock: { mock: { calls: readonly T[] } }) {
  return mock.mock.calls[0];
}

describe("agent handler session create events", () => {
  let tempDir: string;
  let storePath: string;

  beforeEach(async () => {
    tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-agent-create-event-"));
    storePath = path.join(tempDir, "sessions.json");
    configMocks.storePath = storePath;
    configMocks.workspaceDir = tempDir;
    configMocks.getRuntimeConfig.mockClear();
    agentIngressMocks.agentCommandFromIngress.mockClear();
    agentIngressMocks.agentCommandFromIngress.mockResolvedValue({ ok: true });
    await fs.writeFile(storePath, "{}\n", "utf8");
  });

  afterEach(async () => {
    for (const entry of listActiveSessionsForShutdown()) {
      forgetActiveSessionForShutdown(entry.sessionId);
    }
    await fs.rm(tempDir, { recursive: true, force: true });
    vi.restoreAllMocks();
  });

  it("emits sessions.changed with reason create for new agent sessions", async () => {
    const broadcastToConnIds = vi.fn();
    const respond = vi.fn();

    await expectDefined(agentHandlers.agent, "agentHandlers.agent test invariant").call(
      agentHandlers,
      {
        params: {
          message: "hi",
          sessionKey: "agent:main:subagent:create-test",
          idempotencyKey: "idem-agent-create-event",
        },
        respond,
        context: {
          trackExecution: trackAsyncWork,
          dedupe: new Map(),
          deps: {} as never,
          logGateway: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), debug: vi.fn() } as never,
          chatAbortControllers: new Map(),
          addChatRun: vi.fn(),
          registerToolEventRecipient: vi.fn(),
          getRuntimeConfig: configMocks.getRuntimeConfig,
          getSessionEventSubscriberConnIds: () => new Set(["conn-1"]),
          broadcastToConnIds,
        } as never,
        client: null,
        isWebchatConnect: () => false,
        req: { id: "req-agent-create-event" } as never,
      },
    );

    const responseCall = firstMockCall(respond) as
      | [boolean, { status?: string; runId?: string }, unknown, { runId?: string }]
      | undefined;
    expect(responseCall?.[0]).toBe(true);
    expect(responseCall?.[1]?.status).toBe("accepted");
    expect(responseCall?.[1]?.runId).toBe("idem-agent-create-event");
    expect(responseCall?.[2]).toBeUndefined();
    expect(responseCall?.[3]?.runId).toBe("idem-agent-create-event");
    await vi.waitFor(
      () => {
        const call = firstMockCall(broadcastToConnIds) as
          | [
              string,
              { sessionKey?: string; reason?: string },
              Set<string>,
              { dropIfSlow?: boolean; sessionKeys?: string[] },
            ]
          | undefined;
        expect(call?.[0]).toBe("sessions.changed");
        expect(call?.[1]?.sessionKey).toBe("agent:main:subagent:create-test");
        expect(call?.[1]?.reason).toBe("create");
        expect(call?.[2]).toEqual(new Set(["conn-1"]));
        expect(call?.[3]).toEqual({
          agentId: "main",
          dropIfSlow: true,
          sessionKeys: ["agent:main:subagent:create-test"],
        });
      },
      { timeout: 2_000, interval: 5 },
    );
  });
});