File size: 20,772 Bytes
4c76b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// Session attachment contract tests cover plugin session attachment metadata and storage.
import * as fs from "node:fs/promises";
import path from "node:path";
import { FILE_TYPE_SNIFF_MAX_BYTES } from "@openclaw/media-core/mime";
import { registerTestPlugin } from "openclaw/plugin-sdk/plugin-test-contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { SessionEntry } from "../../config/sessions.js";
import { loadSessionEntry, replaceSessionEntry } from "../../config/sessions/session-accessor.js";
import { withTempConfig } from "../../gateway/test-temp-config.js";
import { resolvePreferredOpenClawTmpDir } from "../../infra/tmp-openclaw-dir.js";
import { createOutboundTestPlugin, createTestRegistry } from "../../test-utils/channel-plugins.js";
import { normalizeSessionDeliveryState } from "../../utils/delivery-context.shared.js";
import { sendPluginSessionAttachment } from "../host-hook-attachments.js";
import { clearPluginLoaderCache } from "../loader.test-fixtures.js";
import { createEmptyPluginRegistry } from "../registry-empty.js";
import { createPluginRegistry } from "../registry.js";
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../runtime.js";
import type { PluginRuntime } from "../runtime/types.js";
import { createPluginRecord } from "../status.test-helpers.js";
import type { OpenClawPluginApi } from "../types.js";

const workflowMocks = vi.hoisted(() => ({
  getChannelPlugin: vi.fn(),
  sendMessage: vi.fn(),
}));

const MAIN_SESSION_KEY = "agent:main:main";
const DEFAULT_TELEGRAM_ROUTE = {
  channel: "telegram",
  to: "12345",
} as const;

type SessionAttachmentRequest = Parameters<typeof sendPluginSessionAttachment>[0];
type TestSessionEntry = {
  sessionId?: string;
  updatedAt?: number;
  delivery?: SessionEntry["delivery"];
};

vi.mock("../../channels/plugins/index.js", () => ({
  getChannelPlugin: workflowMocks.getChannelPlugin,
}));

vi.mock("../../infra/outbound/message.js", () => ({
  sendMessage: workflowMocks.sendMessage,
}));

function createSilentPluginLogger() {
  return {
    info() {},
    warn() {},
    error() {},
    debug() {},
  };
}

async function withSessionStore(
  run: (params: { stateDir: string; storePath: string; filePath: string }) => Promise<void>,
) {
  const stateDir = await fs.mkdtemp(
    path.join(resolvePreferredOpenClawTmpDir(), "openclaw-session-attachments-"),
  );
  const storePath = path.join(stateDir, "sessions.json");
  const filePath = path.join(stateDir, "x.txt");
  await fs.writeFile(filePath, "x", "utf8");
  const previousStateDir = process.env.OPENCLAW_STATE_DIR;
  process.env.OPENCLAW_STATE_DIR = stateDir;
  try {
    await withTempConfig({
      cfg: { session: { store: storePath } },
      run: async () => await run({ stateDir, storePath, filePath }),
    });
  } finally {
    if (previousStateDir === undefined) {
      delete process.env.OPENCLAW_STATE_DIR;
    } else {
      process.env.OPENCLAW_STATE_DIR = previousStateDir;
    }
    await fs.rm(stateDir, { recursive: true, force: true });
  }
}

async function writeSessionEntry(
  storePath: string,
  entry: TestSessionEntry = {
    delivery: normalizeSessionDeliveryState({ context: DEFAULT_TELEGRAM_ROUTE }),
  },
  key = MAIN_SESSION_KEY,
) {
  await replaceSessionEntry({ storePath, sessionKey: key }, {
    sessionId: "session-id",
    updatedAt: Date.now(),
    ...entry,
  } as unknown as SessionEntry);
}

