Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

8.6 KB
Raw Blame
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const Module = require("node:module");

const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");
const originalLoad = Module._load;

// Registers the real handler closures against a fake `this` (the scaffolding
// from agentDictationPillIpc.test.js) with the bearer state under test control
// and the binding file in a temporary userData directory, so the scope
// handlers run against the real accountScopeBinding.
const handlers = new Map();
const broadcasts = [];
const userDataDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "account-scope-ipc-"));
let tokenState = { token: null, generation: 0 };

const electronStub = {
  app: {
    getPath: () => userDataDirectory,
    getName: () => "test",
    getVersion: () => "0.0.0",
    isPackaged: false,
    on: () => {},
    requestSingleInstanceLock: () => true,
  },
  ipcMain: {
    handle: (channel, fn) => handlers.set(channel, fn),
    on: () => {},
    removeHandler: () => {},
  },
  net: {
    fetch: async () => ({
      ok: true,
      status: 200,
      json: async () => ({}),
      text: async () => "{}",
    }),
  },
  BrowserWindow: class BrowserWindow {
    static getAllWindows() {
      return [];
    }
    static fromWebContents() {
      return null;
    }
  },
  shell: {},
  dialog: {},
  screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
  systemPreferences: { getMediaAccessStatus: () => "granted" },
  session: { fromPartition: () => ({}) },
  clipboard: {},
  nativeImage: {},
  globalShortcut: {},
  utilityProcess: {},
  MessageChannelMain: class {},
};

Module._load = function loadWithMocks(request, parent, isMain) {
  if (request === "electron") return electronStub;
  if (parent?.filename === handlersModulePath) {
    if (request === "./tokenStore") {
      return {
        get: () => tokenState.token,
        getState: () => ({ ...tokenState }),
        clear: () => {
          tokenState = { token: null, generation: tokenState.generation + 1 };
          return { success: true, ...tokenState };
        },
        subscribe: () => () => {},
      };
    }
    if (request === "./windowBroadcast") {
      return { broadcastToWindows: (channel, data) => broadcasts.push([channel, data]) };
    }
  }
  return originalLoad.call(this, request, parent, isMain);
};

function anything() {
  return new Proxy(function () {}, {
    get: (target, property) => {
      if (property === Symbol.toPrimitive || property === "toString") return () => "";
      if (property === "then") return undefined;
      return anything();
    },
    apply: () => anything(),
  });
}

// Each call with the binding file as it stood then: a connect must be stopped
// only once the scope it ran under is gone.
const connectorCalls = [];
const connectorManager = {
  accountChanged: () => connectorCalls.push(["accountChanged", readBinding()?.accountId ?? null]),
  notifyStatusChanged: async () => connectorCalls.push(["notifyStatusChanged"]),
};

function readBinding() {
  return require("../../src/helpers/accountScopeBinding").read();
}

const databaseScopes = [];
const databaseManager = new Proxy(
  { setActiveAccountId: (accountId) => databaseScopes.push(accountId) },
  { get: (value, property) => (property in value ? value[property] : anything()) }
);

function buildFakeThis() {
  const target = { sessionId: "test-session", connectorManager, databaseManager };
  return new Proxy(target, {
    get: (value, property) => (property in value ? value[property] : anything()),
  });
}

let fakeThis;
let handleAuthTokenChange;

test.before(() => {
  delete require.cache[handlersModulePath];
  const IPCHandlers = require(handlersModulePath);
  const Ctor = IPCHandlers.default || IPCHandlers;
  fakeThis = buildFakeThis();
  Ctor.prototype.setupHandlers.call(fakeThis);
  handleAuthTokenChange = (state) => Ctor.prototype._handleAuthTokenChange.call(fakeThis, state);
});

test.after(() => {
  fakeThis.metaActivation?.dispose?.();
  Module._load = originalLoad;
  fs.rmSync(userDataDirectory, { recursive: true, force: true });
});

const getScope = () => handlers.get("get-active-account-scope")();
const setScope = (accountId, generation) =>
  handlers.get("set-active-account-scope")({}, accountId, generation);

test("no scope is readable before a session has been validated", async () => {
  tokenState = { token: "token-a", generation: 1 };
  assert.equal(await getScope(), null);
});

