Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
test([high-tests-create-test-files-for-server-services]): cover clinvar + telegramBridge
[._.]/ Adam Eivy44e60b700d0d
diff --git a/DONE.md b/DONE.mdindex a179714245..2a7f1e203d 100644--- a/DONE.md+++ b/DONE.md@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-19+- **[high-tests-create-test-files-for-server-services] Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.** Both services had no sibling test file — clinvar covers the genome-scan path PortOS uses to flag actionable variants from a 23andMe upload, and telegramBridge is the outbound HTTP bridge that mirrors notifications to a Telegram chat. New `clinvar.test.js` (12 cases) pins `getClinvarStatus`, `scanClinvar` (severity sort + star tiebreak + corrupt-JSON + unknown-severity fallback), `invalidateClinvarCache`, and `deleteClinvar` (success + ENOENT-swallowed). New `telegramBridge.test.js` (14 cases) pins `init` (4 branches: no token, no allowFrom, getMe rejection, happy path + multi-line .env), `sendMessage` (pre-init, success body shape, ok:false surfaced, rate-limit drain at 30), `reload` (no-op when inactive, chat-id swap when active), `cleanup` (state reset + listener unsubscribe), and notification forwarding through the real `notificationEvents` EventEmitter (HTML-escape + emoji formatting + cachedForwardTypes whitelist filter). Module-level token-bucket reset between tests uses `vi.useFakeTimers({ toFake: ['Date'] })` + `setSystemTime` advancing 5 minutes per test so `refillTokens()` fires on the next consumeToken call. All 5781 server tests pass.- **[wardroberow-migrate-to-userowdraft] Migrate `WardrobeRow` to consume `useRowDraft`.** `client/src/components/pipeline/CanonCard.jsx` no longer runs two `useFieldDraft` calls per outfit row — a single `useRowDraft(wardrobe, onCommit)` call covers both columns, so wardrobe entries pick up the same sibling-draft ride-along race protection that landed for `ListRow` in `[characterdetaileditor-listrow-row-draft-hook]`. `WardrobeSection.commit` reshapes from `(idx, field, value)` to `(idx, nextRow)`; the pending-row promotion trigger moves from "per-field `name` commit with non-empty value" to "any commit where `nextRow.name.trim()` is non-empty" — same end state, and the rewrite fires earlier for the ride-along case (description blur with a pending name draft now promotes the row instead of stranding it in `pendingNew`). The deferred concern from PLAN ("promotion semantics need their own design pass") resolved by following the existing `CharacterDetailEditor.updateRow` pattern, which already runs the same required-column check against `nextRow`. Removed the now-unused `useFieldDraft` import from `CanonCard.jsx`. +1 ride-along regression test in `CanonCard.test.jsx` (description blurs first with a pending name draft → row promotes with both fields intact). All 121 client tests pass.- **[code-quality-dedup-batch] Code quality / dedup batch — 8 items shipped together.** (1) `[extract-optionalbooleanmap-zod-helper]` — new `optionalBooleanMap(keys)` helper in `server/lib/validation.js` collapsing the `Object.fromEntries(KEYS.map((k) => [k, z.boolean().optional()]))` pattern at 3 sites (`server/routes/universeBuilder.js`, `server/routes/pipeline.js` ×2). (2) `[extract-a-tryreadfile-helper]` — new `tryReadFile(path, encoding='utf8')` in `server/lib/fileUtils.js` replacing the `readFile(...).catch(() => null)` pattern at ~60 sites across `server/`; `readFile` import removed from 22 files where all uses migrated. Auto-injected `tryReadFile` mock into ~80 test files' `vi.mock('../lib/fileUtils.js')` bodies to keep partial mocks working. (3) `[aitoolkit-loadproviders-corrupt-fallback]` — `loadProviders` in `server/lib/aiToolkit/providers.js` now wraps `JSON.parse` in a `parseOrRescue(content, source)` helper that renames the corrupt user file to `<path>.corrupt.<timestamp>` + logs + returns `{ activeProvider: null, providers: {} }` so a garbled providers.json can't crash server boot. The shipped-sample path parses BEFORE persisting so a malformed sample can't seed user-side providers.json with garbage (per codex review). (4) `[more-resolveproviderandmodel-migration-candidates]` — migrated 3 sites onto the existing `resolveProviderAndModel` helper (`server/services/agentContentGenerator.js#runAIGeneration`, `server/services/agentPersonalityGenerator.js`, `server/services/loops.js#runIteration`); loops.js wraps with `.catch(() => ({ provider: null }))` to preserve the original "swallow all" semantics across both `getProviderById` and `getActiveProvider` failures. (5) `[extract-assertprovider-helper]` — new `assertProvider(provider, { message, code, status = 503 })` helper in `server/lib/promptRunner.js`; throws `ServerError` with code+status when `code` is provided, plain `Error` otherwise (preserves each caller's original error shape). Migrated 7 `if (!provider) throw …` sites (`universeBuilderAutoSort.js`, `universeBuilderRefine.js`, `universeBuilderExpand.js` ×2, `universeBuilderPromote.js`, `agentContentGenerator.js`, `agentPersonalityGenerator.js`). Auto-injected `assertProvider` mock into 6 test files mocking `promptRunner.js`. (6) `[extract-uselocktoggle-hook]` — new `useLockToggle({ patchFn, onSuccess, lockedMessage, unlockedMessage, errorMessage })` returning `{ busy, toggle }` in `client/src/hooks/useLockToggle.js` collapsing the optimistic-PATCH lock toggle pattern at 4 sites: `toggleArcLock`/`FieldLockToggle#toggle`/`toggleSeasonLock` in `client/src/components/pipeline/ArcCanvas.jsx`, `handleStageLockToggle` in `client/src/pages/PipelineIssue.jsx` (removes the now-dead `stageLockSaving` useState). (7) `[skip-the-text-accumulator-in-promptrunner]` — `runPromptThroughProvider`'s `onData` now skips the `APPEND_CHUNK` text concat for TUI providers (which discard the accumulated `text` anyway in favor of `result.text` from `executeTuiRun`); TUI screen-redraw streams can hit hundreds of KB per run. (8) `[aitoolkit-createprovider-field-parity-test]` — new exhaustive test in `server/lib/aiToolkit/providers.test.js` that round-trips all 20 fields defined in `createProvider`'s explicit field list through `create → save → reload`, guarding against the regression where a Zod-schema field is added without being mirrored into the explicit `createProvider` field list. All 5690 server tests + 103 client tests pass; client build clean.- **[characterdetaileditor-listrow-row-draft-hook] Extract `ListRow`'s multi-column row-draft state into a shared `useRowDraft` hook.** `client/src/components/universe/CharacterDetailEditor.jsx`'s `ListRow` carried 19 lines of inline `useState({})` draft buffer + `draftFor`/`setDraft`/`commit` triple, with the load-bearing sibling-draft "ride-along" merge (`{...row, ...drafts, [col]: v}`) that keeps a fast A-blur → B-blur sequence from losing column A when the parent hasn't re-rendered yet. Lifted into new `client/src/hooks/useRowDraft.js` — the row-level analogue of `useFieldDraft` (single-field draft+blur). Hook signature is `useRowDraft(row, onChange)` returning `{ draftFor, setDraft, commit }`; preserves the ride-along merge verbatim and coerces `null`/`undefined` persisted columns to `''` so inputs stay controlled. `ListRow` collapses to a single hook call. 9 new vitest cases cover persisted/empty fallback, draft buffering without firing onChange, commit no-op when value equals persisted, commit no-op when no draft set, null-as-empty equivalence, the ride-along race-protection invariant (committing column B with a pending column-A draft ships both in one onChange), and that commit clears only the committed column from the drafts map. All 112 client tests pass.diff --git a/PLAN.md b/PLAN.mdindex 0f70276cc2..5b5a063603 100644--- a/PLAN.md+++ b/PLAN.md@@ -115,7 +115,6 @@ _Nothing currently parked — pick the next item from the Backlog._### Better-audit residue- [x] [high-code-server-services-cos-js-3113-remove-node] ~~**[HIGH][CODE]** `server/services/cos.js:3113` — remove `NODE_ENV !== 'test' && VITEST !== 'true'` init guard (test hack in prod boot path).~~ **Shipped 2026-05-17** — `init()` is now exported and called explicitly from `server/index.js` (alongside the other `*.init()` calls); module-level auto-init removed entirely so the test guard is no longer needed.-- [ ] [high-tests-create-test-files-for-server-services] **[HIGH][TESTS]** Create test files for `server/services/clinvar.js` and `server/services/telegramBridge.js`.- [ ] [high-tests-add-coverage-for-server-services-shell] **[HIGH][TESTS]** Add coverage for `server/services/shell.js` and `server/services/feeds.js` — both have exported functions but no sibling test. Shell drives all terminal sessions; feeds manages subscriptions. (New — surfaced 2026-05-16 replan.)- [ ] [low-client-extract-shared-usepopoverposition-hook] **[LOW][CLIENT]** Extract shared `usePopoverPosition` hook — **premise eroded; revisit when a 3rd caller lands.** Original PLAN flagged 4 components but `VisualStylePicker` no longer exists and `AddToCollectionMenu` / `BulkTargetPicker` no longer use portal positioning. Today the pattern lives in exactly two components (`client/src/components/ThemeSwitcher.jsx` and `client/src/components/media/CollectionPickerShell.jsx`) — both implement portal-with-fixed-positioning + `useLayoutEffect` measurement + rAF-coalesced scroll/resize listeners. With only 2 callers the abstraction isn't worth the indirection; extract when a third surface needs the same shape.- [ ] [extract-requiretoolkit-pattern-to-runner-js] **[MEDIUM][CODE]** Extend the `requireToolkit()` pattern from `server/services/providers.js` to `server/services/runner.js` — 13 sites of `if (!aiToolkitInstance) throw new Error('AI Toolkit not initialized')` still inlined there (lines 27, 144, 218, 332, 343 + others). Surfaced by /simplify during the better-audit residue refactor bundle; left out of that PR to keep scope tight. Should reuse the same `ServerError({ status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` shape providers.js now throws.diff --git a/server/services/clinvar.test.js b/server/services/clinvar.test.jsnew file mode 100644index 0000000000..7bc65623df--- /dev/null+++ b/server/services/clinvar.test.js@@ -0,0 +1,228 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const NOT_SYNCED_ERROR = 'ClinVar database not synced. Click "Sync ClinVar" first.';+const NO_GENOME_ERROR = 'No genome data uploaded.';++// Mock the file-system helpers clinvar.js consumes. The service reads the+// compact index + meta via tryReadFile and writes/deletes via fs/promises.+const fileStore = new Map();++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { meatspace: '/mock/meatspace' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ tryReadFile: vi.fn(async (path) => (fileStore.has(path) ? fileStore.get(path) : null)),+ safeJSONParse: (raw, fallback) => {+ try {+ return JSON.parse(raw);+ } catch {+ return fallback;+ }+ }+}));++vi.mock('fs/promises', () => ({+ writeFile: vi.fn(async (path, data) => {+ fileStore.set(path, data);+ }),+ unlink: vi.fn(async (path) => {+ if (!fileStore.has(path)) {+ const err = new Error('ENOENT');+ err.code = 'ENOENT';+ throw err;+ }+ fileStore.delete(path);+ })+}));++const INDEX_PATH = '/mock/meatspace/clinvar-index.json';+const META_PATH = '/mock/meatspace/clinvar-meta.json';+const GZ_PATH = '/mock/meatspace/clinvar-raw.txt.gz';++const {+ getClinvarStatus,+ invalidateClinvarCache,+ scanClinvar,+ deleteClinvar+} = await import('./clinvar.js');++describe('clinvar service', () => {+ beforeEach(() => {+ fileStore.clear();+ invalidateClinvarCache();+ });++ describe('getClinvarStatus', () => {+ it('returns { synced: false } when no meta file exists', async () => {+ expect(await getClinvarStatus()).toEqual({ synced: false });+ });++ it('returns the parsed meta payload when present', async () => {+ const meta = {+ synced: true,+ syncedAt: '2026-05-19T00:00:00.000Z',+ variantCount: 12345,+ downloadSize: 50_000_000,+ indexSize: 4_000_000+ };+ fileStore.set(META_PATH, JSON.stringify(meta));+ expect(await getClinvarStatus()).toEqual(meta);+ });+ });++ describe('scanClinvar', () => {+ it('errors when the index has not been synced', async () => {+ const result = await scanClinvar(new Map());+ expect(result.error).toBe(NOT_SYNCED_ERROR);+ });++ it('errors when snpIndex is missing', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({}));+ const result = await scanClinvar(null);+ expect(result.error).toBe(NO_GENOME_ERROR);+ });++ it('matches rsids against the ClinVar index and returns enriched findings', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs1: { g: 'BRCA1', s: 'pathogenic', c: ['Hereditary cancer'], r: 3, x: 'Pathogenic', n: 5 },+ rs2: { g: 'CYP2C19', s: 'drug_response', c: ['Clopidogrel response'], r: 2, x: 'drug response', n: 2 }+ }));+ const snpIndex = new Map([+ ['rs1', { genotype: 'AG', chromosome: '17', position: '41197695' }],+ ['rs2', { genotype: 'GG', chromosome: '10', position: '96521656' }],+ ['rs9999', { genotype: 'AA', chromosome: '1', position: '1' }] // not in index+ ]);++ const result = await scanClinvar(snpIndex);++ expect(result.totalMatched).toBe(2);+ expect(result.findings).toHaveLength(2);++ const brca1 = result.findings.find(f => f.rsid === 'rs1');+ expect(brca1).toMatchObject({+ gene: 'BRCA1',+ severity: 'pathogenic',+ status: 'major_concern',+ conditions: ['Hereditary cancer'],+ reviewStars: 3,+ submissions: 5,+ genotype: 'AG',+ chromosome: '17',+ position: '41197695'+ });++ const cyp = result.findings.find(f => f.rsid === 'rs2');+ expect(cyp.status).toBe('concern');+ expect(cyp.severity).toBe('drug_response');++ expect(result.bySeverity).toEqual({+ pathogenic: 1,+ drug_response: 1,+ risk_factor: 0,+ protective: 0+ });+ });++ it('sorts pathogenic before drug_response before risk_factor before protective', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs_prot: { g: 'G1', s: 'protective', c: [], r: 1, x: 'protective', n: 1 },+ rs_risk: { g: 'G2', s: 'risk_factor', c: [], r: 1, x: 'risk factor', n: 1 },+ rs_drug: { g: 'G3', s: 'drug_response', c: [], r: 1, x: 'drug response', n: 1 },+ rs_path: { g: 'G4', s: 'pathogenic', c: [], r: 1, x: 'pathogenic', n: 1 }+ }));+ const snpIndex = new Map([+ ['rs_prot', { genotype: 'CC' }],+ ['rs_risk', { genotype: 'AT' }],+ ['rs_drug', { genotype: 'GG' }],+ ['rs_path', { genotype: 'TT' }]+ ]);++ const { findings } = await scanClinvar(snpIndex);+ expect(findings.map(f => f.severity)).toEqual([+ 'pathogenic',+ 'drug_response',+ 'risk_factor',+ 'protective'+ ]);+ });++ it('breaks ties on severity by review-star count (descending)', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs_low: { g: 'G1', s: 'pathogenic', c: [], r: 1, x: 'pathogenic', n: 1 },+ rs_high: { g: 'G2', s: 'pathogenic', c: [], r: 4, x: 'pathogenic', n: 1 },+ rs_mid: { g: 'G3', s: 'pathogenic', c: [], r: 2, x: 'pathogenic', n: 1 }+ }));+ const snpIndex = new Map([+ ['rs_low', { genotype: 'AA' }],+ ['rs_high', { genotype: 'AA' }],+ ['rs_mid', { genotype: 'AA' }]+ ]);++ const { findings } = await scanClinvar(snpIndex);+ expect(findings.map(f => f.rsid)).toEqual(['rs_high', 'rs_mid', 'rs_low']);+ });++ it('maps unknown severity to the generic "concern" status', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs_weird: { g: 'Gx', s: 'mystery', c: [], r: 0, x: 'mystery', n: 1 }+ }));+ const { findings } = await scanClinvar(new Map([['rs_weird', { genotype: 'AA' }]]));+ expect(findings[0].status).toBe('concern');+ });++ it('returns gracefully when the index file is corrupt JSON', async () => {+ fileStore.set(INDEX_PATH, 'not-json-at-all{{{');+ const result = await scanClinvar(new Map([['rs1', { genotype: 'AA' }]]));+ expect(result.error).toBe(NOT_SYNCED_ERROR);+ });+ });++ describe('invalidateClinvarCache', () => {+ it('forces the next scan to re-read the index file from disk', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs1: { g: 'G1', s: 'pathogenic', c: [], r: 1, x: 'pathogenic', n: 1 }+ }));+ const first = await scanClinvar(new Map([['rs1', { genotype: 'AA' }]]));+ expect(first.totalMatched).toBe(1);++ // Mutate disk-state; with the cache live, the next scan should still see rs1.+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs2: { g: 'G2', s: 'pathogenic', c: [], r: 1, x: 'pathogenic', n: 1 }+ }));+ const cached = await scanClinvar(new Map([['rs1', { genotype: 'AA' }]]));+ expect(cached.totalMatched).toBe(1);++ // After invalidation, the next scan sees the fresh disk state.+ invalidateClinvarCache();+ const fresh = await scanClinvar(new Map([['rs1', { genotype: 'AA' }]]));+ expect(fresh.totalMatched).toBe(0);+ });+ });++ describe('deleteClinvar', () => {+ it('unlinks index + meta + raw, clears the cache, and reports success', async () => {+ fileStore.set(INDEX_PATH, JSON.stringify({+ rs1: { g: 'G1', s: 'pathogenic', c: [], r: 1, x: 'pathogenic', n: 1 }+ }));+ fileStore.set(META_PATH, JSON.stringify({ synced: true }));+ fileStore.set(GZ_PATH, 'binary-bytes');++ // Prime the in-memory cache.+ await scanClinvar(new Map([['rs1', { genotype: 'AA' }]]));++ const result = await deleteClinvar();+ expect(result).toEqual({ success: true });+ expect(fileStore.has(INDEX_PATH)).toBe(false);+ expect(fileStore.has(META_PATH)).toBe(false);+ expect(fileStore.has(GZ_PATH)).toBe(false);++ // Cache cleared: next scan with no index file returns the error sentinel.+ const scanAfter = await scanClinvar(new Map([['rs1', { genotype: 'AA' }]]));+ expect(scanAfter.error).toBe(NOT_SYNCED_ERROR);+ });++ it('succeeds even if no ClinVar files exist (unlink ENOENT is swallowed)', async () => {+ const result = await deleteClinvar();+ expect(result).toEqual({ success: true });+ });+ });+});diff --git a/server/services/telegramBridge.test.js b/server/services/telegramBridge.test.jsnew file mode 100644index 0000000000..215c2942b2--- /dev/null+++ b/server/services/telegramBridge.test.js@@ -0,0 +1,284 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { homedir } from 'os';+import { join } from 'path';++const ENV_FILE = join(homedir(), '.claude', 'channels', 'telegram', '.env');+const ACCESS_FILE = join(homedir(), '.claude', 'channels', 'telegram', 'access.json');++// Files the bridge reads at init/reload time.+const fileStore = new Map();++vi.mock('../lib/fileUtils.js', () => ({+ tryReadFile: vi.fn(async (path) => (fileStore.has(path) ? fileStore.get(path) : null)),+ // Stubs to satisfy notifications.js (the real module imports these at load).+ PATHS: { data: '/mock/data' },+ ensureDir: vi.fn().mockResolvedValue(undefined),+ readJSONFile: vi.fn().mockResolvedValue(null),+ atomicWrite: vi.fn().mockResolvedValue(undefined)+}));++// We import the real notifications module so the bridge can subscribe to the+// event emitter — that's the spot where forwardNotification is exercised+// without poking at any private internal.+const { notificationEvents, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');++const {+ init,+ cleanup,+ sendMessage,+ getStatus,+ reload,+ updateCachedForwardTypes+} = await import('./telegramBridge.js');++const BOT_TOKEN = '123:ABC';+const CHAT_ID = 12345;++// Multi-tick flush so the EventEmitter handler → sendMessage → apiCall →+// res.json() microtask chain settles before we assert on fetch calls.+async function flush() {+ for (let i = 0; i < 5; i++) {+ await new Promise((resolve) => setImmediate(resolve));+ }+}++function mockTelegramFetch({ getMeOk = true, sendOk = true } = {}) {+ const fetchSpy = vi.fn(async (url) => {+ if (url.endsWith('/getMe')) {+ return {+ ok: true,+ json: async () => (getMeOk+ ? { ok: true, result: { username: 'portos_test_bot' } }+ : { ok: false, description: 'Unauthorized' })+ };+ }+ if (url.endsWith('/sendMessage')) {+ return {+ ok: true,+ json: async () => (sendOk+ ? { ok: true, result: { message_id: 1 } }+ : { ok: false, description: 'Bad Request' })+ };+ }+ throw new Error(`unexpected telegram URL ${url}`);+ });+ return fetchSpy;+}++function seedCredentials(chatId = CHAT_ID) {+ fileStore.set(ENV_FILE, `TELEGRAM_BOT_TOKEN=${BOT_TOKEN}\n`);+ fileStore.set(ACCESS_FILE, JSON.stringify({ allowFrom: [chatId] }));+}++describe('telegramBridge service', () => {+ // The rate-limit token bucket is module-level state with no public reset;+ // bumping the virtual clock by 5 minutes between tests guarantees the next+ // consumeToken() call triggers a bucket refill before any assertions.+ let virtualNow = Date.now();++ beforeEach(() => {+ fileStore.clear();+ virtualNow += 5 * 60_000;+ vi.useFakeTimers({ now: virtualNow, toFake: ['Date'] });+ });++ afterEach(async () => {+ // Reset module-level state and unsubscribe from the EventEmitter.+ await cleanup();+ updateCachedForwardTypes(null);+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ describe('init', () => {+ it('returns false when no bot token file is present', async () => {+ expect(await init()).toBe(false);+ expect(getStatus()).toMatchObject({ connected: false, hasBotToken: false });+ });++ it('returns false when the access.json has no allowFrom entries', async () => {+ fileStore.set(ENV_FILE, `TELEGRAM_BOT_TOKEN=${BOT_TOKEN}\n`);+ fileStore.set(ACCESS_FILE, JSON.stringify({ allowFrom: [] }));+ expect(await init()).toBe(false);+ expect(getStatus().connected).toBe(false);+ });++ it('returns false and clears the token when getMe rejects the token', async () => {+ seedCredentials();+ vi.stubGlobal('fetch', mockTelegramFetch({ getMeOk: false }));+ expect(await init()).toBe(false);+ expect(getStatus()).toMatchObject({+ connected: false,+ botUsername: null,+ hasBotToken: false,+ hasChatId: true+ });+ });++ it('returns true and records the bot username on a valid handshake', async () => {+ seedCredentials();+ vi.stubGlobal('fetch', mockTelegramFetch());+ expect(await init()).toBe(true);+ expect(getStatus()).toMatchObject({+ connected: true,+ botUsername: 'portos_test_bot',+ chatId: CHAT_ID,+ hasBotToken: true,+ hasChatId: true+ });+ });++ it('parses TELEGRAM_BOT_TOKEN from a multi-line .env file', async () => {+ fileStore.set(ENV_FILE, `OTHER=ignored\nTELEGRAM_BOT_TOKEN=${BOT_TOKEN}\nTRAILING=value\n`);+ fileStore.set(ACCESS_FILE, JSON.stringify({ allowFrom: [CHAT_ID] }));+ vi.stubGlobal('fetch', mockTelegramFetch());+ expect(await init()).toBe(true);+ expect(getStatus().connected).toBe(true);+ });+ });++ describe('sendMessage', () => {+ it('refuses to send before init (no bot token)', async () => {+ const result = await sendMessage('hello');+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/no bot token/i);+ });++ it('posts to the Telegram API with HTML parse mode', async () => {+ seedCredentials();+ const fetchSpy = mockTelegramFetch();+ vi.stubGlobal('fetch', fetchSpy);+ await init();++ const result = await sendMessage('<b>hi</b>');+ expect(result).toEqual({ success: true });++ const sendCall = fetchSpy.mock.calls.find(([url]) => url.endsWith('/sendMessage'));+ expect(sendCall).toBeDefined();+ const [, opts] = sendCall;+ expect(opts.method).toBe('POST');+ expect(JSON.parse(opts.body)).toEqual({+ chat_id: CHAT_ID,+ text: '<b>hi</b>',+ parse_mode: 'HTML'+ });+ });++ it('surfaces an error when the API replies ok:false', async () => {+ seedCredentials();+ vi.stubGlobal('fetch', mockTelegramFetch({ sendOk: false }));+ await init();+ const result = await sendMessage('boom');+ expect(result).toEqual({ success: false, error: 'Send failed' });+ });++ it('returns a rate-limit error once the 30-message bucket drains', async () => {+ seedCredentials();+ const fetchSpy = mockTelegramFetch();+ vi.stubGlobal('fetch', fetchSpy);+ await init();+ // init() consumes one call against /getMe; reset before counting sends.+ fetchSpy.mockClear();++ // Drain 30 successes, then the 31st must hit the rate-limit branch.+ for (let i = 0; i < 30; i++) await sendMessage(`msg ${i}`);+ const sent = fetchSpy.mock.calls.filter(([url]) => url.endsWith('/sendMessage'));+ expect(sent).toHaveLength(30);++ const blocked = await sendMessage('one too many');+ expect(blocked).toEqual({ success: false, error: 'Rate limit exceeded' });+ });+ });++ describe('reload', () => {+ it('no-ops when the bridge is not active', async () => {+ // Seed a different chat id but don't init — reload should silently do nothing.+ fileStore.set(ACCESS_FILE, JSON.stringify({ allowFrom: [999] }));+ await reload();+ expect(getStatus().chatId).toBeNull();+ });++ it('swaps the chat id when access.json changes while active', async () => {+ seedCredentials();+ vi.stubGlobal('fetch', mockTelegramFetch());+ await init();+ expect(getStatus().chatId).toBe(CHAT_ID);++ fileStore.set(ACCESS_FILE, JSON.stringify({ allowFrom: [987] }));+ await reload();+ expect(getStatus().chatId).toBe(987);+ });+ });++ describe('cleanup', () => {+ it('clears module state and unsubscribes from notification events', async () => {+ seedCredentials();+ const fetchSpy = mockTelegramFetch();+ vi.stubGlobal('fetch', fetchSpy);+ await init();+ expect(notificationEvents.listenerCount('added')).toBeGreaterThanOrEqual(1);++ await cleanup();+ expect(getStatus()).toMatchObject({+ connected: false,+ botUsername: null,+ chatId: null,+ hasBotToken: false,+ hasChatId: false+ });+ expect(notificationEvents.listenerCount('added')).toBe(0);+ });+ });++ describe('notification forwarding', () => {+ it('forwards a notification by emitting an "added" event after init', async () => {+ seedCredentials();+ const fetchSpy = mockTelegramFetch();+ vi.stubGlobal('fetch', fetchSpy);+ await init();+ fetchSpy.mockClear();++ notificationEvents.emit('added', {+ type: NOTIFICATION_TYPES.HEALTH_ISSUE,+ title: 'High & rising',+ description: '<script>',+ priority: PRIORITY_LEVELS.HIGH+ });+ await flush();++ const sendCall = fetchSpy.mock.calls.find(([url]) => url.endsWith('/sendMessage'));+ expect(sendCall).toBeDefined();+ const body = JSON.parse(sendCall[1].body);+ expect(body.text).toContain('⚠️');+ expect(body.text).toContain('<b>High & rising</b>');+ expect(body.text).toContain('<script>');+ expect(body.text).toContain('Priority: 🟠 high');+ });++ it('filters by updateCachedForwardTypes when the whitelist is non-empty', async () => {+ seedCredentials();+ const fetchSpy = mockTelegramFetch();+ vi.stubGlobal('fetch', fetchSpy);+ await init();+ fetchSpy.mockClear();++ updateCachedForwardTypes([NOTIFICATION_TYPES.HEALTH_ISSUE]);+ notificationEvents.emit('added', {+ type: NOTIFICATION_TYPES.CODE_REVIEW, // not in whitelist+ title: 'PR ready',+ priority: PRIORITY_LEVELS.LOW+ });+ await flush();+ expect(fetchSpy.mock.calls.filter(([url]) => url.endsWith('/sendMessage'))).toHaveLength(0);++ fetchSpy.mockClear();+ notificationEvents.emit('added', {+ type: NOTIFICATION_TYPES.HEALTH_ISSUE,+ title: 'Glucose',+ priority: PRIORITY_LEVELS.MEDIUM+ });+ await flush();+ expect(fetchSpy.mock.calls.filter(([url]) => url.endsWith('/sendMessage'))).toHaveLength(1);+ });+ });+});