function mockSuccessfulAttachmentDelivery(messageId = "attachment-1") {
  workflowMocks.sendMessage.mockImplementation(async (params: Record<string, unknown>) => ({
    channel: params.channel,
    to: params.to,
    via: "direct" as const,
    mediaUrl: null,
    result: { channel: params.channel, messageId },
  }));
}

async function sendBundledSessionAttachment(
  params: Omit<SessionAttachmentRequest, "origin" | "sessionKey"> &
    Partial<Pick<SessionAttachmentRequest, "sessionKey">>,
) {
  return await sendPluginSessionAttachment({
    origin: "bundled",
    sessionKey: MAIN_SESSION_KEY,
    ...params,
  });
}

function expectTelegramAttachmentResult(result: unknown, count: number) {
  const response = result as { ok?: unknown; channel?: unknown; count?: unknown };
  expect(response.ok).toBe(true);
  expect(response.channel).toBe("telegram");
  expect(response.count).toBe(count);
}

function requireFirstSendMessageParams() {
  const params = workflowMocks.sendMessage.mock.calls[0]?.[0] as
    | Record<string, unknown>
    | undefined;
  if (!params) {
    throw new Error("expected sendMessage call");
  }
  return params;
}

describe("plugin session attachments", () => {
  afterEach(() => {
    workflowMocks.getChannelPlugin.mockReset();
    workflowMocks.sendMessage.mockReset();
    resetPluginRuntimeStateForTest();
    clearPluginLoaderCache();
    delete (globalThis as { proofAttachmentApi?: OpenClawPluginApi }).proofAttachmentApi;
    delete (globalThis as { proofAttachmentLog?: unknown[] }).proofAttachmentLog;
  });

  it("sends validated files through the session delivery route with portable hints", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath, {
        delivery: normalizeSessionDeliveryState({
          context: { ...DEFAULT_TELEGRAM_ROUTE, accountId: "default", threadId: 42 },
        }),
      });
      mockSuccessfulAttachmentDelivery();

      const result = await sendBundledSessionAttachment({
        files: [{ path: filePath }],
        channelHints: { silent: true, parseMode: "HTML", threadId: "attachment-thread" },
      });

      expect(result).toEqual({
        ok: true,
        channel: "telegram",
        deliveredTo: "12345",
        count: 1,
      });
      expect(workflowMocks.sendMessage).toHaveBeenCalledTimes(1);
      const sendParams = requireFirstSendMessageParams();
      expect(sendParams.to).toBe("12345");
      expect(sendParams.channel).toBe("telegram");
      expect(sendParams.accountId).toBe("default");
      expect(sendParams.threadId).toBe("attachment-thread");
      expect(sendParams.mediaUrls).toEqual([filePath]);
      expect(sendParams.bestEffort).toBe(false);
      expect(sendParams.silent).toBe(true);
      expect(sendParams.parseMode).toBe("HTML");
    });
  });

  it("does not use best-effort mode for attachment batches", async () => {
    await withSessionStore(async ({ storePath, stateDir }) => {
      const first = path.join(stateDir, "first.txt");
      const second = path.join(stateDir, "second.txt");
      await fs.writeFile(first, "1", "utf8");
      await fs.writeFile(second, "2", "utf8");
      await writeSessionEntry(storePath);
      mockSuccessfulAttachmentDelivery();

      const result = await sendBundledSessionAttachment({
        files: [{ path: first }, { path: second }],
      });
      expectTelegramAttachmentResult(result, 2);
      const sendParams = requireFirstSendMessageParams();
      expect(sendParams.mediaUrls).toEqual([first, second]);
      expect(sendParams.bestEffort).toBe(false);
    });
  });

  it("keeps shipped Telegram hints compatible when escaping plain captions", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath);
      mockSuccessfulAttachmentDelivery();

      const result = await sendBundledSessionAttachment({
        files: [{ path: filePath }],
        text: "1 < 2 & 3 > 2",
        captionFormat: "plain",
        channelHints: { telegram: { parseMode: "HTML" } },
      });
      expectTelegramAttachmentResult(result, 1);
      const sendParams = requireFirstSendMessageParams();
      expect(sendParams.content).toBe("1 &lt; 2 &amp; 3 &gt; 2");
      expect(sendParams.parseMode).toBe("HTML");
    });
  });

  it("keeps shipped Slack thread hints compatible", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath, {
        delivery: normalizeSessionDeliveryState({ context: { channel: "slack", to: "C123" } }),
      });
      mockSuccessfulAttachmentDelivery();

      const result = await sendBundledSessionAttachment({
        files: [{ path: filePath }],
        channelHints: { slack: { threadTs: "171234.567" } },
      });

      expect(result).toMatchObject({ ok: true, channel: "slack", deliveredTo: "C123" });
      expect(requireFirstSendMessageParams().threadId).toBe("171234.567");
    });
  });

  it("resolves relative attachment paths against the session agent workspace", async () => {
    await withSessionStore(async ({ storePath, stateDir }) => {
      const workspaceDir = path.join(stateDir, "workspace");
      const relativeFilePath = "./report.txt";
      const absoluteFilePath = path.join(workspaceDir, "report.txt");
      await fs.mkdir(workspaceDir, { recursive: true });
      await fs.writeFile(absoluteFilePath, "workspace report", "utf8");
      await writeSessionEntry(storePath);
      mockSuccessfulAttachmentDelivery();

      const result = await sendBundledSessionAttachment({
        files: [{ path: relativeFilePath }],
        config: {
          session: { store: storePath },
          agents: {
            list: [{ id: "main", default: true, workspace: workspaceDir }],
          },
        },
      });
      expectTelegramAttachmentResult(result, 1);
      expect(requireFirstSendMessageParams().mediaUrls).toEqual([absoluteFilePath]);
    });
  });

  it("reports attachment delivery as failed when no delivery result is returned", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath);
      workflowMocks.sendMessage.mockResolvedValue({
        channel: "telegram",
        to: "12345",
        via: "direct",
        mediaUrl: null,
      });

      await expect(
        sendBundledSessionAttachment({
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error: "attachment delivery failed: no delivery result returned",
      });
    });
  });

  it("rejects external plugins and sessions without delivery routes", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath, {});

      await expect(
        sendPluginSessionAttachment({
          origin: "workspace",
          sessionKey: MAIN_SESSION_KEY,
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error: "session attachments are restricted to bundled plugins",
      });
      await expect(
        sendBundledSessionAttachment({
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error: "session has no active delivery route: agent:main:main",
      });
      expect(workflowMocks.sendMessage).not.toHaveBeenCalled();
    });
  });

  it("rejects malformed or oversized attachment inputs before delivery", async () => {
    await withSessionStore(async ({ storePath, stateDir, filePath }) => {
      await writeSessionEntry(storePath);

      await expect(
        sendBundledSessionAttachment({
          files: Array.from({ length: 11 }, () => ({ path: path.join(stateDir, "missing.txt") })),
        }),
      ).resolves.toEqual({
        ok: false,
        error: "at most 10 attachment files are allowed",
      });

      await expect(
        sendBundledSessionAttachment({
          files: [null as never],
        }),
      ).resolves.toEqual({
        ok: false,
        error: "attachment file entry must be an object",
      });

      const first = path.join(stateDir, "first.txt");
      const second = path.join(stateDir, "second.txt");
      await fs.writeFile(first, "123", "utf8");
      await fs.writeFile(second, "456", "utf8");
      await expect(
        sendBundledSessionAttachment({
          files: [{ path: first }, { path: second }],
          maxBytes: 5,
        }),
      ).resolves.toEqual({
        ok: false,
        error: "attachment files exceed 5 bytes total",
      });
      const symlinkPath = path.join(stateDir, "linked.txt");
      await fs.symlink(first, symlinkPath);
      await expect(
        sendBundledSessionAttachment({
          files: [{ path: symlinkPath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error: `attachment file symlinks are not allowed: ${symlinkPath}`,
      });
      await expect(
        sendBundledSessionAttachment({
          files: [{ path: filePath }],
          channelHints: { forceDocumentMime: "application/pdf" },
        }),
      ).resolves.toEqual({
        ok: false,
        error: `attachment file MIME mismatch for ${filePath}: expected application/pdf, got unknown`,
      });
      const fakePdfPath = path.join(stateDir, "fake.pdf");
      await fs.writeFile(fakePdfPath, "not a pdf", "utf8");
      await expect(
        sendBundledSessionAttachment({
          files: [{ path: fakePdfPath }],
          channelHints: { forceDocumentMime: "application/pdf" },
        }),
      ).resolves.toEqual({
        ok: false,
        error: `attachment file MIME mismatch for ${fakePdfPath}: expected application/pdf, got unknown`,
      });
      expect(workflowMocks.sendMessage).not.toHaveBeenCalled();
    });
  });

  it("validates force-document MIME using only the configured sniff window", async () => {
    await withSessionStore(async ({ storePath, stateDir }) => {
      const pdfPath = path.join(stateDir, "large.pdf");
      await fs.writeFile(
        pdfPath,
        Buffer.concat([Buffer.from("%PDF-1.7\n"), Buffer.alloc(FILE_TYPE_SNIFF_MAX_BYTES + 32)]),
      );
      await writeSessionEntry(storePath);
      mockSuccessfulAttachmentDelivery();

      const result = await sendBundledSessionAttachment({
        files: [{ path: pdfPath }],
        forceDocument: false,
        channelHints: { forceDocumentMime: "application/pdf" },
      });
      expectTelegramAttachmentResult(result, 1);
      const sendParams = requireFirstSendMessageParams();
      expect(sendParams.mediaUrls).toEqual([pdfPath]);
      expect(sendParams.forceDocument).toBe(true);
    });
  });

  it("rejects gateway-mode channels before attempting host-local attachment delivery", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath);
      workflowMocks.getChannelPlugin.mockReturnValue(
        createOutboundTestPlugin({
          id: "telegram",
          outbound: { deliveryMode: "gateway" },
        }),
      );
      setActivePluginRegistry(
        createTestRegistry([
          {
            pluginId: "telegram",
            source: "test",
            plugin: createOutboundTestPlugin({
              id: "telegram",
              outbound: { deliveryMode: "gateway" },
            }),
          },
        ]),
      );

      await expect(
        sendBundledSessionAttachment({
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error:
          "session attachments require direct outbound delivery for channel telegram; " +
          "channel uses gateway delivery",
      });
      expect(workflowMocks.sendMessage).not.toHaveBeenCalled();
    });
  });

  it("rejects unloaded bundled gateway-mode channels before attachment delivery", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath, {
        delivery: normalizeSessionDeliveryState({
          context: { channel: "whatsapp", to: "+15551234567" },
        }),
      });
      setActivePluginRegistry(createEmptyPluginRegistry());
      workflowMocks.getChannelPlugin.mockReturnValue(
        createOutboundTestPlugin({
          id: "whatsapp",
          outbound: { deliveryMode: "gateway" },
        }),
      );

      await expect(
        sendBundledSessionAttachment({
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error:
          "session attachments require direct outbound delivery for channel whatsapp; " +
          "channel uses gateway delivery",
      });
      expect(workflowMocks.sendMessage).not.toHaveBeenCalled();
    });
  });

  it("returns structured errors when channel delivery lookup fails", async () => {
    await withSessionStore(async ({ storePath, filePath }) => {
      await writeSessionEntry(storePath);
      workflowMocks.getChannelPlugin.mockImplementation(() => {
        throw new Error("channel registry unavailable");
      });

      await expect(
        sendBundledSessionAttachment({
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error: "attachment delivery setup failed: channel registry unavailable",
      });
      expect(workflowMocks.sendMessage).not.toHaveBeenCalled();
    });
  });

  it("uses replacement runtime config when captured async session hooks resume", async () => {
    await withSessionStore(async ({ stateDir, storePath, filePath }) => {
      await writeSessionEntry(storePath);
      mockSuccessfulAttachmentDelivery();

      const staleStorePath = path.join(stateDir, "stale-sessions.json");
      await writeSessionEntry(staleStorePath);
      const registrationConfig = { session: { store: staleStorePath } };
      const liveConfig = { session: { store: storePath } };
      let runtimeConfig = registrationConfig;
      const registry = createPluginRegistry({
        logger: createSilentPluginLogger(),
        runtime: {
          config: {
            current: () => runtimeConfig,
          },
        } as unknown as PluginRuntime,
      });
      let capturedApi: OpenClawPluginApi | undefined;
      registerTestPlugin({
        registry,
        config: registrationConfig,
        record: createPluginRecord({
          id: "live-config-attachment-plugin",
          name: "Live Config Attachment Plugin",
          origin: "bundled",
        }),
        register(api) {
          capturedApi = api;
        },
      });
      setActivePluginRegistry(registry.registry);

      const attachment = capturedApi?.sendSessionAttachment({
        sessionKey: MAIN_SESSION_KEY,
        files: [{ path: filePath }],
      });
      const injection = capturedApi?.enqueueNextTurnInjection({
        sessionKey: MAIN_SESSION_KEY,
        text: "resume with current config",
        idempotencyKey: "live-config-injection",
      });
      runtimeConfig = liveConfig;

      const result = await attachment;
      expectTelegramAttachmentResult(result, 1);
      expect(workflowMocks.sendMessage).toHaveBeenCalledTimes(1);
      expect(requireFirstSendMessageParams().cfg).toBe(liveConfig);
      await expect(injection).resolves.toEqual({
        enqueued: true,
        id: "live-config-injection",
        sessionKey: MAIN_SESSION_KEY,
      });
      expect(
        loadSessionEntry({ storePath, sessionKey: MAIN_SESSION_KEY })?.pluginNextTurnInjections?.[
          "live-config-attachment-plugin"
        ],
      ).toEqual([
        expect.objectContaining({
          id: "live-config-injection",
          text: "resume with current config",
        }),
      ]);
      expect(
        loadSessionEntry({ storePath: staleStorePath, sessionKey: MAIN_SESSION_KEY })
          ?.pluginNextTurnInjections,
      ).toBeUndefined();
    });
  });

  it("returns structured errors when the captured API cannot read the live runtime config", async () => {
    await withSessionStore(async ({ stateDir, storePath, filePath }) => {
      await writeSessionEntry(storePath);

      const registrationConfig = { session: { store: path.join(stateDir, "stale-sessions.json") } };
      const registry = createPluginRegistry({
        logger: createSilentPluginLogger(),
        runtime: {
          config: {
            current: () => {
              throw new Error("config runtime unavailable");
            },
          },
        } as unknown as PluginRuntime,
      });
      let capturedApi: OpenClawPluginApi | undefined;
      registerTestPlugin({
        registry,
        config: registrationConfig,
        record: createPluginRecord({
          id: "attachment-runtime-error-plugin",
          name: "Attachment Runtime Error Plugin",
          origin: "bundled",
        }),
        register(api) {
          capturedApi = api;
        },
      });
      setActivePluginRegistry(registry.registry);

      await expect(
        capturedApi?.sendSessionAttachment({
          sessionKey: MAIN_SESSION_KEY,
          files: [{ path: filePath }],
        }),
      ).resolves.toEqual({
        ok: false,
        error: "attachment delivery setup failed: config runtime unavailable",
      });
      expect(workflowMocks.sendMessage).not.toHaveBeenCalled();
    });
  });
});