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: add unit tests for six untested lib helpers
Adam Eivy298e0f3e9afc
diff --git a/server/lib/aiProvider.test.js b/server/lib/aiProvider.test.jsnew file mode 100644index 0000000000..09a0f4bf16--- /dev/null+++ b/server/lib/aiProvider.test.js@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest';+import { stripCodeFences, parseLLMJSON } from './aiProvider.js';++describe('aiProvider pure helpers', () => {+ describe('stripCodeFences', () => {+ it('strips a leading ```json fence and trailing fence', () => {+ const raw = '```json\n{"a":1}\n```';+ expect(stripCodeFences(raw)).toBe('{"a":1}');+ });++ it('strips a bare ``` fence (no language tag)', () => {+ const raw = '```\n{"a":1}\n```';+ expect(stripCodeFences(raw)).toBe('{"a":1}');+ });++ it('leaves un-fenced text untouched (modulo trim)', () => {+ expect(stripCodeFences(' {"a":1} ')).toBe('{"a":1}');+ expect(stripCodeFences('{"a":1}')).toBe('{"a":1}');+ });++ it('strips a leading fence even without a trailing fence', () => {+ expect(stripCodeFences('```json\n{"a":1}')).toBe('{"a":1}');+ });++ it('strips a trailing fence even without a leading fence', () => {+ expect(stripCodeFences('{"a":1}\n```')).toBe('{"a":1}');+ });++ it('does not strip mid-string backticks', () => {+ const raw = '{"src":"```foo```"}';+ expect(stripCodeFences(raw)).toBe('{"src":"```foo```"}');+ });+ });++ describe('parseLLMJSON', () => {+ it('parses fenced JSON', () => {+ expect(parseLLMJSON('```json\n{"a":1,"b":[2,3]}\n```')).toEqual({ a: 1, b: [2, 3] });+ });++ it('parses bare JSON', () => {+ expect(parseLLMJSON('{"a":1}')).toEqual({ a: 1 });+ });++ it('throws a descriptive error on malformed JSON', () => {+ expect(() => parseLLMJSON('not json at all')).toThrow(/Invalid JSON from AI/);+ });++ it('error message includes the underlying parser detail', () => {+ let err;+ try { parseLLMJSON('{"a":1,'); } catch (e) { err = e; }+ expect(err).toBeDefined();+ expect(err.message).toMatch(/Invalid JSON from AI:/);+ });++ it('handles arrays and primitives at the top level', () => {+ expect(parseLLMJSON('[1,2,3]')).toEqual([1, 2, 3]);+ expect(parseLLMJSON('```\nnull\n```')).toBeNull();+ expect(parseLLMJSON('"hello"')).toBe('hello');+ });+ });+});diff --git a/server/lib/identityValidation.test.js b/server/lib/identityValidation.test.jsnew file mode 100644index 0000000000..b648228ff8--- /dev/null+++ b/server/lib/identityValidation.test.js@@ -0,0 +1,321 @@+import { describe, it, expect } from 'vitest';+import {+ sectionStatusEnum,+ chronotypeEnum,+ chronotypeBehavioralInputSchema,+ birthDateInputSchema,+ goalHorizonEnum,+ goalCategoryEnum,+ goalStatusEnum,+ goalTypeEnum,+ createGoalInputSchema,+ updateGoalInputSchema,+ addMilestoneInputSchema,+ aiProviderInputSchema,+ acceptPhasesInputSchema,+ addProgressEntrySchema,+ addTodoInputSchema,+ updateTodoInputSchema,+ updateProgressSchema,+ linkActivityInputSchema,+ linkCalendarInputSchema,+ applyOrganizationInputSchema+} from './identityValidation.js';++describe('identityValidation', () => {+ describe('enums', () => {+ it('sectionStatusEnum admits the documented states', () => {+ for (const v of ['active', 'pending', 'unavailable']) {+ expect(sectionStatusEnum.safeParse(v).success).toBe(true);+ }+ expect(sectionStatusEnum.safeParse('archived').success).toBe(false);+ });++ it('chronotypeEnum admits the three classic chronotypes', () => {+ for (const v of ['morning', 'intermediate', 'evening']) {+ expect(chronotypeEnum.safeParse(v).success).toBe(true);+ }+ expect(chronotypeEnum.safeParse('night-owl').success).toBe(false);+ });++ it('goalHorizonEnum covers 1y through lifetime', () => {+ for (const v of ['1-year', '3-year', '5-year', '10-year', '20-year', 'lifetime']) {+ expect(goalHorizonEnum.safeParse(v).success).toBe(true);+ }+ expect(goalHorizonEnum.safeParse('30-year').success).toBe(false);+ });++ it('goalStatusEnum / goalTypeEnum / goalCategoryEnum reject unknown values', () => {+ expect(goalStatusEnum.safeParse('paused').success).toBe(false);+ expect(goalTypeEnum.safeParse('mega').success).toBe(false);+ expect(goalCategoryEnum.safeParse('not-a-cat').success).toBe(false);+ });+ });++ describe('chronotypeBehavioralInputSchema', () => {+ it('accepts well-formed HH:MM values', () => {+ const r = chronotypeBehavioralInputSchema.safeParse({+ preferredWakeTime: '06:30',+ preferredSleepTime: '22:45',+ peakFocusStart: '09:00',+ peakFocusEnd: '11:30',+ caffeineLastIntake: '14:00'+ });+ expect(r.success).toBe(true);+ });++ it('accepts edge HH:MM values (00:00 and 23:59)', () => {+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '00:00' }).success).toBe(true);+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '23:59' }).success).toBe(true);+ });++ it('rejects out-of-range times', () => {+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '24:00' }).success).toBe(false);+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '12:60' }).success).toBe(false);+ });++ it('rejects bad formats', () => {+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '6:30' }).success).toBe(false);+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '06-30' }).success).toBe(false);+ expect(chronotypeBehavioralInputSchema.safeParse({ preferredWakeTime: '0630' }).success).toBe(false);+ });++ it('accepts an empty object (all fields optional)', () => {+ expect(chronotypeBehavioralInputSchema.safeParse({}).success).toBe(true);+ });+ });++ describe('birthDateInputSchema', () => {+ it('accepts a past calendar date', () => {+ expect(birthDateInputSchema.safeParse({ birthDate: '1990-05-15' }).success).toBe(true);+ });++ it('rejects future dates', () => {+ const future = new Date(Date.now() + 1000 * 60 * 60 * 24 * 365 * 5)+ .toISOString().slice(0, 10);+ const r = birthDateInputSchema.safeParse({ birthDate: future });+ expect(r.success).toBe(false);+ });++ it('rejects non-calendar dates like Feb 30', () => {+ expect(birthDateInputSchema.safeParse({ birthDate: '2020-02-30' }).success).toBe(false);+ });++ it('rejects bad formats', () => {+ expect(birthDateInputSchema.safeParse({ birthDate: '1990/05/15' }).success).toBe(false);+ expect(birthDateInputSchema.safeParse({ birthDate: '90-05-15' }).success).toBe(false);+ });+ });++ describe('createGoalInputSchema', () => {+ it('accepts a minimal goal and fills defaults', () => {+ const r = createGoalInputSchema.safeParse({ title: 'Learn jazz piano' });+ expect(r.success).toBe(true);+ expect(r.data.horizon).toBe('5-year');+ expect(r.data.category).toBe('mastery');+ expect(r.data.goalType).toBe('standard');+ expect(r.data.parentId).toBeNull();+ expect(r.data.tags).toEqual([]);+ });++ it('rejects an empty title', () => {+ expect(createGoalInputSchema.safeParse({ title: '' }).success).toBe(false);+ });++ it('rejects a title longer than 200 chars', () => {+ expect(createGoalInputSchema.safeParse({ title: 'a'.repeat(201) }).success).toBe(false);+ });++ it('caps tag count at 20', () => {+ const tags = Array.from({ length: 21 }, (_, i) => `tag-${i}`);+ expect(createGoalInputSchema.safeParse({ title: 'x', tags }).success).toBe(false);+ });++ it('accepts a fully-specified timeBlockConfig', () => {+ const r = createGoalInputSchema.safeParse({+ title: 'Practice',+ timeBlockConfig: {+ preferredDays: ['mon', 'wed', 'fri'],+ timeSlot: 'morning',+ sessionDurationMinutes: 60+ }+ });+ expect(r.success).toBe(true);+ });++ it('accepts HH:MM as timeSlot in timeBlockConfig', () => {+ const r = createGoalInputSchema.safeParse({+ title: 'Practice',+ timeBlockConfig: {+ preferredDays: ['mon'],+ timeSlot: '07:30',+ sessionDurationMinutes: 30+ }+ });+ expect(r.success).toBe(true);+ });++ it('rejects timeBlockConfig with bad sessionDuration', () => {+ const r = createGoalInputSchema.safeParse({+ title: 'Practice',+ timeBlockConfig: {+ preferredDays: ['mon'],+ timeSlot: 'morning',+ sessionDurationMinutes: 10+ }+ });+ expect(r.success).toBe(false);+ });+ });++ describe('updateGoalInputSchema', () => {+ it('accepts an empty patch', () => {+ expect(updateGoalInputSchema.safeParse({}).success).toBe(true);+ });++ it('accepts targetDate=null to clear', () => {+ expect(updateGoalInputSchema.safeParse({ targetDate: null }).success).toBe(true);+ });++ it('rejects bad status value', () => {+ expect(updateGoalInputSchema.safeParse({ status: 'paused' }).success).toBe(false);+ });+ });++ describe('addMilestoneInputSchema', () => {+ it('accepts title only', () => {+ expect(addMilestoneInputSchema.safeParse({ title: 'First demo' }).success).toBe(true);+ });++ it('rejects bad targetDate', () => {+ expect(addMilestoneInputSchema.safeParse({ title: 'x', targetDate: '2020-02-30' }).success).toBe(false);+ });+ });++ describe('aiProviderInputSchema', () => {+ it('accepts empty body', () => {+ expect(aiProviderInputSchema.safeParse({}).success).toBe(true);+ });++ it('rejects empty providerId / model strings', () => {+ expect(aiProviderInputSchema.safeParse({ providerId: '' }).success).toBe(false);+ expect(aiProviderInputSchema.safeParse({ model: '' }).success).toBe(false);+ });+ });++ describe('acceptPhasesInputSchema', () => {+ it('accepts a single well-formed phase', () => {+ const r = acceptPhasesInputSchema.safeParse({+ phases: [{ title: 'P1', description: 'desc', targetDate: '2030-01-01', order: 0 }]+ });+ expect(r.success).toBe(true);+ });++ it('defaults description to empty string', () => {+ const r = acceptPhasesInputSchema.safeParse({+ phases: [{ title: 'P1', targetDate: '2030-01-01', order: 0 }]+ });+ expect(r.success).toBe(true);+ expect(r.data.phases[0].description).toBe('');+ });++ it('rejects empty phases array', () => {+ expect(acceptPhasesInputSchema.safeParse({ phases: [] }).success).toBe(false);+ });++ it('caps phases at 20', () => {+ const phases = Array.from({ length: 21 }, (_, i) => ({+ title: `P${i}`, targetDate: '2030-01-01', order: i+ }));+ expect(acceptPhasesInputSchema.safeParse({ phases }).success).toBe(false);+ });+ });++ describe('addProgressEntrySchema', () => {+ it('accepts a minimal entry', () => {+ const r = addProgressEntrySchema.safeParse({ date: '2025-01-15', note: 'practiced scales' });+ expect(r.success).toBe(true);+ });++ it('rejects an empty note', () => {+ expect(addProgressEntrySchema.safeParse({ date: '2025-01-15', note: '' }).success).toBe(false);+ });++ it('caps duration at 1440 minutes', () => {+ expect(addProgressEntrySchema.safeParse({+ date: '2025-01-15', note: 'x', durationMinutes: 1441+ }).success).toBe(false);+ });+ });++ describe('addTodoInputSchema / updateTodoInputSchema', () => {+ it('addTodoInputSchema defaults priority to medium', () => {+ const r = addTodoInputSchema.safeParse({ title: 'Send email' });+ expect(r.success).toBe(true);+ expect(r.data.priority).toBe('medium');+ });++ it('rejects bad priority', () => {+ expect(addTodoInputSchema.safeParse({ title: 'x', priority: 'urgent' }).success).toBe(false);+ });++ it('updateTodoInputSchema accepts estimateMinutes=null to clear', () => {+ expect(updateTodoInputSchema.safeParse({ estimateMinutes: null }).success).toBe(true);+ });++ it('updateTodoInputSchema rejects bad status', () => {+ expect(updateTodoInputSchema.safeParse({ status: 'archived' }).success).toBe(false);+ });+ });++ describe('updateProgressSchema', () => {+ it('clamps progress to 0..100', () => {+ expect(updateProgressSchema.safeParse({ value: 0 }).success).toBe(true);+ expect(updateProgressSchema.safeParse({ value: 100 }).success).toBe(true);+ expect(updateProgressSchema.safeParse({ value: -1 }).success).toBe(false);+ expect(updateProgressSchema.safeParse({ value: 101 }).success).toBe(false);+ });+ });++ describe('linkActivityInputSchema / linkCalendarInputSchema', () => {+ it('linkActivity defaults note to empty', () => {+ const r = linkActivityInputSchema.safeParse({ activityName: 'jogging' });+ expect(r.success).toBe(true);+ expect(r.data.note).toBe('');+ });++ it('linkActivity rejects non-positive frequency', () => {+ expect(linkActivityInputSchema.safeParse({+ activityName: 'x', requiredFrequency: 0+ }).success).toBe(false);+ });++ it('linkCalendar defaults matchPattern to empty', () => {+ const r = linkCalendarInputSchema.safeParse({+ subcalendarId: 'cal1', subcalendarName: 'Health'+ });+ expect(r.success).toBe(true);+ expect(r.data.matchPattern).toBe('');+ });+ });++ describe('applyOrganizationInputSchema', () => {+ it('accepts a minimal organization patch', () => {+ const r = applyOrganizationInputSchema.safeParse({+ organization: [{ id: 'g1' }]+ });+ expect(r.success).toBe(true);+ });++ it('accepts null suggestedParentId to detach', () => {+ const r = applyOrganizationInputSchema.safeParse({+ organization: [{ id: 'g1', suggestedParentId: null }]+ });+ expect(r.success).toBe(true);+ });++ it('rejects an empty organization array', () => {+ expect(applyOrganizationInputSchema.safeParse({ organization: [] }).success).toBe(false);+ });+ });+});diff --git a/server/lib/mediaItemKey.test.js b/server/lib/mediaItemKey.test.jsnew file mode 100644index 0000000000..56ff82a6f7--- /dev/null+++ b/server/lib/mediaItemKey.test.js@@ -0,0 +1,102 @@+import { describe, it, expect } from 'vitest';+import {+ ITEM_KINDS,+ ITEM_KIND,+ REF_MAX_LENGTH,+ itemKey,+ parseKey,+ isValidKey+} from './mediaItemKey.js';++describe('mediaItemKey', () => {+ describe('exports', () => {+ it('exposes the same kinds in both array and set forms', () => {+ expect(ITEM_KINDS).toEqual(['image', 'video']);+ for (const k of ITEM_KINDS) expect(ITEM_KIND.has(k)).toBe(true);+ expect(ITEM_KIND.size).toBe(ITEM_KINDS.length);+ });++ it('caps refs at 256 chars', () => {+ expect(REF_MAX_LENGTH).toBe(256);+ });+ });++ describe('itemKey', () => {+ it('joins kind and ref with a colon', () => {+ expect(itemKey({ kind: 'image', ref: 'cover.png' })).toBe('image:cover.png');+ expect(itemKey({ kind: 'video', ref: 'abc123' })).toBe('video:abc123');+ });+ });++ describe('parseKey', () => {+ it('parses valid image keys', () => {+ expect(parseKey('image:cover.png')).toEqual({ kind: 'image', ref: 'cover.png' });+ });++ it('parses valid video keys', () => {+ expect(parseKey('video:abc123')).toEqual({ kind: 'video', ref: 'abc123' });+ });++ it('preserves dot-extensions and dashes in refs', () => {+ expect(parseKey('image:my-cover-v2.png')).toEqual({ kind: 'image', ref: 'my-cover-v2.png' });+ });++ it('rejects non-string inputs', () => {+ expect(parseKey(null)).toBeNull();+ expect(parseKey(undefined)).toBeNull();+ expect(parseKey(42)).toBeNull();+ expect(parseKey({})).toBeNull();+ });++ it('rejects keys missing a colon', () => {+ expect(parseKey('imageNoColon')).toBeNull();+ });++ it('rejects keys with an empty kind (leading colon)', () => {+ expect(parseKey(':orphan-ref')).toBeNull();+ });++ it('rejects unknown kinds', () => {+ expect(parseKey('audio:foo.wav')).toBeNull();+ expect(parseKey('Image:cover.png')).toBeNull(); // case-sensitive+ });++ it('rejects refs that contain a colon (ambiguous in REST surface)', () => {+ expect(parseKey('image:foo:bar')).toBeNull();+ });++ it('rejects empty refs', () => {+ expect(parseKey('image:')).toBeNull();+ });++ it('accepts refs at the max length', () => {+ const ref = 'a'.repeat(REF_MAX_LENGTH);+ expect(parseKey(`image:${ref}`)).toEqual({ kind: 'image', ref });+ });++ it('rejects refs over the max length', () => {+ const ref = 'a'.repeat(REF_MAX_LENGTH + 1);+ expect(parseKey(`image:${ref}`)).toBeNull();+ });+ });++ describe('isValidKey', () => {+ it('returns true for valid keys', () => {+ expect(isValidKey('image:cover.png')).toBe(true);+ expect(isValidKey('video:xyz')).toBe(true);+ });++ it('returns false for invalid keys', () => {+ expect(isValidKey('audio:bar')).toBe(false);+ expect(isValidKey('image:')).toBe(false);+ expect(isValidKey(null)).toBe(false);+ });++ it('round-trips through itemKey', () => {+ const it = { kind: 'video', ref: 'abc' };+ const key = itemKey(it);+ expect(isValidKey(key)).toBe(true);+ expect(parseKey(key)).toEqual(it);+ });+ });+});diff --git a/server/lib/pipelineIssueOrder.test.js b/server/lib/pipelineIssueOrder.test.jsnew file mode 100644index 0000000000..72253de098--- /dev/null+++ b/server/lib/pipelineIssueOrder.test.js@@ -0,0 +1,172 @@+import { describe, it, expect } from 'vitest';+import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from './pipelineIssueOrder.js';++const mkIssue = (over = {}) => ({+ id: over.id || `i${Math.random().toString(36).slice(2, 7)}`,+ seriesId: 's1',+ seasonId: over.seasonId ?? null,+ arcPosition: over.arcPosition ?? 1,+ createdAt: over.createdAt || '2024-01-01T00:00:00Z',+ number: over.number ?? 0,+ ...over+});++describe('applyVolumeOrderedNumbers', () => {+ it('numbers issues volume-by-volume in season order', () => {+ const seasons = [+ { id: 'v1', number: 1 },+ { id: 'v2', number: 2 }+ ];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v2', arcPosition: 1 }),+ mkIssue({ id: 'b', seasonId: 'v1', arcPosition: 2 }),+ mkIssue({ id: 'c', seasonId: 'v1', arcPosition: 1 })+ ];++ const changed = applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons });++ expect(changed).toBe(true);+ expect(issues.find(i => i.id === 'c').number).toBe(1);+ expect(issues.find(i => i.id === 'b').number).toBe(2);+ expect(issues.find(i => i.id === 'a').number).toBe(3);+ });++ it('sorts within a volume by arcPosition then createdAt', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1, createdAt: '2024-03-01T00:00:00Z' }),+ mkIssue({ id: 'b', seasonId: 'v1', arcPosition: 1, createdAt: '2024-01-01T00:00:00Z' }),+ mkIssue({ id: 'c', seasonId: 'v1', arcPosition: 0, createdAt: '2024-06-01T00:00:00Z' })+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons });+ // arcPosition 0 first; then arcPosition 1 sorted by createdAt+ expect(issues.find(i => i.id === 'c').number).toBe(1);+ expect(issues.find(i => i.id === 'b').number).toBe(2);+ expect(issues.find(i => i.id === 'a').number).toBe(3);+ });++ it('appends unscoped issues after volume issues, ordered by createdAt', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1 }),+ mkIssue({ id: 'u2', seasonId: null, createdAt: '2024-02-01T00:00:00Z' }),+ mkIssue({ id: 'u1', seasonId: null, createdAt: '2024-01-01T00:00:00Z' })+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons });+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'u1').number).toBe(2);+ expect(issues.find(i => i.id === 'u2').number).toBe(3);+ });++ it('treats issues with a stale seasonId as unscoped', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1 }),+ mkIssue({ id: 'b', seasonId: 'v-gone', createdAt: '2024-01-01T00:00:00Z' })+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons });+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'b').number).toBe(2);+ });++ it('skips issues that belong to other series', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1 }),+ { id: 'x', seriesId: 'other', seasonId: 'v1', arcPosition: 1, createdAt: '', number: 99 }+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons });+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ // Other-series issue is untouched+ expect(issues.find(i => i.id === 'x').number).toBe(99);+ });++ it('returns false when no numbers change', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1, number: 1 }),+ mkIssue({ id: 'b', seasonId: 'v1', arcPosition: 2, number: 2 })+ ];+ const changed = applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons });+ expect(changed).toBe(false);+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'b').number).toBe(2);+ });++ describe('fromSeasonId anchor', () => {+ it('with null anchor, renumbers the whole series', () => {+ const seasons = [+ { id: 'v1', number: 1 },+ { id: 'v2', number: 2 }+ ];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1, number: 9 }),+ mkIssue({ id: 'b', seasonId: 'v2', arcPosition: 1, number: 9 })+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons, fromSeasonId: null });+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'b').number).toBe(2);+ });++ it('preserves earlier-volume numbers when anchor is on a later volume', () => {+ const seasons = [+ { id: 'v1', number: 1 },+ { id: 'v2', number: 2 }+ ];+ const issues = [+ // V1 already at #1 and #2 — must stay there even though we renumber from V2+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1, number: 1 }),+ mkIssue({ id: 'b', seasonId: 'v1', arcPosition: 2, number: 2 }),+ mkIssue({ id: 'c', seasonId: 'v2', arcPosition: 1, number: 0 })+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons, fromSeasonId: 'v2' });+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'b').number).toBe(2);+ // Counter resumed from max(pre-anchor) + 1 = 3+ expect(issues.find(i => i.id === 'c').number).toBe(3);+ });++ it('UNSCOPED_ANCHOR only renumbers the trailing unscoped tail', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1, number: 1 }),+ mkIssue({ id: 'u', seasonId: null, number: 0, createdAt: '2024-01-01T00:00:00Z' })+ ];+ applyVolumeOrderedNumbers({+ issues,+ seriesId: 's1',+ seasons,+ fromSeasonId: UNSCOPED_ANCHOR+ });+ // V1 untouched, only unscoped gets re-numbered after the seeded counter+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'u').number).toBe(2);+ });++ it('treats a stale (unknown) fromSeasonId as UNSCOPED_ANCHOR', () => {+ const seasons = [{ id: 'v1', number: 1 }];+ const issues = [+ mkIssue({ id: 'a', seasonId: 'v1', arcPosition: 1, number: 1 }),+ mkIssue({ id: 'u', seasonId: null, number: 0, createdAt: '2024-01-01T00:00:00Z' })+ ];+ applyVolumeOrderedNumbers({+ issues,+ seriesId: 's1',+ seasons,+ fromSeasonId: 'stale-id-that-does-not-exist'+ });+ expect(issues.find(i => i.id === 'a').number).toBe(1);+ expect(issues.find(i => i.id === 'u').number).toBe(2);+ });+ });++ it('handles an empty seasons list with only unscoped issues', () => {+ const issues = [+ mkIssue({ id: 'u1', seasonId: null, createdAt: '2024-01-01T00:00:00Z' }),+ mkIssue({ id: 'u2', seasonId: null, createdAt: '2024-02-01T00:00:00Z' })+ ];+ applyVolumeOrderedNumbers({ issues, seriesId: 's1', seasons: [] });+ expect(issues.find(i => i.id === 'u1').number).toBe(1);+ expect(issues.find(i => i.id === 'u2').number).toBe(2);+ });+});diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.jsnew file mode 100644index 0000000000..a09b9a0fa9--- /dev/null+++ b/server/lib/providerModels.test.js@@ -0,0 +1,153 @@+import { describe, it, expect } from 'vitest';+import {+ CODEX_CONFIGURED_DEFAULT,+ isCodexConfiguredDefault,+ resolveCliModel,+ filterSelectableModels,+ hasModelFlag,+ extractBakedModel+} from './providerModels.js';++describe('providerModels', () => {+ describe('isCodexConfiguredDefault', () => {+ it('matches the sentinel exactly', () => {+ expect(isCodexConfiguredDefault(CODEX_CONFIGURED_DEFAULT)).toBe(true);+ expect(isCodexConfiguredDefault('codex-configured-default')).toBe(true);+ });++ it('rejects everything else', () => {+ expect(isCodexConfiguredDefault('gpt-5')).toBe(false);+ expect(isCodexConfiguredDefault('')).toBe(false);+ expect(isCodexConfiguredDefault(null)).toBe(false);+ expect(isCodexConfiguredDefault(undefined)).toBe(false);+ });+ });++ describe('resolveCliModel', () => {+ it('returns null for the codex sentinel so --model is omitted', () => {+ expect(resolveCliModel(CODEX_CONFIGURED_DEFAULT)).toBeNull();+ });++ it('returns null for empty / nullish values', () => {+ expect(resolveCliModel(null)).toBeNull();+ expect(resolveCliModel(undefined)).toBeNull();+ expect(resolveCliModel('')).toBeNull();+ });++ it('returns the model string when concrete', () => {+ expect(resolveCliModel('gpt-5')).toBe('gpt-5');+ expect(resolveCliModel('claude-opus-4-7')).toBe('claude-opus-4-7');+ });+ });++ describe('filterSelectableModels', () => {+ it('strips the codex sentinel from the list', () => {+ expect(filterSelectableModels(['a', CODEX_CONFIGURED_DEFAULT, 'b'])).toEqual(['a', 'b']);+ });++ it('returns an empty list for nullish input', () => {+ expect(filterSelectableModels(null)).toEqual([]);+ expect(filterSelectableModels(undefined)).toEqual([]);+ });++ it('passes a sentinel-free list through unchanged', () => {+ expect(filterSelectableModels(['a', 'b'])).toEqual(['a', 'b']);+ });+ });++ describe('hasModelFlag', () => {+ it('detects --model with separated value', () => {+ expect(hasModelFlag(['--model', 'gpt-5'])).toBe(true);+ });++ it('detects -m with separated value', () => {+ expect(hasModelFlag(['-m', 'gpt-5'])).toBe(true);+ });++ it('detects joined --model=value', () => {+ expect(hasModelFlag(['--model=gpt-5'])).toBe(true);+ });++ it('detects joined -m=value', () => {+ expect(hasModelFlag(['-m=gpt-5'])).toBe(true);+ });++ it('returns false for separated flag at end of argv', () => {+ expect(hasModelFlag(['--foo', '--model'])).toBe(false);+ });++ it('returns false when separated --model is followed by another flag', () => {+ expect(hasModelFlag(['--model', '--other'])).toBe(false);+ });++ it('returns false for joined form with no value (`--model=`)', () => {+ expect(hasModelFlag(['--model='])).toBe(false);+ expect(hasModelFlag(['-m='])).toBe(false);+ });++ it('returns false for unrelated argv', () => {+ expect(hasModelFlag(['--verbose', 'exec', '-'])).toBe(false);+ expect(hasModelFlag([])).toBe(false);+ });++ it('returns false for non-array input', () => {+ expect(hasModelFlag(null)).toBe(false);+ expect(hasModelFlag('not-an-array')).toBe(false);+ });+ });++ describe('extractBakedModel', () => {+ it('extracts from separated --model form', () => {+ expect(extractBakedModel(['--model', 'gpt-5'])).toBe('gpt-5');+ });++ it('extracts from separated -m form', () => {+ expect(extractBakedModel(['-m', 'gpt-5'])).toBe('gpt-5');+ });++ it('extracts from joined --model=value form', () => {+ expect(extractBakedModel(['--model=gpt-5'])).toBe('gpt-5');+ });++ it('extracts from joined -m=value form', () => {+ expect(extractBakedModel(['-m=gpt-5'])).toBe('gpt-5');+ });++ it('returns null when separated form has no value', () => {+ expect(extractBakedModel(['--model'])).toBeNull();+ expect(extractBakedModel(['--model', '--other'])).toBeNull();+ });++ it('returns null when joined form has empty value', () => {+ expect(extractBakedModel(['--model='])).toBeNull();+ expect(extractBakedModel(['-m='])).toBeNull();+ });++ it('returns null when no model flag is present', () => {+ expect(extractBakedModel(['--verbose', 'exec'])).toBeNull();+ expect(extractBakedModel([])).toBeNull();+ });++ it('returns null for non-array input', () => {+ expect(extractBakedModel(null)).toBeNull();+ expect(extractBakedModel(undefined)).toBeNull();+ });+ });++ it('hasModelFlag and extractBakedModel stay consistent on common shapes', () => {+ const shapes = [+ ['--model', 'gpt-5'],+ ['-m', 'gpt-5'],+ ['--model=gpt-5'],+ ['-m=gpt-5'],+ ['--model'],+ ['--model=']+ ];+ for (const args of shapes) {+ const has = hasModelFlag(args);+ const baked = extractBakedModel(args);+ // If hasModelFlag says yes, extractBakedModel must produce a non-null value.+ if (has) expect(baked, `args=${JSON.stringify(args)}`).not.toBeNull();+ }+ });+});diff --git a/server/lib/writersRoomStylePresets.test.js b/server/lib/writersRoomStylePresets.test.jsnew file mode 100644index 0000000000..8452792288--- /dev/null+++ b/server/lib/writersRoomStylePresets.test.js@@ -0,0 +1,104 @@+import { describe, it, expect } from 'vitest';+import {+ STYLE_PRESETS,+ STYLE_PRESET_IDS,+ STYLE_ID,+ ALL_STYLE_IDS,+ EMPTY_IMAGE_STYLE,+ getStylePresetById,+ findStylePreset+} from './writersRoomStylePresets.js';++describe('writersRoomStylePresets', () => {+ describe('STYLE_PRESETS catalog', () => {+ it('exposes a non-empty preset list', () => {+ expect(Array.isArray(STYLE_PRESETS)).toBe(true);+ expect(STYLE_PRESETS.length).toBeGreaterThan(0);+ });++ it('every preset has the required fields', () => {+ for (const p of STYLE_PRESETS) {+ expect(typeof p.id).toBe('string');+ expect(p.id.length).toBeGreaterThan(0);+ expect(typeof p.label).toBe('string');+ expect(p.label.length).toBeGreaterThan(0);+ expect(typeof p.category).toBe('string');+ expect(p.category.length).toBeGreaterThan(0);+ expect(typeof p.prompt).toBe('string');+ expect(p.prompt.length).toBeGreaterThan(0);+ expect(typeof p.negativePrompt).toBe('string');+ }+ });++ it('preset ids are unique (the cache map relies on this)', () => {+ const seen = new Set();+ for (const p of STYLE_PRESETS) {+ expect(seen.has(p.id), `duplicate preset id: ${p.id}`).toBe(false);+ seen.add(p.id);+ }+ });++ it('STYLE_PRESET_IDS mirrors the preset id list in order', () => {+ expect(STYLE_PRESET_IDS).toEqual(STYLE_PRESETS.map(p => p.id));+ });+ });++ describe('STYLE_ID sentinels', () => {+ it('exposes none/custom sentinels', () => {+ expect(STYLE_ID.NONE).toBe('none');+ expect(STYLE_ID.CUSTOM).toBe('custom');+ });++ it('ALL_STYLE_IDS prefixes sentinels then preset ids', () => {+ expect(ALL_STYLE_IDS[0]).toBe(STYLE_ID.NONE);+ expect(ALL_STYLE_IDS[1]).toBe(STYLE_ID.CUSTOM);+ expect(ALL_STYLE_IDS.slice(2)).toEqual(STYLE_PRESET_IDS);+ });++ it('EMPTY_IMAGE_STYLE is the none-preset zero-value', () => {+ expect(EMPTY_IMAGE_STYLE).toEqual({+ presetId: STYLE_ID.NONE,+ prompt: '',+ negativePrompt: ''+ });+ });+ });++ describe('getStylePresetById', () => {+ it('returns the matching preset', () => {+ const cinematic = getStylePresetById('cinematic');+ expect(cinematic).toBeDefined();+ expect(cinematic.id).toBe('cinematic');+ expect(cinematic.label).toBe('Cinematic');+ });++ it('returns null for unknown ids', () => {+ expect(getStylePresetById('this-id-does-not-exist')).toBeNull();+ });++ it('returns null for nullish / non-string input', () => {+ expect(getStylePresetById(null)).toBeNull();+ expect(getStylePresetById(undefined)).toBeNull();+ expect(getStylePresetById('')).toBeNull();+ expect(getStylePresetById(42)).toBeNull();+ });+ });++ describe('findStylePreset', () => {+ it('returns the matching preset', () => {+ const noir = findStylePreset('noir');+ expect(noir).toBeDefined();+ expect(noir.id).toBe('noir');+ });++ it('returns null for unknown ids', () => {+ expect(findStylePreset('not-a-real-style')).toBeNull();+ });++ it('agrees with getStylePresetById for every known id', () => {+ for (const id of STYLE_PRESET_IDS) {+ expect(findStylePreset(id)).toBe(getStylePresetById(id));+ }+ });+ });+});