diff --git a/apps/server/src/modules/ai-dm/ai-dm.module.ts b/apps/server/src/modules/ai-dm/ai-dm.module.ts index 768276356..8046df8cd 100644 --- a/apps/server/src/modules/ai-dm/ai-dm.module.ts +++ b/apps/server/src/modules/ai-dm/ai-dm.module.ts @@ -7,6 +7,7 @@ import { ProposalRecordsModule } from '../proposals/proposal-records.module'; import { AiPricingModule } from '../ai-pricing/ai-pricing.module'; import { SessionZeroModule } from '../session-zero/session-zero.module'; import { StorylinesModule } from '../storylines/storylines.module'; +import { TimelineModule } from '../timeline/timeline.module'; import { AiDmService } from './ai-dm.service'; import { AiDmController } from './ai-dm.controller'; import { CoDmService } from './co-dm.service'; @@ -30,6 +31,7 @@ import { AI_DM_PROVIDER, NoopAiDmProvider } from './ai-dm.provider'; ProposalRecordsModule, SessionZeroModule, StorylinesModule, + TimelineModule, AiPricingModule, ], controllers: [AiDmController, CoDmController], diff --git a/apps/server/src/modules/ai-dm/co-dm.service.ts b/apps/server/src/modules/ai-dm/co-dm.service.ts index 06aa86425..c49f67153 100644 --- a/apps/server/src/modules/ai-dm/co-dm.service.ts +++ b/apps/server/src/modules/ai-dm/co-dm.service.ts @@ -23,6 +23,8 @@ import { StoryBeatProposalCreate, StoryBeatUpdate, StoryArcUpdate, + TimelineEventCreate, + TimelineEventUpdate, ruleSystemAdapter, } from '@campfire/schema'; import type { AiExternalContentPolicy, AiGenerationProvenance, CoDmDraftRequest, CoDmDraftResult, CoDmDraftTarget, HomebrewMechanicsProfile, NarrationLanguage, Proposal, Role, RuleSystemAdapter } from '@campfire/schema'; @@ -42,6 +44,7 @@ import { isWithheldFinishReason, describeWithheldTurn } from '../ai-driver/drive import { AiProviderConfigService } from '../ai-provider-config/ai-provider-config.service'; import { provenanceEndpointBaseUrl, resolveAiProvenanceEgress } from '../../common/ai-provenance-endpoint'; import { StorylinesService } from '../storylines/storylines.service'; +import { TimelineService, toEventDomain } from '../timeline/timeline.service'; type CoDmDraftRequestInput = z.infer; @@ -62,10 +65,11 @@ const TARGET_ENTITY_TYPE: Record = { recap: 'session', // a session recap is filed as a session encounter: 'encounter', map: 'map', + timeline_event: 'timeline_event', }; /** Targets that support drafting N items at once; the rest ignore `count`. */ -const MULTI_TARGETS = new Set(['npc', 'location', 'beat', 'quest', 'faction']); +const MULTI_TARGETS = new Set(['npc', 'location', 'beat', 'quest', 'faction', 'timeline_event']); /** * Co-DM authoring (issue #313) — the AI drafts content for the DM's approval queue. @@ -103,6 +107,7 @@ export class CoDmService { @Inject(AI_DM_PROVIDER) private readonly provider: AiDmProvider, private readonly providerConfig: AiProviderConfigService, private readonly storylines: StorylinesService, + private readonly timelineService: TimelineService, ) {} /** 403 unless the server-wide experimental flag is on — the same choke point as the AI DM seat. */ @@ -133,8 +138,8 @@ export class CoDmService { if (input.target === 'arc' && !editing) { throw new BadRequestException('Story arcs can be rewritten with entityId; creating arcs with co-DM drafting is not supported'); } - if (editing && input.target !== 'arc' && input.target !== 'beat') { - throw new BadRequestException('entityId is supported only when rewriting an existing story arc or beat'); + if (editing && input.target !== 'arc' && input.target !== 'beat' && input.target !== 'timeline_event') { + throw new BadRequestException('entityId is supported only when rewriting an existing story arc, beat, or timeline event'); } if (editing && (input.arcId != null || input.count != null)) { throw new BadRequestException('arcId and count are not used when rewriting an existing storyline entity'); @@ -153,7 +158,9 @@ export class CoDmService { ); } const edit = editing - ? await this.storylines.getRewriteContext(campaignId, input.target as 'arc' | 'beat', input.entityId!) + ? (input.target === 'timeline_event' + ? await this.getTimelineRewriteContext(campaignId, input.entityId!) + : await this.storylines.getRewriteContext(campaignId, input.target as 'arc' | 'beat', input.entityId!)) : null; const providerPrompt = edit ? JSON.stringify({ rewriteInstructions: input.prompt, currentStoryline: edit.providerContext }) @@ -573,7 +580,8 @@ export class CoDmService { case 'arc': case 'beat': case 'quest': - case 'faction': { + case 'faction': + case 'timeline_event': { if (parsed === null) { throw new UnprocessableEntityException( `The AI did not return a JSON ${target} draft. Configure a real provider (the default no-op scaffold cannot author content) or retry.`, @@ -649,6 +657,27 @@ export class CoDmService { ...(typeof raw.standing === 'string' ? { standing: raw.standing } : {}), ...(typeof raw.dmSecret === 'string' ? { dmSecret: raw.dmSecret } : {}), }) as Record; + case 'timeline_event': + if (opts?.editing) { + return TimelineEventUpdate.parse({ + ...(typeof raw.title === 'string' ? { title: raw.title } : {}), + ...(typeof raw.inWorldDate === 'string' ? { inWorldDate: raw.inWorldDate } : {}), + ...(typeof raw.era === 'string' ? { era: raw.era } : {}), + ...(typeof raw.sortIndex === 'number' || typeof raw.sortIndex === 'string' ? { sortIndex: Number(raw.sortIndex) } : {}), + ...(typeof raw.body === 'string' ? { body: raw.body } : {}), + ...(typeof raw.dmSecret === 'string' ? { dmSecret: raw.dmSecret } : {}), + ...(typeof raw.hidden === 'boolean' ? { hidden: raw.hidden } : {}), + }) as Record; + } + return TimelineEventCreate.parse({ + title: typeof raw.title === 'string' && raw.title.trim() ? raw.title : (typeof raw.name === 'string' && raw.name.trim() ? raw.name : 'Untitled event'), + ...(typeof raw.inWorldDate === 'string' ? { inWorldDate: raw.inWorldDate } : {}), + ...(typeof raw.era === 'string' ? { era: raw.era } : {}), + ...(typeof raw.sortIndex === 'number' || typeof raw.sortIndex === 'string' ? { sortIndex: Number(raw.sortIndex) } : {}), + ...(typeof raw.body === 'string' ? { body: raw.body } : {}), + ...(typeof raw.dmSecret === 'string' ? { dmSecret: raw.dmSecret } : {}), + ...(typeof raw.hidden === 'boolean' ? { hidden: raw.hidden } : {}), + }) as Record; case 'recap': return SessionCreate.parse(raw) as Record; case 'encounter': { @@ -683,6 +712,32 @@ export class CoDmService { ); } } + + private async getTimelineRewriteContext(campaignId: number, eventId: number) { + const row = await this.timelineService.getEventRowOrThrow(eventId); + if (row.campaignId !== campaignId) { + throw new BadRequestException(`Timeline event ${eventId} does not belong to this campaign`); + } + const domain = toEventDomain(row); + const providerContext = { + target: 'timeline_event' as const, + event: { + id: domain.id, + title: domain.title, + inWorldDate: domain.inWorldDate, + era: domain.era, + sortIndex: domain.sortIndex, + body: domain.body, + dmSecret: domain.dmSecret, + }, + }; + const contextHash = crypto.createHash('sha256').update(JSON.stringify(providerContext)).digest('hex'); + return { + providerContext, + contextHash, + baseSnapshot: { ...domain }, + }; + } } /** Per-target JSON hint the model is asked to fill (informational; the server re-validates). */ @@ -696,6 +751,8 @@ const DRAFT_JSON_SHAPE = (adapter: RuleSystemAdapter): Record { diff --git a/apps/server/src/modules/proposals/proposal-records.service.ts b/apps/server/src/modules/proposals/proposal-records.service.ts index d4e61f82a..70ead38c2 100644 --- a/apps/server/src/modules/proposals/proposal-records.service.ts +++ b/apps/server/src/modules/proposals/proposal-records.service.ts @@ -3,7 +3,7 @@ import { and, desc, eq, isNull } from 'drizzle-orm'; import { AiGenerationProvenance } from '@campfire/schema'; import type { EntityType, Proposal, ProposalAction, Role } from '@campfire/schema'; import { DB, type DrizzleDb } from '../../db/db.module'; -import { proposals, quests, npcs, locations, sessions, characters, factions, storyArcs, storyBeats, auditLog, ruleEntries } from '../../db/schema'; +import { proposals, quests, npcs, locations, sessions, characters, factions, storyArcs, storyBeats, auditLog, ruleEntries, timelineEvents } from '../../db/schema'; import { nowIso } from '../../common/time'; import { fromJsonText, toJsonText } from '../../common/json'; import { notDeleted } from '../../common/soft-delete'; @@ -20,6 +20,7 @@ import { toDomain as npcToDomain } from '../npcs/npcs.service'; import { toDomain as locationToDomain } from '../locations/locations.service'; import { toDomain as sessionToDomain } from '../sessions/sessions.service'; import { toDomain as characterToDomain } from '../characters/characters.service'; +import { toEventDomain as timelineEventToDomain } from '../timeline/timeline.service'; import { projectProposal, projectProposals } from './proposal-projection'; import { hashProposalSnapshot } from './proposal-snapshot'; @@ -32,7 +33,7 @@ import { hashProposalSnapshot } from './proposal-snapshot'; // standalone rather than derived from EntityType. Factions (issue #1056) are also // proposable for Co-DM drafting and are create-only in v1 (direct faction writes remain // DM-gated; the proposal queue is the co-DM intermediary). -export type ProposableEntityType = Exclude | 'map' | 'story_arc' | 'story_beat' | 'rule_entry'; +export type ProposableEntityType = Exclude | 'map' | 'story_arc' | 'story_beat' | 'timeline_event' | 'rule_entry'; type ProposalTx = Parameters[0]>[0]; type ProposalDb = DrizzleDb | ProposalTx; type ProposalAttribution = { @@ -42,7 +43,7 @@ type ProposalAttribution = { generationProvenance?: AiGenerationProvenance | null; }; -const PROPOSABLE_ENTITY_TYPES: ProposableEntityType[] = ['quest', 'npc', 'location', 'session', 'character', 'encounter', 'map', 'faction', 'story_arc', 'story_beat', 'rule_entry']; +const PROPOSABLE_ENTITY_TYPES: ProposableEntityType[] = ['quest', 'npc', 'location', 'session', 'character', 'encounter', 'map', 'faction', 'story_arc', 'story_beat', 'timeline_event', 'rule_entry']; export function isProposableEntityType(value: string): value is ProposableEntityType { return (PROPOSABLE_ENTITY_TYPES as string[]).includes(value); @@ -447,6 +448,17 @@ export class ProposalRecordsService { if (!row) throw new NotFoundException(`Homebrew rule entry ${entityId} not found`); return { id: row.id, slug: row.slug, name: row.name, type: row.type, summary: row.summary, body: row.body, dataJson: row.dataJson, rightsStatus: row.rightsStatus, license: row.license, attribution: row.attribution, author: row.author, sourceUrl: row.sourceUrl, iconSlug: row.iconSlug, updatedAt: row.updatedAt, archivedAt: row.archivedAt }; } + case 'timeline_event': { + const [row] = await this.db + .select() + .from(timelineEvents) + .where(and(eq(timelineEvents.id, entityId), eq(timelineEvents.campaignId, campaignId), notDeleted(timelineEvents.deletedAt))) + .limit(1); + if (!row) throw new NotFoundException(`Timeline event ${entityId} not found`); + const domain = timelineEventToDomain(row); + if (!isVisibleTo(domain, role)) throw new NotFoundException(`Timeline event ${entityId} not found`); + return { ...domain }; + } } } @@ -597,6 +609,18 @@ export class ProposalRecordsService { archivedAt: row.archivedAt, }; } + case 'timeline_event': { + const row = db + .select() + .from(timelineEvents) + .where(and(eq(timelineEvents.id, entityId), eq(timelineEvents.campaignId, campaignId), notDeleted(timelineEvents.deletedAt))) + .limit(1) + .get(); + if (!row) throw new NotFoundException(`Timeline event ${entityId} not found`); + const domain = timelineEventToDomain(row); + if (!isVisibleTo(domain, role)) throw new NotFoundException(`Timeline event ${entityId} not found`); + return { ...domain }; + } } } diff --git a/apps/server/src/modules/proposals/proposals.module.ts b/apps/server/src/modules/proposals/proposals.module.ts index 7f10967e3..717f892d9 100644 --- a/apps/server/src/modules/proposals/proposals.module.ts +++ b/apps/server/src/modules/proposals/proposals.module.ts @@ -12,6 +12,7 @@ import { MapsModule } from '../maps/maps.module'; import { FactionsModule } from '../factions/factions.module'; import { StorylinesModule } from '../storylines/storylines.module'; import { RulesModule } from '../rules/rules.module'; +import { TimelineModule } from '../timeline/timeline.module'; import { ProposalRecordsModule } from './proposal-records.module'; import { ProposalsService } from './proposals.service'; import { CampaignProposalsController, ProposalsController } from './proposals.controller'; @@ -32,6 +33,7 @@ import { CampaignProposalsController, ProposalsController } from './proposals.co FactionsModule, StorylinesModule, RulesModule, + TimelineModule, ], controllers: [CampaignProposalsController, ProposalsController], providers: [ProposalsService], diff --git a/apps/server/src/modules/proposals/proposals.service.ts b/apps/server/src/modules/proposals/proposals.service.ts index 3caf7e476..e47a6337e 100644 --- a/apps/server/src/modules/proposals/proposals.service.ts +++ b/apps/server/src/modules/proposals/proposals.service.ts @@ -24,6 +24,8 @@ import { ProposalResolve, HomebrewRuleEntryInput, HomebrewRuleEntryUpdate, + TimelineEventCreate, + TimelineEventUpdate, } from '@campfire/schema'; import type { Proposal, ProposalAction, Role } from '@campfire/schema'; import { fromJsonText } from '../../common/json'; @@ -38,6 +40,7 @@ import { SessionsService } from '../sessions/sessions.service'; import { CharactersService } from '../characters/characters.service'; import { EncountersService } from '../encounters/encounters.service'; import { MapsService } from '../maps/maps.service'; +import { TimelineService } from '../timeline/timeline.service'; import { FactionsService } from '../factions/factions.service'; import { StorylineRewriteContextChangedError, @@ -109,6 +112,7 @@ const CREATE_SCHEMAS: Record = { encounter: EncounterGenerate.strict(), map: GenerateMapParams.strict(), rule_entry: HomebrewRuleEntryInput, + timeline_event: TimelineEventCreate.strict(), }; const UPDATE_SCHEMAS: Record = { quest: QuestUpdate.strict(), @@ -122,6 +126,7 @@ const UPDATE_SCHEMAS: Record = { encounter: EncounterGenerate.strict(), map: GenerateMapParams.strict(), rule_entry: HomebrewRuleEntryUpdate.strict(), + timeline_event: TimelineEventUpdate.strict(), }; @Injectable() @@ -139,6 +144,7 @@ export class ProposalsService { private readonly maps: MapsService, private readonly factions: FactionsService, @Inject(StorylinesService) private readonly storylines: ProposalStorylinesService, + private readonly timeline: TimelineService, private readonly rules?: RulesService, ) {} @@ -318,6 +324,31 @@ export class ProposalsService { update: (id: number, payload: Record, user: RequestUser) => this.rules!.updateCampaignHomebrewFromProposal(id, payload, user), remove: () => Promise.reject(new BadRequestException('Homebrew archive proposals are not supported yet')), }; + case 'timeline_event': + return { + create: (campaignId: number, payload: Record, user: RequestUser, role: Role) => + this.timeline.createEvent( + campaignId, + payload as Parameters[1], + user, + role, + ), + update: ( + id: number, + payload: Record, + user: RequestUser, + role: Role, + opts?: Parameters[4], + ) => + this.timeline.updateEvent( + id, + payload as Parameters[1], + user, + role, + opts, + ), + remove: (id: number, user: RequestUser, role: Role) => this.timeline.removeEvent(id, user, role), + }; } } diff --git a/apps/server/test/co-dm.e2e-spec.ts b/apps/server/test/co-dm.e2e-spec.ts index b7655865c..0217b6764 100644 --- a/apps/server/test/co-dm.e2e-spec.ts +++ b/apps/server/test/co-dm.e2e-spec.ts @@ -107,6 +107,79 @@ describe('co-DM authoring — draft → proposal → approve (e2e)', () => { expect(recap.body.proposals[0].payload.recap).toContain('crossed the moor'); }); + it('drafts a timeline event as a pending proposal and approving it creates the timeline event', async () => { + h.script({ + text: JSON.stringify({ + title: 'Fall of Netheril', + inWorldDate: 'Year -339 DR', + era: 'Ancient Era', + body: 'Floating cities crash during Karsus’s Folly.', + }), + }); + const res = await draft({ target: 'timeline_event', prompt: 'an ancient catastrophe' }); + expect(res.status).toBe(201); + expect(res.body.target).toBe('timeline_event'); + expect(res.body.entityType).toBe('timeline_event'); + expect(res.body.proposalIds).toHaveLength(1); + + const proposal = res.body.proposals[0]; + expect(proposal.status).toBe('pending'); + expect(proposal.action).toBe('create'); + expect(proposal.payload.title).toBe('Fall of Netheril'); + expect(proposal.payload.inWorldDate).toBe('Year -339 DR'); + + const approve = await request(h.server).post(`/api/v1/proposals/${proposal.id}/approve`).set(dm).send({}); + expect(approve.status).toBe(201); + expect(approve.body.status).toBe('approved'); + expect(approve.body.entityId).toBeGreaterThan(0); + + const event = await request(h.server).get(`/api/v1/timeline/${approve.body.entityId}`).set(dm); + expect(event.status).toBe(200); + expect(event.body.title).toBe('Fall of Netheril'); + expect(event.body.era).toBe('Ancient Era'); + }); + + it('rewrites an existing timeline event with entityId and files an update proposal', async () => { + // Create an event manually first + const created = await request(h.server).post(`/api/v1/campaigns/${campaignId}/timeline`).set(dm).send({ + title: 'Battle of Red Valley', + inWorldDate: '1490 DR', + body: 'Minor skirmish.', + }); + expect(created.status).toBe(201); + const eventId = created.body.id; + + h.script({ + text: JSON.stringify({ + title: 'The Great Battle of Red Valley', + body: 'Decisive victory for the alliance forces.', + }), + }); + const res = await draft({ + target: 'timeline_event', + prompt: 'make the battle epic and detail the outcome', + entityId: eventId, + includeCampaignSecrets: true, + }); + expect(res.status).toBe(201); + expect(res.body.target).toBe('timeline_event'); + expect(res.body.entityType).toBe('timeline_event'); + + const proposal = res.body.proposals[0]; + expect(proposal.status).toBe('pending'); + expect(proposal.action).toBe('update'); + expect(proposal.entityId).toBe(eventId); + expect(proposal.payload.title).toBe('The Great Battle of Red Valley'); + + const approve = await request(h.server).post(`/api/v1/proposals/${proposal.id}/approve`).set(dm).send({}); + expect(approve.status).toBe(201); + expect(approve.body.status).toBe('approved'); + + const updated = await request(h.server).get(`/api/v1/timeline/${eventId}`).set(dm); + expect(updated.body.title).toBe('The Great Battle of Red Valley'); + expect(updated.body.body).toContain('Decisive victory'); + }); + it('approving a drafted story beat creates it under the target arc', async () => { const arc = await request(h.server).post(`/api/v1/campaigns/${campaignId}/arcs`).set(dm).send({ title: 'Main arc' }); expect(arc.status).toBe(201); diff --git a/apps/server/test/unit/proposals-approve.spec.ts b/apps/server/test/unit/proposals-approve.spec.ts index bca8bb3a2..89f062406 100644 --- a/apps/server/test/unit/proposals-approve.spec.ts +++ b/apps/server/test/unit/proposals-approve.spec.ts @@ -93,6 +93,7 @@ describe('ProposalsService.approve (issue #681)', () => { {} as never, {} as never, storylines, + {} as never, ); return { service, records, quests, storylines, audit, existing }; diff --git a/apps/web/src/features/ai-dm/DraftWithAiButton.tsx b/apps/web/src/features/ai-dm/DraftWithAiButton.tsx index 2e3766801..f1a27b8cf 100644 --- a/apps/web/src/features/ai-dm/DraftWithAiButton.tsx +++ b/apps/web/src/features/ai-dm/DraftWithAiButton.tsx @@ -28,7 +28,7 @@ import { useDraftWithAiAvailable } from './useDraftWithAiAvailable'; import { UI_ICON_SIZE } from '../../lib/uiIcons'; /** Targets that support drafting N items at once (mirrors CoDmService's MULTI_TARGETS). */ -const MULTI_TARGETS = new Set(['npc', 'location', 'beat', 'quest', 'faction']); +const MULTI_TARGETS = new Set(['npc', 'location', 'beat', 'quest', 'faction', 'timeline_event']); const TARGET_NOUN: Record = { npc: 'NPC', @@ -40,6 +40,7 @@ const TARGET_NOUN: Record = { map: 'map', quest: 'quest', faction: 'faction', + timeline_event: 'timeline event', }; const TARGET_PLURAL: Record = { @@ -52,6 +53,7 @@ const TARGET_PLURAL: Record = { map: 'maps', quest: 'quests', faction: 'factions', + timeline_event: 'timeline events', }; const TARGET_TITLE: Record = { @@ -64,6 +66,7 @@ const TARGET_TITLE: Record = { map: 'Draft a map with AI', quest: 'Draft a quest with AI', faction: 'Draft a faction with AI', + timeline_event: 'Draft a timeline event with AI', }; const TARGET_EXAMPLE: Record = { @@ -76,6 +79,7 @@ const TARGET_EXAMPLE: Record = { map: "a small smugglers' cave with a tidal chamber", quest: "retrieve the stolen relic from the bandits' hideout before the full moon", faction: 'a merchant guild that secretly controls the city council through debts', + timeline_event: 'a major battle in 1492 DR where the ancient alliance was broken', }; /** diff --git a/apps/web/src/features/timeline/TimelinePage.tsx b/apps/web/src/features/timeline/TimelinePage.tsx index ed0df2c6b..ff070611f 100644 --- a/apps/web/src/features/timeline/TimelinePage.tsx +++ b/apps/web/src/features/timeline/TimelinePage.tsx @@ -36,6 +36,7 @@ import { StaleWriteConflict, type ConflictField } from '../../components/StaleWr import { RevisionHistoryPanel } from '../../components/RevisionHistoryPanel'; import { ConfirmDialog } from '../../components/ConfirmDialog'; import { UndoSnackbar } from '../../components/UndoSnackbar'; +import { DraftWithAiButton } from '../ai-dm/DraftWithAiButton'; import { TIMELINE_BODY_HELP, TIMELINE_BODY_LABEL, @@ -430,18 +431,25 @@ export default function TimelinePage() { {t('nav.timeline')}
{canDmWrite && !creating && ( - { - setNewDraft(emptyDraft(nextSortIndex)); - setNewFieldErrors({}); - setCreating(true); - setActionError(null); - }} - style={{ fontSize: 13 }} - > - + New event - +
+ + { + setNewDraft(emptyDraft(nextSortIndex)); + setNewFieldErrors({}); + setCreating(true); + setActionError(null); + }} + style={{ fontSize: 13 }} + > + + New event + +
)}
@@ -637,8 +645,16 @@ export default function TimelinePage() { fieldErrors={editFieldErrors} onClearFieldError={(field) => setEditFieldErrors((fe) => ({ ...fe, [field]: undefined }))} /> -
+
saveEdit(e.id)} disabled={busy}>{eventConflict ? 'Save resolution' : 'Save'} + { diff --git a/apps/web/test/component/TimelineDraftWithAi.spec.tsx b/apps/web/test/component/TimelineDraftWithAi.spec.tsx new file mode 100644 index 000000000..930aa770f --- /dev/null +++ b/apps/web/test/component/TimelineDraftWithAi.spec.tsx @@ -0,0 +1,58 @@ +/** + * Component-render coverage for issue #1310: "Draft with AI" button and modal + * for timeline_event target. + */ +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; +import { describe, test, expect, vi, afterEach } from 'vitest'; +import '../../src/i18n'; +import { DraftWithAiButton } from '../../src/features/ai-dm/DraftWithAiButton'; + +vi.mock('../../src/features/ai-dm/useDraftWithAiAvailable', () => ({ + useDraftWithAiAvailable: () => true, +})); + +describe('DraftWithAiButton for timeline_event target (issue #1310)', () => { + afterEach(() => { + cleanup(); + vi.clearAllMocks(); + }); + + test('renders Draft with AI button and opens modal for timeline_event', async () => { + render( + , + ); + + const button = screen.getByRole('button', { name: /Draft with AI/i }); + expect(button).toBeDefined(); + + fireEvent.click(button); + + const dialog = screen.getByRole('dialog'); + expect(dialog).toBeDefined(); + expect(screen.getByText('Draft a timeline event with AI')).toBeDefined(); + }); + + test('renders Edit with AI button for rewriting an existing timeline event', async () => { + render( + , + ); + + const button = screen.getByRole('button', { name: /Edit with AI/i }); + expect(button).toBeDefined(); + + fireEvent.click(button); + + const dialog = screen.getByRole('dialog'); + expect(dialog).toBeDefined(); + }); +}); diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index 3ce6e02a5..7981b7a14 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -9992,7 +9992,7 @@ export function aiDmReadinessProgress( // (#304/#306); the proposal payload carries their (seeded) params and approval // runs the generator. Every draft is metered against the seat budget and the // proposer is attributed to the AI seat + model, not a raw token name. -export const CoDmDraftTarget = z.enum(['npc', 'location', 'arc', 'beat', 'recap', 'encounter', 'map', 'quest', 'faction']); +export const CoDmDraftTarget = z.enum(['npc', 'location', 'arc', 'beat', 'recap', 'encounter', 'map', 'quest', 'faction', 'timeline_event']); export type CoDmDraftTarget = z.infer; // POST /campaigns/:id/ai-dm/draft (dm only) and the draft_content MCP tool.