A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: review application letters through canonical drafting
Amruth Pillaia7ceac2c60ae
diff --git a/docs/guides/managing-applications-with-mcp.mdx b/docs/guides/managing-applications-with-mcp.mdxindex 67718611d..eca1d3dc9 100644--- a/docs/guides/managing-applications-with-mcp.mdx+++ b/docs/guides/managing-applications-with-mcp.mdx@@ -139,7 +139,7 @@ Draft a short follow-up to the recruiter at Northwind Games asking about next st| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || `score_application_match` | Saves a new match score on the application, replacing the previous one. The score is an editing aid for finding gaps, not a hiring probability or a promise that an applicant tracking system accepts the resume. || `tailor_resume_for_application` | Creates a private copy of the linked resume with a rewritten summary, links the copy to the application in place of the original and adds a timeline note. The original resume is unchanged. It changes only the summary, without a review step. |-| `draft_application_message` | In cover-letter mode, saves a new cover letter and returns its text and ID. In follow-up mode, returns the text only. It never sends anything. |+| `draft_application_message` | In cover-letter mode, returns draft text for review and the ID of a new linked letter with an empty body. `reviewRequired: true` means the body has not been kept. In follow-up mode, returns text only. It never sends anything. || `autofill_application_from_job` | Returns suggested company, role, location and salary from a pasted posting. It saves nothing. |For reviewable changes across the whole resume, use the same assistant as the app: copy the resume for the job (`api_documents_copy_for_job`), start an assistant conversation on the copy (`api_agent_threads_start`) and ask it to tailor (`api_agent_messages_send`). Its proposed edits come back pending, each with the posting requirement it addresses, the assistant's citations and anything nothing checked backs, plus the posting requirements it found, gaps included. Each set names the application whose copy it's for (`tailoredFor`), and recording one as accepted on any other resume is refused. Nothing changes until you approve: your AI client applies an approved edit to that copy with `apply_resume_patch`, passing `proposalApplications` and `proposalSafety`, so the decision is recorded in the same write. If the edit's current wording isn't what the patch writes, or tailoring doesn't allow it on that resume, nothing is written. A structural set (an edit with a `snapshot`) is applied whole. Send `snapshot:<edit id>` as its `proposalApplications` value; this bounded receipt identifies the immutable proposal even when its review summary is long. Prose receipts name the current `after`. Both allow later user refinements in the same save. Older `true` receipts require the saved content to match the proposal exactly, including the whole `snapshot.after` for structural sets. A resume with tailored or reworded assistant edits refuses content changes that don't send `proposalSafety`.@@ -148,6 +148,19 @@ For reviewable changes across the whole resume, use the same assistant as the apCopy my resume for the Northwind Games application and ask the Reactive Resume assistant to tailor the copy. Show me each proposed edit with its requirement, citations and flagged claims, and the requirements with gaps. Apply only the ones I approve.```+Cover-letter mode uses the app's letter draft prompt and language rules, sending the posting and linked resume text without private notes or design settings. Review the returned `text` in your AI client. Only after you approve it should the client read the new letter's current revision and call `update_cover_letter` with the approved body as escaped HTML paragraphs, `expectedRevision`, and the returned `aiOperationIds`. Those references retain the original provider/model; saving approved text makes no new model request. The returned `coverLetterId` does not mean the draft body has been accepted. A failed draft creates no letter. Follow-up mode neither creates a letter nor logs a reply as sent.++<Frame caption="After an explicit approved save, the letter retains its fictional draft connection and model even after that connection is deleted.">+ <img+ src="/images/guides/career/mcp-letter-reviewed-source.png"+ alt="Letter body with a fictional services paragraph, one AI request attempt from Fictional MCP Letter AI using letter-capable, and its greeting and sign-off fields."+ />+</Frame>++```text+Draft a cover letter for Northwind Games. Show me the returned text first. Keep the linked letter's body empty until I approve it, then save that version with its request sources.+```+Read anything the AI writes before you use it. You can also tailor resumes and write letters from the app; see [Tailoring a resume for a job](/guides/tailoring-a-resume-for-a-job).## Clean updiff --git a/docs/guides/using-the-api.mdx b/docs/guides/using-the-api.mdxindex 79a17e841..d2c327ca7 100644--- a/docs/guides/using-the-api.mdx+++ b/docs/guides/using-the-api.mdx@@ -197,6 +197,8 @@ curl "https://rxresu.me/api/openapi/resumes?limit=20&offset=20" \Use `PATCH` for partial application, interview, timeline-entry and cover-letter updates. Resume content uses JSON Patch at `/resumes/{id}`; metadata uses `PATCH /resumes/{id}/metadata`. Resource-oriented paths such as `/resumes/{id}/copies` and `/documents/{type}/{id}/trash` are preferred for new integrations. Existing verb-based routes, partial `PUT` routes, response shapes and enum values remain supported.+Application cover-letter drafts at `POST /applications/{id}/ai/message-drafts` retain `text` and `coverLetterId`, and add `reviewRequired: true`, recorded `aiOperationIds` and `aiUsage`. The new linked letter's body stays empty: show the text for approval before saving it with `PATCH /cover-letters/{coverLetterId}`, the letter's current `expectedRevision`, and those operation IDs. Convert approved plain text to escaped HTML paragraphs for `content`. Do not treat the returned ID as acceptance of generated text. Follow-up mode still returns text without creating or sending a letter.+## RetriesState-changing operations do not implement `Idempotency-Key`. Treat mutations as unsafe to retry automatically, including requests that timed out: the change might already have happened. Read the current resource before deciding whether to repeat a write. Repeating create, copy, import or AI operations can create duplicates or incur provider charges.diff --git a/docs/guides/writing-a-cover-letter.mdx b/docs/guides/writing-a-cover-letter.mdxindex 34abc8724..7ecf1ab71 100644--- a/docs/guides/writing-a-cover-letter.mdx+++ b/docs/guides/writing-a-cover-letter.mdx@@ -158,6 +158,8 @@ If you've connected an AI provider, an empty body offers a first draft. See [ConAfter accepting a body draft on an updated server, the body shows its recorded **AI request attempts**, original connection label, provider and requested model. Choosing an earlier version keeps that version's sources. A revision also keeps sources from the draft it revised. **Stop**, recovery, copying a letter and saving don't add provider requests. The weekly report still includes attempts for drafts you reject. Historical details stay after removing a connection.+An AI client using [the MCP application tools](/guides/managing-applications-with-mcp#use-ai-on-an-application) uses the same letter draft prompt. It receives text for you to review and an empty linked letter. The client must ask before keeping that body; after an approved save, its recorded request sources appear here too. Nothing is sent to the employer.+<Frame caption="The accepted body keeps its original request history even after the connection is removed."><imgsrc="/images/guides/writing-a-cover-letter/letter-ai-provenance.png"diff --git a/docs/images/guides/career/mcp-letter-reviewed-source.png b/docs/images/guides/career/mcp-letter-reviewed-source.pngnew file mode 100644index 000000000..ef005cdf8Binary files /dev/null and b/docs/images/guides/career/mcp-letter-reviewed-source.png differdiff --git a/docs/spec.json b/docs/spec.jsonindex 5c4bc4ff3..c883c911a 100644--- a/docs/spec.json+++ b/docs/spec.json@@ -37811,7 +37811,7 @@"post": {"operationId": "aiDraftApplicationMessage","summary": "Draft a message about this application",- "description": "Drafts a cover letter or follow-up message from the application's posting and linked resume using your AI provider. A cover letter is saved as a new letter and its ID returned; a follow-up is returned as text. Nothing is sent.",+ "description": "Drafts a cover letter or follow-up message using your AI provider. Cover-letter text is returned for review with a new empty linked letter's ID; reviewRequired means the body has not been saved. Save approved text through the letter update endpoint with its aiOperationIds. A follow-up is returned as text. Nothing is sent.","deprecated": true,"tags": ["Applications",@@ -37862,6 +37862,65 @@},"coverLetterId": {"type": "string"+ },+ "reviewRequired": {+ "const": true+ },+ "aiOperationIds": {+ "type": "array",+ "maxItems": 1000,+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ },+ "aiUsage": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "requests": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "models": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "providerId": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "provider": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "providerId",+ "label",+ "provider",+ "model"+ ]+ }+ }+ },+ "required": [+ "requests",+ "models"+ ]+ },+ {+ "type": "null"+ }+ ]}},"required": [@@ -166268,7 +166327,7 @@"post": {"operationId": "createApplicationMessageDraft","summary": "Draft a message about this application",- "description": "Drafts a cover letter or follow-up message from the application's posting and linked resume using your AI provider. A cover letter is saved as a new letter and its ID returned; a follow-up is returned as text. Nothing is sent.",+ "description": "Drafts a cover letter or follow-up message using your AI provider. Cover-letter text is returned for review with a new empty linked letter's ID; reviewRequired means the body has not been saved. Save approved text through the letter update endpoint with its aiOperationIds. A follow-up is returned as text. Nothing is sent.","tags": ["Applications","AI"@@ -166318,6 +166377,65 @@},"coverLetterId": {"type": "string"+ },+ "reviewRequired": {+ "const": true+ },+ "aiOperationIds": {+ "type": "array",+ "maxItems": 1000,+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ },+ "aiUsage": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "requests": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "models": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "providerId": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "provider": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "providerId",+ "label",+ "provider",+ "model"+ ]+ }+ }+ },+ "required": [+ "requests",+ "models"+ ]+ },+ {+ "type": "null"+ }+ ]}},"required": [diff --git a/packages/api/src/features/ai/usage.integration.test.ts b/packages/api/src/features/ai/usage.integration.test.tsindex 0c101875b..cc29c521b 100644--- a/packages/api/src/features/ai/usage.integration.test.ts+++ b/packages/api/src/features/ai/usage.integration.test.ts@@ -9,8 +9,10 @@ import { generateText, stepCountIs, streamText, tool } from "ai";import { strFromU8, unzipSync, zipSync, strToU8 } from "fflate";import { Pool } from "pg";import { z } from "zod";+import { letterDraftSystemPrompt } from "@reactive-resume/ai/prompts";import { db, withDatabasePool } from "@reactive-resume/db/client";import * as tables from "@reactive-resume/db/schema";+import { coverLetterTextToHtml } from "@reactive-resume/resume/cover-letter";import { aiOperationIds } from "@reactive-resume/schema/ai-usage";import { sampleResumeData } from "@reactive-resume/schema/resume/sample";import { buildAccountZip } from "@reactive-resume/utils/account-zip";@@ -18,6 +20,7 @@ import { loadDocument } from "../agent/document";import { upsertAssistantUiMessage } from "../agent/messages-persistence";import { agentRouter } from "../agent/router";import { aiProvidersService } from "../ai-providers/service";+import { aiRouter as applicationAiRouter } from "../applications/ai";import { authRouter } from "../auth/router";import { authService } from "../auth/service";import { careerRouter } from "../career/router";@@ -62,12 +65,14 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec| "writing"| "resume"| "agent"+ | "letter"| "improve";let agentChanges: unknown[] = [];let agentStep = 0;let release = () => {};let arrived = () => {};let requests: { model: string; path: string }[] = [];+ let requestMessages: unknown[][] = [];const server = createServer((req, res) => {let raw = "";req.on("data", (chunk) => {@@ -75,8 +80,9 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec});req.on("end", () => {void (async () => {- const body = JSON.parse(raw) as { model: string };+ const body = JSON.parse(raw) as { model: string; messages?: unknown[]; stream?: boolean };requests.push({ model: body.model, path: req.url ?? "" });+ requestMessages.push(body.messages ?? []);arrived();if (mode === "hold")await new Promise<void>((resolve) => {@@ -120,6 +126,16 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec);return;}+ if (mode === "letter" && body.stream) {+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.write(+ `data: ${JSON.stringify({ id: "letter", created: 1, model: body.model, choices: [{ index: 0, delta: { content: "done" }, finish_reason: null }] })}\n\n`,+ );+ res.end(+ `data: ${JSON.stringify({ id: "letter", created: 1, model: body.model, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\ndata: [DONE]\n\n`,+ );+ return;+ }if (mode === "stream") {res.writeHead(200, { "content-type": "text/event-stream" });for (let index = 0; index < 50; index++)@@ -183,7 +199,10 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec});});const run = (operation: () => Promise<void>) => withDatabasePool(pool, operation);- const client = (permissions: ("read" | "write" | "delete")[] = ["read", "write", "delete"]) =>+ const client = (+ permissions: ("read" | "write" | "delete")[] = ["read", "write", "delete"],+ reqHeaders = new Headers(),+ ) =>createRouterClient({ai: aiRouter,@@ -193,11 +212,12 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecresume: resumeRouter,documents: documentsRouter,agent: agentRouter,+ applicationAi: applicationAiRouter,},{context: {locale: "en-US",- reqHeaders: new Headers(),+ reqHeaders,authentication: { user, method: "apiKey", permissions },},},@@ -234,6 +254,7 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecrelease();arrived = () => {};requests = [];+ requestMessages = [];agentStep = 0;agentChanges = [];mode = "text";@@ -709,6 +730,169 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec}),);+ it("uses the canonical letter prompt for MCP/REST cover-letter drafts", () =>+ run(async () => {+ await provider();+ const api = client();+ const data = structuredClone(sampleResumeData);+ data.metadata.page.locale = "en-GB";+ data.metadata.notes = "PRIVATE_FICTIONAL_NOTES_NOT_FOR_DRAFT";+ const sourceId = await api.resume.import({ data });+ const sourceBefore = await api.resume.getById({ id: sourceId });+ const [application] = await db+ .insert(tables.application)+ .values({+ userId: user.id,+ company: "Fictional Cedar",+ role: "Engineer",+ status: "saved",+ resumeId: sourceId,+ jobDescription: "Build fictional reliable services.",+ postingSource: {+ method: "paste",+ format: "text",+ truncated: false,+ completeness: "unknown",+ language: "de-DE",+ },+ })+ .returning();+ if (!application) throw new Error("Missing fictional application");+ mode = "letter";+ const result = await api.applicationAi.draftMessage({ id: application.id, kind: "cover-letter" });+ expect(result.text).toBe("done");+ expect(requests).toHaveLength(1);+ const system = requestMessages[0]?.find((message) => (message as { role?: string }).role === "system") as+ | { content: string }+ | undefined;+ expect(system?.content).toBe(letterDraftSystemPrompt);+ expect(JSON.stringify(requestMessages[0])).toContain("Write in de-DE.");+ expect(JSON.stringify(requestMessages[0])).not.toContain(data.metadata.notes);+ expect(result).toMatchObject({+ reviewRequired: true,+ coverLetterId: expect.any(String),+ aiOperationIds: [expect.any(String)],+ aiUsage: { requests: 1 },+ });+ const letter = await api.letters.getById({ id: result.coverLetterId ?? "missing" });+ expect(letter.content).toBe("");+ expect(letter.aiOperationIds).toEqual([]);+ expect(letter.style.metadata.page.locale).toBe("de-DE");+ await expect(+ client(["read"]).applicationAi.draftMessage({ id: application.id, kind: "cover-letter" }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ await expect(+ client(undefined, new Headers({ "x-ai-destination": "none" })).applicationAi.draftMessage({+ id: application.id,+ kind: "cover-letter",+ }),+ ).rejects.toMatchObject({ code: "CONFLICT" });+ expect(requests).toHaveLength(1);+ const accepted = await api.letters.update({+ id: letter.id,+ expectedRevision: letter.revision,+ content: coverLetterTextToHtml(result.text),+ aiOperationIds: result.aiOperationIds,+ });+ expect(accepted.content).toBe("<p>done</p>");+ expect(accepted.aiUsage).toEqual(result.aiUsage);+ expect(requests).toHaveLength(1);+ expect((await api.resume.getById({ id: sourceId })).data).toEqual(sourceBefore.data);+ }));++ it("does not create a letter when a canonical application draft fails or the application belongs to another account", () =>+ run(async () => {+ await provider();+ const [owned, foreign] = await db+ .insert(tables.application)+ .values([+ {+ userId: user.id,+ company: "Fictional Cedar",+ role: "Engineer",+ status: "saved" as const,+ jobDescription: "Build fictional reliable services.",+ },+ {+ userId: "usage-bob",+ company: "Other fictional company",+ role: "Engineer",+ status: "saved" as const,+ jobDescription: "PRIVATE_OTHER_APPLICATION",+ },+ ])+ .returning();+ if (!owned || !foreign) throw new Error("Missing fictional applications");+ await expect(client().applicationAi.draftMessage({ id: foreign.id, kind: "cover-letter" })).rejects.toMatchObject(+ { code: "NOT_FOUND" },+ );+ expect(requests).toHaveLength(0);+ mode = "failure";+ await expect(client().applicationAi.draftMessage({ id: owned.id, kind: "cover-letter" })).rejects.toMatchObject({+ code: "BAD_GATEWAY",+ });+ expect(requests).toHaveLength(1);+ expect((await pool.query("select id from cover_letter where user_id=$1", [user.id])).rows).toEqual([]);+ }));++ it("leaves no new letter after an application draft is cancelled in transport", () =>+ run(async () => {+ await provider();+ const [application] = await db+ .insert(tables.application)+ .values({+ userId: user.id,+ company: "Fictional Cedar",+ role: "Engineer",+ status: "saved",+ jobDescription: "Build fictional reliable services.",+ })+ .returning();+ if (!application) throw new Error("Missing fictional application");+ mode = "hold";+ const arrivedAtProvider = new Promise<void>((resolve) => {+ arrived = resolve;+ });+ const controller = new AbortController();+ const pending = client().applicationAi.draftMessage(+ { id: application.id, kind: "cover-letter" },+ { signal: controller.signal },+ );+ try {+ await arrivedAtProvider;+ controller.abort();+ await expect(pending).rejects.toThrow();+ expect(requests).toHaveLength(1);+ expect((await client().ai.usage({})).requests).toBe(1);+ expect((await pool.query("select id from cover_letter where user_id=$1", [user.id])).rows).toEqual([]);+ } finally {+ release();+ }+ }));++ it("preserves the legacy follow-up text contract without creating a letter or logging a sent reply", () =>+ run(async () => {+ await provider();+ const [application] = await db+ .insert(tables.application)+ .values({+ userId: user.id,+ company: "Fictional Cedar",+ role: "Engineer",+ status: "saved",+ jobDescription: "Build fictional reliable services.",+ })+ .returning();+ if (!application) throw new Error("Missing fictional application");+ const result = await client().applicationAi.draftMessage({ id: application.id, kind: "follow-up" });+ expect(result).toEqual({ text: "done" });+ expect(requests).toHaveLength(1);+ expect((await pool.query("select id from cover_letter where user_id=$1", [user.id])).rows).toEqual([]);+ expect(+ (await pool.query("select activity from application where id=$1", [application.id])).rows[0]?.activity,+ ).toEqual(application.activity);+ }));+it.each(["resume", "letter"] as const)("%s accepted assistant sources preserve prior lineage, partial decisions and older clients",(kind) =>diff --git a/packages/api/src/features/applications/ai.ts b/packages/api/src/features/applications/ai.tsindex 4fb2dab32..4d7db7eb3 100644--- a/packages/api/src/features/applications/ai.ts+++ b/packages/api/src/features/applications/ai.ts@@ -6,7 +6,7 @@ import { APICallError, generateText, RetryError } from "ai";import z from "zod";import { safetySystemPrompt } from "@reactive-resume/ai/prompts";import { aiModelForTask } from "@reactive-resume/ai/task-models";-import { coverLetterTextToHtml } from "@reactive-resume/resume/cover-letter";+import { aiOperationIdsSchema, aiUsageSummarySchema } from "@reactive-resume/schema/ai-usage";import { postingSourceSchema } from "@reactive-resume/schema/applications/data";import { slugify } from "@reactive-resume/utils/slug";import { generateId } from "@reactive-resume/utils/string";@@ -17,7 +17,8 @@ import { dataBlock } from "../ai/data-block";import { isNoAiDestination } from "../ai/destination";import { aiDeadline, generateJson as sharedGenerateJson } from "../ai/generate-json";import { getModel } from "../ai/service";-import { createAiUsage } from "../ai/usage";+import { createAiUsage, readAiUsage } from "../ai/usage";+import { draftLetterBody } from "../cover-letters/draft";import { coverLetterService } from "../cover-letters/service";import { assertDocumentVersion } from "../documents/ownership";import { resumeService } from "../resume/service";@@ -474,12 +475,20 @@ export const aiRouter = {operationId: "aiDraftApplicationMessage",summary: "Draft a message about this application",description:- "Drafts a cover letter or follow-up message from the application's posting and linked resume using your AI provider. A cover letter is saved as a new letter and its ID returned; a follow-up is returned as text. Nothing is sent.",+ "Drafts a cover letter or follow-up message using your AI provider. Cover-letter text is returned for review with a new empty linked letter's ID; reviewRequired means the body has not been saved. Save approved text through the letter update endpoint with its aiOperationIds. A follow-up is returned as text. Nothing is sent.",...reserved,}).input(z.object({ id: z.string(), kind: z.enum(["cover-letter", "follow-up"]) })).use(aiRequestRateLimit)- .output(z.object({ text: z.string(), coverLetterId: z.string().optional() }))+ .output(+ z.object({+ text: z.string(),+ coverLetterId: z.string().optional(),+ reviewRequired: z.literal(true).optional(),+ aiOperationIds: aiOperationIdsSchema.optional(),+ aiUsage: aiUsageSummarySchema.nullable().optional(),+ }),+ ).errors(aiErrors).handler(async ({ context, input, signal }) => {const application = await applicationService.getById({ id: input.id, userId: context.user.id });@@ -490,27 +499,48 @@ export const aiRouter = {await assertApplicationVersion(tx, context.user.id, application);if (resume) await assertDocumentVersion(tx, context.user.id, { kind: "resume", ...resume });};+ if (input.kind === "cover-letter") {+ const draft = await draftLetterBody({+ application,+ resume,+ userId: context.user.id,+ variant: "draft",+ includeProvenance: true,+ signal,+ });+ let text = "";+ const aiOperationIds: string[] = [];+ for await (const part of draft) {+ if (typeof part === "string") text += part;+ else aiOperationIds.push(part.aiOperationId);+ }+ signal?.throwIfAborted();+ const aiUsage = await readAiUsage(context.user.id, aiOperationIds);+ const letter = await coverLetterService.create({+ userId: context.user.id,+ name: `${application.company} — ${application.role}`.slice(0, 100),+ content: "",+ applicationId: input.id,+ ...(resume ? { resumeId: resume.id } : {}),+ });+ return {+ text: text.trim(),+ coverLetterId: letter.id,+ reviewRequired: true as const,+ aiOperationIds,+ aiUsage,+ };+ }const { model, provider } = await resolveModel(context.user.id, "draft-message", "capable", check);const context_ = `${dataBlock("POSTING", JSON.stringify({ role: application.role, company: application.company, location: application.location, description: application.jobDescription }))}${resume ? `\nCANDIDATE RESUME:\n${JSON.stringify(resume.data)}` : ""}`;- const prompt =- input.kind === "cover-letter"- ? `Write a concise, specific cover letter (250-350 words, no placeholders like [Name]) for this application, drawing on the resume. Return only the letter text.\n\n${context_}`- : `Write a short, polite follow-up message (80-120 words) to a recruiter checking in on this application. Warm but not pushy. Return only the message text.\n\n${context_}`;+ const prompt = `Write a short, polite follow-up message (80-120 words) to a recruiter checking in on this application. Warm but not pushy. Return only the message text.\n\n${context_}`;await aiProvidersService.authorize({ userId: context.user.id, id: provider.id }, check);signal?.throwIfAborted();const text = await generatePlainText(model, prompt, signal);- if (input.kind === "follow-up") return { text };- const letter = await coverLetterService.create({- userId: context.user.id,- name: `${application.company} — ${application.role}`.slice(0, 100),- content: coverLetterTextToHtml(text),- applicationId: input.id,- ...(resume ? { resumeId: resume.id } : {}),- });- return { text, coverLetterId: letter.id };+ return { text };}),// Create a tailored copy of the linked resume (job-specific summary) and link it to the application.diff --git a/packages/api/src/features/cover-letters/draft.ts b/packages/api/src/features/cover-letters/draft.tsindex 33ad1098d..dfd5df365 100644--- a/packages/api/src/features/cover-letters/draft.ts+++ b/packages/api/src/features/cover-letters/draft.ts@@ -3,6 +3,7 @@ import { ORPCError } from "@orpc/client";import { streamText } from "ai";import { letterDraftSystemPrompt } from "@reactive-resume/ai/prompts";import { aiModelForTask } from "@reactive-resume/ai/task-models";+import { initialCoverLetterLocale } from "@reactive-resume/resume/cover-letter";import { buildMarkdown } from "@reactive-resume/resume/markdown";import { aiProvidersService } from "../ai-providers/service";import { dataBlock } from "../ai/data-block";@@ -15,6 +16,17 @@ import { coverLetterService } from "./service";type Variant = CoverLetterDraftInput["variant"];+type DraftLetterInput = (+ | CoverLetterDraftInput+ | {+ application: Awaited<ReturnType<typeof applicationService.getById>>;+ resume: Awaited<ReturnType<typeof resumeService.getById>> | null;+ variant: "draft";+ previous?: undefined;+ includeProvenance?: boolean;+ }+) & { userId: string; signal?: AbortSignal | undefined };+const REQUESTS: Record<Variant, string> = {draft: "Write the body of the letter.",shorter: "Shorter: revise the previous draft.",@@ -50,16 +62,21 @@ function buildLetterDraftPrompt(input: PromptInput): string {* shows the draft until it's kept or discarded, so a failure leaves the letter as it was.*/export async function draftLetterBody(- input: CoverLetterDraftInput & { userId: string; signal?: AbortSignal | undefined },+ input: DraftLetterInput,): Promise<AsyncGenerator<string | { aiOperationId: string }>> {const { userId } = input;- const letter = await coverLetterService.getById({ id: input.id, userId });- const [resume, application] = await Promise.all([- letter.sourceResumeId ? resumeService.getById({ id: letter.sourceResumeId, userId }).catch(() => null) : null,- letter.sourceApplicationId- ? applicationService.getById({ id: letter.sourceApplicationId, userId }).catch(() => null)- : null,- ]);+ const letter = "id" in input ? await coverLetterService.getById({ id: input.id, userId }) : null;+ const [resume, application] =+ "application" in input+ ? [input.resume, input.application]+ : await Promise.all([+ letter?.sourceResumeId+ ? resumeService.getById({ id: letter.sourceResumeId, userId }).catch(() => null)+ : null,+ letter?.sourceApplicationId+ ? applicationService.getById({ id: letter.sourceApplicationId, userId }).catch(() => null)+ : null,+ ]);if (!resume && !application) {throw new ORPCError("BAD_REQUEST", { message: "Link the letter to a resume or an application first." });}@@ -73,7 +90,7 @@ export async function draftLetterBody(application?.jobDescription?.trim() ||(application?.requirements.length ? application.requirements.map((item) => `- ${item}`).join("\n") : undefined);const usage = createAiUsage(userId, "draft-letter", provider, async (tx) => {- await assertDocumentVersion(tx, userId, { kind: "letter", ...letter });+ if (letter) await assertDocumentVersion(tx, userId, { kind: "letter", ...letter });if (resume) await assertDocumentVersion(tx, userId, { kind: "resume", ...resume });if (application) await assertApplicationVersion(tx, userId, application);});@@ -86,14 +103,16 @@ export async function draftLetterBody(});const prompt = buildLetterDraftPrompt({variant: input.variant,- locale: letter.style.metadata.page.locale,+ locale:+ letter?.style.metadata.page.locale ??+ initialCoverLetterLocale(application?.postingSource?.language, resume?.data.metadata.page.locale),job: application ? `${application.role} at ${application.company}` : undefined,posting,resume: resume ? buildMarkdown(resume.data) : undefined,previous: input.previous,});await aiProvidersService.authorize({ userId, id: provider.id }, async (tx) => {- await assertDocumentVersion(tx, userId, { kind: "letter", ...letter });+ if (letter) await assertDocumentVersion(tx, userId, { kind: "letter", ...letter });if (resume) await assertDocumentVersion(tx, userId, { kind: "resume", ...resume });if (application) await assertApplicationVersion(tx, userId, application);});diff --git a/packages/api/src/features/cover-letters/service.ts b/packages/api/src/features/cover-letters/service.tsindex ec2348a60..1ce61301a 100644--- a/packages/api/src/features/cover-letters/service.ts+++ b/packages/api/src/features/cover-letters/service.ts@@ -11,7 +11,7 @@ import { ORPCError } from "@orpc/client";import { and, asc, count, desc, eq, ilike, inArray, isNull, ne, or, sql } from "drizzle-orm";import { db } from "@reactive-resume/db/client";import * as schema from "@reactive-resume/db/schema";-import { copyCoverLetterStyle } from "@reactive-resume/resume/cover-letter";+import { copyCoverLetterStyle, initialCoverLetterLocale } from "@reactive-resume/resume/cover-letter";import { SUBMITTED_DOCUMENT_LOCKED } from "@reactive-resume/schema/applications/errors";import {coverLetterContentSchema,@@ -560,15 +560,10 @@ export const coverLetterService = {if (input.template) style.metadata.template = input.template;// The letter is for an employer whose posting declared a language: start in it, so the body, greeting,// sign-off and date all match. The user can change it in Design; existing letters are never rewritten.- const postingLanguage = application?.postingSource?.language;- if (postingLanguage) {- try {- const [canonical] = Intl.getCanonicalLocales(postingLanguage);- if (canonical) style.metadata.page.locale = canonical;- } catch {- // An unusable tag leaves the letter's own language alone.- }- }+ style.metadata.page.locale = initialCoverLetterLocale(+ application?.postingSource?.language,+ style.metadata.page.locale,+ );const linked = Boolean(input.resumeId) && !input.template;const letter = await db.transaction(async (tx) => {await lockUser(tx, input.userId);diff --git a/packages/mcp/src/tool-meta.ts b/packages/mcp/src/tool-meta.tsindex 26bd5b5dc..b3fa4d433 100644--- a/packages/mcp/src/tool-meta.ts+++ b/packages/mcp/src/tool-meta.ts@@ -8,6 +8,7 @@ import { resumePatchOperationsSchema } from "@reactive-resume/ai/tools/resume-toimport { applicationDto } from "@reactive-resume/api/dto/application";import { coverLetterDto } from "@reactive-resume/api/dto/cover-letter";import { resumeDto } from "@reactive-resume/api/dto/resume";+import { aiOperationIdsSchema, aiUsageSummarySchema } from "@reactive-resume/schema/ai-usage";import {applicationStatusSchema,interviewDetailsSchema,@@ -767,8 +768,14 @@ export const TOOL_META = withAnnotationTitles({[T.draftApplicationMessage]: {title: "Draft Application Message",description:- "Send application context and the full linked resume, when available, to your configured AI provider to draft a cover letter or recruiter follow-up. Requires an enabled, tested default AI provider. Cover-letter mode saves a new cover letter and returns text plus coverLetterId; follow-up mode returns text without saving it. Neither mode sends a message to a recruiter.",- outputSchema: z.object({ text: z.string(), coverLetterId: z.string().optional() }),+ "Draft a cover letter or recruiter follow-up with your enabled, tested default AI provider. Cover-letter mode uses the same draft owner and letter-language rules as the app, sending the posting and linked resume text rather than resume design or private notes. It returns text, coverLetterId, reviewRequired:true and recorded aiOperationIds/aiUsage; the new linked letter body is empty. Show the draft to the user and obtain approval before saving its body with update_cover_letter, passing the returned aiOperationIds and the letter's current expectedRevision. Never save generated text automatically. Existing text/coverLetterId fields remain available; reviewRequired explicitly identifies unaccepted body text. Follow-up mode sends application context and the full linked resume, then returns text without creating a letter or logging a reply. Neither mode sends anything to an employer.",+ outputSchema: z.object({+ text: z.string(),+ coverLetterId: z.string().optional(),+ reviewRequired: z.literal(true).optional(),+ aiOperationIds: aiOperationIdsSchema.optional(),+ aiUsage: aiUsageSummarySchema.nullable().optional(),+ }),inputSchema: wireInput(z.strictObject({ id: applicationIdSchema, kind: z.enum(["cover-letter", "follow-up"]) })),annotations: { ...WRITE_NON_IDEMPOTENT, openWorldHint: true },},diff --git a/packages/mcp/src/tools.test.ts b/packages/mcp/src/tools.test.tsindex 362438086..02db058ae 100644--- a/packages/mcp/src/tools.test.ts+++ b/packages/mcp/src/tools.test.ts@@ -107,6 +107,31 @@ describe("registerTools", () => {vi.clearAllMocks();});+ it("preserves the application-letter review and provenance envelope without saving generated text", async () => {+ const draft = {+ text: "Fictional reviewed body",+ coverLetterId: "letter",+ reviewRequired: true,+ aiOperationIds: ["operation"],+ aiUsage: {+ requests: 1,+ models: [{ providerId: "provider", label: "Fictional AI", provider: "openai", model: "original-model" }],+ },+ };+ clientMock.applications.ai.draftMessage.mockResolvedValueOnce(draft);+ const { server, registered } = makeFakeServer();+ registerTools(server as never, clientMock as never, new Headers());+ const tool = registered.find((tool) => tool.name === MCP_TOOL_NAME.draftApplicationMessage)!;+ const input = { id: "application", kind: "cover-letter" };+ const result = await tool.handler(TOOL_META[MCP_TOOL_NAME.draftApplicationMessage].inputSchema.parse(input));+ expect(clientMock.applications.ai.draftMessage).toHaveBeenCalledWith(input);+ expect(result.structuredContent).toEqual(draft);+ expect(clientMock.coverLetters.update).not.toHaveBeenCalled();+ expect(TOOL_META[MCP_TOOL_NAME.draftApplicationMessage].outputSchema.parse({ text: "Legacy follow-up" })).toEqual({+ text: "Legacy follow-up",+ });+ });+it("creates and duplicates with an automatically generated address", async () => {const { server, registered } = makeFakeServer();registerTools(server as never, clientMock as never, new Headers());diff --git a/packages/resume/src/cover-letter.test.ts b/packages/resume/src/cover-letter.test.tsindex dbe15288b..caca46635 100644--- a/packages/resume/src/cover-letter.test.ts+++ b/packages/resume/src/cover-letter.test.ts@@ -7,8 +7,16 @@ import {createCoverLetterResumeData,detachEmbeddedLetters,greetingName,+ initialCoverLetterLocale,} from "./cover-letter";+it("keeps creation and drafting on the same posting/resume/default language", () => {+ expect(initialCoverLetterLocale("de-de", "en-GB")).toBe("de-DE");+ expect(initialCoverLetterLocale("not_a_language", "en-GB")).toBe("en-GB");+ expect(initialCoverLetterLocale(undefined, "en-GB")).toBe("en-GB");+ expect(initialCoverLetterLocale(undefined)).toBe(defaultResumeData.metadata.page.locale);+});+describe("detachEmbeddedLetters", () => {it("takes letters out of the resume and its layout, and returns each one", () => {const data = structuredClone(defaultResumeData);diff --git a/packages/resume/src/cover-letter.ts b/packages/resume/src/cover-letter.tsindex c118a8363..195eb5fb4 100644--- a/packages/resume/src/cover-letter.ts+++ b/packages/resume/src/cover-letter.ts@@ -12,6 +12,19 @@ export function copyCoverLetterStyle(return structuredClone({ basics: data.basics, picture: data.picture, metadata, sectionId, itemId });}+/** A new letter follows a valid posting language, otherwise its resume or the default style. */+export function initialCoverLetterLocale(+ postingLanguage: string | undefined,+ fallback = defaultResumeData.metadata.page.locale,+): string {+ if (!postingLanguage) return fallback;+ try {+ return Intl.getCanonicalLocales(postingLanguage)[0] ?? fallback;+ } catch {+ return fallback;+ }+}+export function createCoverLetterResumeData(letter: Pick<CoverLetter, "name" | "recipient" | "content" | "style">,): ResumeData {diff --git a/tests/e2e/specs/ai-usage.spec.ts b/tests/e2e/specs/ai-usage.spec.tsindex 84a0342ba..dc43f41a4 100644--- a/tests/e2e/specs/ai-usage.spec.ts+++ b/tests/e2e/specs/ai-usage.spec.ts@@ -16,6 +16,84 @@ test.afterAll(async () => {await stub?.close();});+test("application message REST draft stays empty until approved and retains the canonical letter source", async ({+ authPage: page,+}, info) => {+ test.skip(process.env.FLAG_ALLOW_UNSAFE_AI_BASE_URL !== "true", "Needs isolated local AI stub permission");+ await page.setViewportSize({ width: 1440, height: 1000 });+ await approveLocalStubOperations(page);+ const connection = await page.request.post("/api/openapi/ai-providers", {+ data: {+ label: "Fictional MCP Letter AI",+ provider: "openai-compatible",+ model: "letter-main",+ capableModel: "letter-capable",+ baseURL: stub.baseURL,+ apiKey: "stub-key",+ },+ });+ await expect(connection).toBeOK();+ const { id: providerId } = await connection.json();+ await expect(await page.request.post(`/api/openapi/ai-providers/${providerId}/test`)).toBeOK();+ await createSampleResumeFromDashboard(page, info);+ const resumeId = new URL(page.url()).pathname.split("/").at(-1) ?? "";+ const application = await page.request.post("/api/openapi/applications", {+ data: {+ company: "Fictional Cedar",+ role: "Engineer",+ resumeId,+ jobDescription: "Build fictional reliable services.",+ },+ });+ await expect(application).toBeOK();+ const id = await application.json();+ const before = stub.requests.length;+ const response = await page.request.post(`/api/openapi/applications/${id}/ai/message-drafts`, {+ data: { kind: "cover-letter" },+ });+ await expect(response).toBeOK();+ const result = await response.json();+ expect(result).toMatchObject({+ text: expect.any(String),+ coverLetterId: expect.any(String),+ reviewRequired: true,+ aiOperationIds: [expect.any(String)],+ aiUsage: { requests: 1 },+ });+ const read = async () => await (await page.request.get(`/api/openapi/cover-letters/${result.coverLetterId}`)).json();+ const blank = await read();+ expect(blank.content).toBe("");+ expect(blank.aiOperationIds).toEqual([]);+ await page.goto(`/builder/letter/${blank.id}`);+ const body = page.getByRole("region", { name: "Letter", exact: true });+ await body.getByRole("button", { name: "Write it myself", exact: true }).click();+ await expect(body.getByRole("textbox", { name: "Letter body", exact: true })).toHaveText("");+ expect(stub.requests.length - before).toBe(1);+ const content = result.text+ .split(/\n\s*\n/)+ .map(+ (paragraph: string) =>+ `<p>${paragraph.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">")}</p>`,+ )+ .join("");+ await expect(+ await page.request.patch(`/api/openapi/cover-letters/${blank.id}`, {+ data: { content, expectedRevision: blank.revision, aiOperationIds: result.aiOperationIds },+ }),+ ).toBeOK();+ await expect(await page.request.delete(`/api/openapi/ai-providers/${providerId}`)).toBeOK();+ await page.reload();+ await expect(body.getByRole("textbox", { name: "Letter body", exact: true })).toContainText(+ result.text.split("\n")[0],+ );+ await expect(+ body.getByText("Fictional MCP Letter AI · openai-compatible · letter-capable", { exact: true }),+ ).toBeVisible();+ expect((await read()).aiUsage).toEqual(result.aiUsage);+ expect(stub.requests.length - before).toBe(1);+ await body.screenshot({ path: info.outputPath("mcp-letter-reviewed-source.png"), animations: "disabled" });+});+for (const kind of ["resume assistant", "letter assistant", "writing review"] as const)test(`${kind} acceptance pairs original sources with saved content and Undo without generating again`, async ({authPage: page,