repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/tests/notify.test.ts

Raw
import { beforeEach, describe, expect, mock, test } from "bun:test";
import path from "node:path";

// Track notifier calls
let notifierCalls: Array<Record<string, unknown>> = [];
let notifierShouldFail = false;

// Mock node-notifier at top level before any imports
mock.module("node-notifier", () => ({
  default: {
    notify: mock(
      (
        options: Record<string, unknown>,
        callback: (err: Error | null) => void,
      ) => {
        notifierCalls.push(options);
        callback(notifierShouldFail ? new Error("Notification failed") : null);
      },
    ),
  },
}));

// Mock node:os at top level
mock.module("node:os", () => ({
  homedir: () => "/home/testuser",
}));

beforeEach(() => {
  notifierCalls = [];
  notifierShouldFail = false;
  delete process.env.OPENCODE_CONFIG_DIR;
});

// Context object for testing
const ctx = {
  directory: "/test/project",
} as any;

describe("validateOptions", () => {
  test("returns null for valid options", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const result = validateOptions({
      title: "Test Title",
      message: "Test message",
      sound: true,
      timeout: 60,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBeNull();
  });

  test("returns error for title > 256 characters", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const longTitle = "a".repeat(257);
    const result = validateOptions({
      title: longTitle,
      message: "Test message",
      sound: true,
      timeout: 60,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBe("Title and message must be 256 characters or less");
  });

  test("returns error for message > 256 characters", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const longMessage = "a".repeat(257);
    const result = validateOptions({
      title: "Test Title",
      message: longMessage,
      sound: true,
      timeout: 60,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBe("Title and message must be 256 characters or less");
  });

  test("accepts title exactly 256 characters", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const exact256 = "a".repeat(256);
    const result = validateOptions({
      title: exact256,
      message: "Test message",
      sound: true,
      timeout: 60,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBeNull();
  });

  test("accepts message exactly 256 characters", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const exact256 = "a".repeat(256);
    const result = validateOptions({
      title: "Test Title",
      message: exact256,
      sound: true,
      timeout: 60,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBeNull();
  });

  test("returns error for negative timeout", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const result = validateOptions({
      title: "Test Title",
      message: "Test message",
      sound: true,
      timeout: -1,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBe("Timeout must be between 0 and 86400 seconds");
  });

  test("returns error for timeout > 86400", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const result = validateOptions({
      title: "Test Title",
      message: "Test message",
      sound: true,
      timeout: 86401,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBe("Timeout must be between 0 and 86400 seconds");
  });

  test("accepts timeout of 0", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const result = validateOptions({
      title: "Test Title",
      message: "Test message",
      sound: true,
      timeout: 0,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBeNull();
  });

  test("accepts timeout of 86400 (exactly 24 hours)", async () => {
    const { validateOptions } = await import("../tools/notify.ts");
    const result = validateOptions({
      title: "Test Title",
      message: "Test message",
      sound: true,
      timeout: 86400,
      urgency: "normal",
      wait: false,
    });
    expect(result).toBeNull();
  });
});

describe("getConfigDir", () => {
  test("returns OPENCODE_CONFIG_DIR when set", async () => {
    process.env.OPENCODE_CONFIG_DIR = "/custom/config";
    // Re-import to pick up the new env var
    mock.module("node:os", () => ({
      homedir: () => "/home/testuser",
    }));

    const { getConfigDir } = await import("../tools/notify.ts");
    const result = getConfigDir();
    expect(result).toBe("/custom/config");
  });

  test("falls back to homedir/.config/opencode when env var not set", async () => {
    delete process.env.OPENCODE_CONFIG_DIR;

    const { getConfigDir } = await import("../tools/notify.ts");
    const result = getConfigDir();
    expect(result).toBe("/home/testuser/.config/opencode");
  });

  test("falls back to homedir when OPENCODE_CONFIG_DIR is empty string", async () => {
    process.env.OPENCODE_CONFIG_DIR = "";

    const { getConfigDir } = await import("../tools/notify.ts");
    const result = getConfigDir();
    // Empty string is falsy, so it should fall back
    expect(result).toBe("/home/testuser/.config/opencode");
  });
});

describe("send tool", () => {
  test("sends notification successfully", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test Title",
        message: "Test message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe("Notification sent: Test Title - Test message");
    expect(notifierCalls).toHaveLength(1);
  });

  test("returns failure message when notifier fails", async () => {
    const errorSpy = mock(() => {});
    const originalError = console.error;
    console.error = errorSpy;

    notifierShouldFail = true;

    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test Title",
        message: "Test message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe(
      "Failed to send notification: node-notifier failed. Ensure node-notifier is installed and a notification daemon is running.",
    );
    expect(notifierCalls).toHaveLength(1);
    expect(errorSpy).toHaveBeenCalledWith(
      "node-notifier error:",
      "Notification failed",
    );

    console.error = originalError;
  });

  test("returns validation error for title too long", async () => {
    const { send } = await import("../tools/notify.ts");
    const longTitle = "a".repeat(257);

    const result = await send.execute(
      {
        title: longTitle,
        message: "Test message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe(
      "Validation error: Title and message must be 256 characters or less",
    );
    // Notifier should not be called when validation fails
    expect(notifierCalls).toHaveLength(0);
  });

  test("returns validation error for invalid timeout", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test Title",
        message: "Test message",
        sound: true,
        timeout: -1,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe(
      "Validation error: Timeout must be between 0 and 86400 seconds",
    );
    expect(notifierCalls).toHaveLength(0);
  });

  test("passes correct options to notifier", async () => {
    const { send } = await import("../tools/notify.ts");

    await send.execute(
      {
        title: "My Title",
        message: "My Message",
        sound: false,
        timeout: 30,
        urgency: "low",
        wait: true,
      },
      ctx,
    );

    expect(notifierCalls).toHaveLength(1);
    const options = notifierCalls[0]!;

    expect(options.title).toBe("My Title");
    expect(options.message).toBe("My Message");
    expect(options.sound).toBe(false);
    expect(options.timeout).toBe(30);
    expect(options.wait).toBe(true);
    expect(options.urgency).toBe("low");
    expect(options.icon).toBe(
      path.join("/home/testuser/.config/opencode", "notify-icon.png"),
    );
  });

  test("does not pass urgency 'normal' to notifier (optimization)", async () => {
    const { send } = await import("../tools/notify.ts");

    await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(notifierCalls).toHaveLength(1);
    const options = notifierCalls[0]!;

    // urgency should NOT be present when it's "normal"
    expect(options).not.toHaveProperty("urgency");
  });

  test("passes urgency 'low' to notifier", async () => {
    const { send } = await import("../tools/notify.ts");

    await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "low",
        wait: false,
      },
      ctx,
    );

    expect(notifierCalls).toHaveLength(1);
    const options = notifierCalls[0]!;

    expect(options.urgency).toBe("low");
  });

  test("passes urgency 'critical' to notifier", async () => {
    const { send } = await import("../tools/notify.ts");

    await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "critical",
        wait: false,
      },
      ctx,
    );

    expect(notifierCalls).toHaveLength(1);
    const options = notifierCalls[0]!;

    expect(options.urgency).toBe("critical");
  });

  test("uses default values when args are not provided", async () => {
    const { send } = await import("../tools/notify.ts");

    // Pass minimal args - defaults should kick in
    const result = await send.execute(
      {
        title: "Test",
        message: "Message",
      } as any,
      ctx,
    );

    expect(result).toBe("Notification sent: Test - Message");
    expect(notifierCalls).toHaveLength(1);

    const options = notifierCalls[0]!;
    expect(options.sound).toBe(true); // default
    expect(options.timeout).toBe(60); // default
    expect(options.wait).toBe(false); // default
    // urgency "normal" is not passed (optimization)
    expect(options).not.toHaveProperty("urgency");
  });

  test("icon path uses config directory", async () => {
    const { send } = await import("../tools/notify.ts");

    await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    const options = notifierCalls[0]!;
    expect(options.icon).toBe(
      "/home/testuser/.config/opencode/notify-icon.png",
    );
  });

  test("icon path respects OPENCODE_CONFIG_DIR", async () => {
    process.env.OPENCODE_CONFIG_DIR = "/custom/path";

    // Need to re-import to pick up the new env var
    // Reset the module cache by re-mocking
    mock.module("node:os", () => ({
      homedir: () => "/home/testuser",
    }));

    const { send } = await import("../tools/notify.ts");

    await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    const options = notifierCalls[0]!;
    expect(options.icon).toBe("/custom/path/notify-icon.png");
  });

  test("handles special characters in title and message", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test ๐ŸŽ‰ Unicode!",
        message: "Message with\nnewlines and\ttabs",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe(
      "Notification sent: Test ๐ŸŽ‰ Unicode! - Message with\nnewlines and\ttabs",
    );
    expect(notifierCalls).toHaveLength(1);

    const options = notifierCalls[0]!;
    expect(options.title).toBe("Test ๐ŸŽ‰ Unicode!");
    expect(options.message).toBe("Message with\nnewlines and\ttabs");
  });

  test("handles empty title", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    // Empty string is valid (length 0 <= 256)
    expect(result).toBe("Notification sent:  - Message");
    expect(notifierCalls).toHaveLength(1);
  });

  test("handles empty message", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Title",
        message: "",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    // Empty string is valid (length 0 <= 256)
    expect(result).toBe("Notification sent: Title - ");
    expect(notifierCalls).toHaveLength(1);
  });

  test("catches and returns error for exceptions in execute", async () => {
    // Force an exception by making notifier throw synchronously
    mock.module("node-notifier", () => ({
      default: {
        notify: mock(() => {
          throw new Error("Sync error");
        }),
      },
    }));

    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe("Notification error: Sync error");

    // Restore the normal mock for subsequent tests
    mock.module("node-notifier", () => ({
      default: {
        notify: mock(
          (
            options: Record<string, unknown>,
            callback: (err: Error | null) => void,
          ) => {
            notifierCalls.push(options);
            callback(
              notifierShouldFail ? new Error("Notification failed") : null,
            );
          },
        ),
      },
    }));
  });
});