test("a validated scope is readable back and broadcast to every window", async () => {
  tokenState = { token: "token-a", generation: 1 };
  broadcasts.length = 0;
  assert.deepEqual(await setScope("account-a", 1), { success: true });
  assert.deepEqual(await getScope(), { accountId: "account-a", authGeneration: 1 });
  assert.deepEqual(broadcasts, [
    ["active-account-scope-changed", { accountId: "account-a", authGeneration: 1 }],
  ]);
});

test("a rotated bearer hides the scope until the session is validated again", async () => {
  tokenState = { token: "token-b", generation: 2 };
  assert.equal(await getScope(), null);
  await setScope("account-a", 2);
  assert.deepEqual(await getScope(), { accountId: "account-a", authGeneration: 2 });
});

test("a rejected scope request changes nothing and broadcasts nothing", async () => {
  tokenState = { token: "token-b", generation: 3 };
  broadcasts.length = 0;
  const result = await setScope("account-b", 2);
  assert.equal(result.success, false);
  assert.equal(result.code, "AUTH_CONTEXT_CHANGED");
  assert.deepEqual(broadcasts, []);
});

test("a validated sign-out clears the scope and broadcasts the clearing", async () => {
  tokenState = { token: null, generation: 4 };
  broadcasts.length = 0;
  assert.deepEqual(await setScope(null, 4), { success: true });
  assert.equal(await getScope(), null);
  assert.deepEqual(broadcasts, [["active-account-scope-changed", null]]);
});

test("a scope change stops connects another account started, after the scope moves", async () => {
  tokenState = { token: "token-c", generation: 5 };
  connectorCalls.length = 0;
  await setScope("account-c", 5);
  await setScope(null, 5);
  assert.deepEqual(connectorCalls, [
    ["accountChanged", "account-c"],
    ["notifyStatusChanged"],
    ["accountChanged", null],
    ["notifyStatusChanged"],
  ]);
});

test("a sign-out in main stops connects without waiting for the renderer", async () => {
  tokenState = { token: "token-d", generation: 6 };
  await setScope("account-d", 6);
  connectorCalls.length = 0;

  // A rotated token isn't another account: connects keep running.
  handleAuthTokenChange({ generation: 7, token: "token-e" });
  assert.deepEqual(connectorCalls, [["notifyStatusChanged"]]);

  connectorCalls.length = 0;
  databaseScopes.length = 0;
  broadcasts.length = 0;
  handleAuthTokenChange({ generation: 8, token: null });
  assert.deepEqual(connectorCalls, [["accountChanged", null], ["notifyStatusChanged"]]);
  assert.equal(readBinding(), null);
  assert.deepEqual(databaseScopes, [null]);
  assert.deepEqual(broadcasts, [
    ["active-account-scope-changed", null],
    ["auth-token-state-changed", { generation: 8, hasToken: false }],
  ]);
});

test("meeting prompt retirement precedes scope mutation and skips a true no-op", async () => {
  tokenState = { token: "meeting-test-token", generation: 20 };
  const originalManager = fakeThis.windowManager;
  const calls = [];
  fakeThis.windowManager = {
    retireMeetingNotificationScope: () => calls.push(databaseManager.activeAccountId),
  };
  databaseManager.activeAccountId = "old-account";
  await setScope("meeting-account", 20);
  assert.deepEqual(calls, ["old-account"]);
  databaseManager.activeAccountId = "meeting-account";
  await setScope("meeting-account", 20);
  assert.deepEqual(calls, ["old-account"]);
  handleAuthTokenChange({ token: "rotated", generation: 21 });
  assert.deepEqual(calls, ["old-account", "meeting-account"]);
  handleAuthTokenChange({ token: null, generation: 22 });
  assert.deepEqual(calls, ["old-account", "meeting-account", "meeting-account"]);
  fakeThis.windowManager = originalManager;
});

test("activation storage failure cannot prevent clearing the local bearer", async () => {
  const manager = fakeThis.metaActivation;
  fakeThis.metaActivation = {
    close: async () => {
      throw new Error("disk full");
    },
  };
  tokenState = { token: "must-clear", generation: 30 };
  try {
    const result = await handlers.get("auth-clear-session")({ sender: {} });
    assert.equal(result.success, true);
    assert.equal(tokenState.token, null);
    assert.equal(tokenState.generation, 31);
  } finally {
    fakeThis.metaActivation = manager;
  }
});