describe("send tool - edge cases", () => {
  test("handles timeout boundary at 0", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 0,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe("Notification sent: Test - Message");
    expect(notifierCalls).toHaveLength(1);
    expect(notifierCalls[0]!.timeout).toBe(0);
  });

  test("handles timeout boundary at 86400", async () => {
    const { send } = await import("../tools/notify.ts");

    const result = await send.execute(
      {
        title: "Test",
        message: "Message",
        sound: true,
        timeout: 86400,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe("Notification sent: Test - Message");
    expect(notifierCalls).toHaveLength(1);
    expect(notifierCalls[0]!.timeout).toBe(86400);
  });

  test("title exactly 256 chars passes validation", async () => {
    const { send } = await import("../tools/notify.ts");
    const exact256 = "a".repeat(256);

    const result = await send.execute(
      {
        title: exact256,
        message: "Message",
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe(`Notification sent: ${exact256} - Message`);
    expect(notifierCalls).toHaveLength(1);
  });

  test("message exactly 256 chars passes validation", async () => {
    const { send } = await import("../tools/notify.ts");
    const exact256 = "b".repeat(256);

    const result = await send.execute(
      {
        title: "Title",
        message: exact256,
        sound: true,
        timeout: 60,
        urgency: "normal",
        wait: false,
      },
      ctx,
    );

    expect(result).toBe(`Notification sent: Title - ${exact256}`);
    expect(notifierCalls).toHaveLength(1);
  });
});