From 181a8a718ba15ae3f72f4efc923cd4929229b89e Mon Sep 17 00:00:00 2001 From: Rohita Date: Sat, 14 Nov 2026 11:15:46 +0530 Subject: [PATCH 1/3] feat(journey): add sample chats and harden inline verification --- backend/.env.example | 1 + backend/src/ai/gemini.provider.ts | 6 +- backend/src/config/upstash.config.ts | 3 +- backend/src/controllers/journey.controller.ts | 21 +- .../journey/continueJourney.processor.ts | 46 +++- .../journey/createGraph.processor.ts | 11 +- .../journey/extractJourneyDraft.processor.ts | 12 +- .../journey/finalizeJourneyDraft.processor.ts | 99 ++++++-- .../journey/generateUserSummary.processor.ts | 6 +- .../src/processors/journey/journeySchema.ts | 12 +- .../journey/partialJourneyDraft.schema.ts | 23 +- .../journey/submitJourney.processor.ts | 143 +++++++---- .../journey/verifyProof.processor.ts | 239 +++++------------- .../prompts/onboarding/journeyDraft.prompt.ts | 100 +++----- backend/src/routes/journey.routes.ts | 16 +- backend/src/services/journeyMapping.ts | 11 +- backend/src/services/user.service.ts | 6 +- .../types/journey/GeminiJourneyDraft.types.ts | 7 +- backend/src/types/journey/Journey.types.ts | 7 +- .../src/types/journey/JourneySession.types.ts | 6 +- backend/tests/journeyDraft.test.ts | 84 ++++++ backend/tests/journeyMapping.test.ts | 18 ++ backend/tests/proofVerification.test.ts | 54 ++++ docs/how-it-works.md | 6 +- frontend/api/journey.api.ts | 25 +- frontend/app/(tabs)/journey.tsx | 1 + frontend/app/share-journey.tsx | 211 +++++++++++++--- .../desktop/DesktopExperienceChat.tsx | 118 +++++++++ .../components/desktop/DesktopJourney.tsx | 23 +- .../components/landing/desktopLanding.css | 53 ++-- frontend/package-lock.json | 75 ------ 31 files changed, 930 insertions(+), 513 deletions(-) create mode 100644 backend/tests/journeyDraft.test.ts create mode 100644 backend/tests/proofVerification.test.ts create mode 100644 frontend/components/desktop/DesktopExperienceChat.tsx diff --git a/backend/.env.example b/backend/.env.example index ee9953c..7deeabd 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -22,3 +22,4 @@ NODE_ENV=development PORT=5000 # Expo can use 8082 when another development server occupies 8081. CORS_ORIGINS=http://localhost:8081,http://localhost:8082,http://localhost:19006 +MAINTENANCE_SECRET= diff --git a/backend/src/ai/gemini.provider.ts b/backend/src/ai/gemini.provider.ts index f3ff907..8e505f8 100644 --- a/backend/src/ai/gemini.provider.ts +++ b/backend/src/ai/gemini.provider.ts @@ -19,11 +19,13 @@ export class GeminiProvider { userPrompt, schema, temperature, + timeoutMs, }: { systemPrompt: string; userPrompt: string; schema: Schema; temperature?: number; + timeoutMs?: number; }): Promise { const model = geminiClient.getGenerativeModel({ @@ -38,9 +40,7 @@ export class GeminiProvider { }); const result = - await model.generateContent( - userPrompt - ); + await model.generateContent(userPrompt, timeoutMs === undefined ? undefined : { timeout: timeoutMs }); const text = result.response.text(); diff --git a/backend/src/config/upstash.config.ts b/backend/src/config/upstash.config.ts index 26cf5f6..316ba28 100644 --- a/backend/src/config/upstash.config.ts +++ b/backend/src/config/upstash.config.ts @@ -3,4 +3,5 @@ import { Redis } from "@upstash/redis"; export const upstash = new Redis({ url: process.env.UPSTASH_REDIS_URL!, token: process.env.UPSTASH_REDIS_TOKEN!, -}); \ No newline at end of file + signal: () => AbortSignal.timeout(5_000), +}); diff --git a/backend/src/controllers/journey.controller.ts b/backend/src/controllers/journey.controller.ts index 5c171af..b71e3e6 100644 --- a/backend/src/controllers/journey.controller.ts +++ b/backend/src/controllers/journey.controller.ts @@ -34,15 +34,24 @@ export async function continueJourneyController( ): Promise { try { const { conversationId, message } = req.body; + const userId = req.userId; + if (!userId) { + res.status(401).json({ error: "Unauthorized" }); + return; + } if (!conversationId || typeof conversationId !== "string") { res.status(400).json({ error: "conversationId is required" }); return; } - if (!message || typeof message !== "string") { + if (typeof message !== "string" || !message.trim()) { res.status(400).json({ error: "message is required" }); return; } - const response = await continueJourney(conversationId, message); + const response = await continueJourney(userId, conversationId, message.trim()); + if (!response) { + res.status(404).json({ error: "Journey session not found" }); + return; + } res.json({ success: true, @@ -106,11 +115,15 @@ export async function submitJourneyController( }); return; } + if (journeyPayload.mockVerification !== undefined && typeof journeyPayload.mockVerification !== "boolean") { + res.status(400).json({ error: "mockVerification must be a boolean" }); + return; + } const proofFile = req.file ?? null; const result = await submitJourney( userId, conversationId, - { experiences: journeyPayload.experiences }, + { experiences: journeyPayload.experiences, mockVerification: journeyPayload.mockVerification }, proofFile ); res.json({ @@ -127,4 +140,4 @@ export async function submitJourneyController( error: message, }); } -} \ No newline at end of file +} diff --git a/backend/src/processors/journey/continueJourney.processor.ts b/backend/src/processors/journey/continueJourney.processor.ts index 5326fed..204ece1 100644 --- a/backend/src/processors/journey/continueJourney.processor.ts +++ b/backend/src/processors/journey/continueJourney.processor.ts @@ -1,28 +1,56 @@ import { getJourneySession, updateJourneySession } from "../../services/journeySession.service.js"; import { extractJourneyDraft } from "./extractJourneyDraft.processor.js"; -import { finalizeJourneyDraft } from "./finalizeJourneyDraft.processor.js"; +import { applyJourneyDraftChanges } from "./finalizeJourneyDraft.processor.js"; import type { JourneyMessage } from "../../types/journey/JourneySession.types.js"; +import type { GeminiJourneyDraft } from "../../types/journey/GeminiJourneyDraft.types.js"; +import { getUserGoals } from "../../services/goal.service.js"; + +async function loadDraftGoals(userId: string) { + let deadline: ReturnType | undefined; + try { + return await Promise.race([ + getUserGoals(userId), + new Promise>>(resolve => { + deadline = setTimeout(() => resolve([]), 3_000); + }), + ]); + } catch { + return []; + } finally { + clearTimeout(deadline); + } +} export async function continueJourney( + userId: string, conversationId: string, message: string ) { const session = await getJourneySession(conversationId); - if (!session) { - throw new Error("Journey session not found"); - } + if (!session || session.userId !== userId) return null; const userMessage: JourneyMessage = { role: "user", content: message, timestamp: Date.now(), }; - session.conversationHistory.push(userMessage); - const geminiDraft = await extractJourneyDraft(message); - const journeyDraft = await finalizeJourneyDraft(geminiDraft,session.userId); + const previous = session.journeyDraft?.experiences ?? []; + const goalsRequest = session.journeyDraft?.goals ?? loadDraftGoals(userId); + let extractionUnavailable = false; + let geminiDraft: GeminiJourneyDraft; + try { + geminiDraft = (await extractJourneyDraft(message, previous, session.conversationHistory)) ?? { experiences: [] }; + } catch (error) { + console.warn("Journey draft extraction unavailable:", error instanceof Error ? error.name : "Unknown error"); + extractionUnavailable = true; + geminiDraft = { experiences: [] }; + } + const { experiences, changedFields } = applyJourneyDraftChanges(geminiDraft, previous, message); + const journeyDraft = { goals: await goalsRequest, experiences }; + session.conversationHistory.push(userMessage); session.journeyDraft = journeyDraft; session.updatedAt = Date.now(); await updateJourneySession(conversationId, session); - return { conversationId, journeyDraft }; -} \ No newline at end of file + return { conversationId, journeyDraft, changedFields, extractionUnavailable }; +} diff --git a/backend/src/processors/journey/createGraph.processor.ts b/backend/src/processors/journey/createGraph.processor.ts index 02bfc32..bd3a81b 100644 --- a/backend/src/processors/journey/createGraph.processor.ts +++ b/backend/src/processors/journey/createGraph.processor.ts @@ -50,6 +50,8 @@ function experienceParams(experience: JourneyExperience, order: number) { applicationStatus: nullIfUndefined(experience.applicationStatus), achievements: experience.achievements ?? null, isVerified: experience.isVerified ?? false, + verificationStatus: experience.verificationStatus ?? null, + verificationMocked: experience.verificationMocked ?? null, order, }; } @@ -127,7 +129,7 @@ export async function upsertExperience( await tx.run( ` MATCH (u:User {username: $username}) - MERGE (e:Experience {id: $id}) + MERGE (u)-[r:HAS_EXPERIENCE]->(e:Experience {id: $id}) SET e.title = $title, e.timelineSummary = $timelineSummary, @@ -142,9 +144,10 @@ export async function upsertExperience( e.organization = $organization, e.applicationStatus = $applicationStatus, e.achievements = $achievements, - e.isVerified = $isVerified - MERGE (u)-[r:HAS_EXPERIENCE]->(e) - SET r.order = $order + e.isVerified = $isVerified, + e.verificationStatus = $verificationStatus, + e.verificationMocked = $verificationMocked, + r.order = $order `, { username, diff --git a/backend/src/processors/journey/extractJourneyDraft.processor.ts b/backend/src/processors/journey/extractJourneyDraft.processor.ts index 2cb883c..e2b9fde 100644 --- a/backend/src/processors/journey/extractJourneyDraft.processor.ts +++ b/backend/src/processors/journey/extractJourneyDraft.processor.ts @@ -1,16 +1,20 @@ import { geminiProvider } from "../../ai/gemini.provider.js"; import { JOURNEY_DRAFT_SYSTEM_PROMPT, buildJourneyDraftPrompt, } from "../../prompts/onboarding/journeyDraft.prompt.js"; -import type { GeminiJourneyDraft } from "../../types/journey/GeminiJourneyDraft.types.js"; +import type { GeminiExperience, GeminiJourneyDraft } from "../../types/journey/GeminiJourneyDraft.types.js"; +import type { JourneyMessage } from "../../types/journey/JourneySession.types.js"; import { partialJourneyDraftSchema } from "./partialJourneyDraft.schema.js"; export async function extractJourneyDraft( - narrative: string + narrative: string, + previous: GeminiExperience[], + history: JourneyMessage[], ): Promise { return geminiProvider.generateStructuredJson({ systemPrompt: JOURNEY_DRAFT_SYSTEM_PROMPT, - userPrompt: buildJourneyDraftPrompt(narrative), + userPrompt: buildJourneyDraftPrompt(narrative, previous, history), schema: partialJourneyDraftSchema, + timeoutMs: 15_000, }); -} \ No newline at end of file +} diff --git a/backend/src/processors/journey/finalizeJourneyDraft.processor.ts b/backend/src/processors/journey/finalizeJourneyDraft.processor.ts index aaef9fc..8778504 100644 --- a/backend/src/processors/journey/finalizeJourneyDraft.processor.ts +++ b/backend/src/processors/journey/finalizeJourneyDraft.processor.ts @@ -1,25 +1,82 @@ import { randomUUID } from "crypto"; -import { getUserGoals } from "../../services/goal.service.js"; +import { z } from "zod"; import type { GeminiJourneyDraft } from "../../types/journey/GeminiJourneyDraft.types.js"; import type { PartialJourneyDraft } from "../../types/journey/PartialJourney.types.js"; +import { applicationStatusSchema, journeySkillSchema } from "./journeySchema.js"; -export async function finalizeJourneyDraft( - draft: GeminiJourneyDraft, - userId: string -): Promise { - const existingGoals = await getUserGoals(userId); - const experiences = - draft.experiences.map((experience) => { - return { - ...experience, - id:randomUUID(), - goalIds: [], - proofs: [], - isVerified: false, - }; - }); - return { - goals: existingGoals, - experiences, - }; -} \ No newline at end of file +const text = z.string().trim().min(1); +const date = z.string().trim().regex(/^(0[1-9]|1[0-2]) \d{4}$/); +const draftChangesSchema = z.object({ + experienceNumber: z.number().int().positive().optional().catch(0), + title: text.optional().catch(undefined), + context: text.optional().catch(undefined), + timelineSummary: text.optional().catch(undefined), + startDate: date.nullable().optional().catch(undefined), + endDate: date.nullable().optional().catch(undefined), + organization: text.nullable().optional().catch(undefined), + challengeFaced: text.nullable().optional().catch(undefined), + outcome: text.nullable().optional().catch(undefined), + applicationStatus: applicationStatusSchema.nullable().optional().catch(undefined), + achievements: z.array(text).nullable().optional().catch(undefined), + skills: z.array(journeySkillSchema).nullable().optional().catch(undefined), + decisionReason: text.nullable().optional().catch(undefined), +}); + +export function applyJourneyDraftChanges( + draft: GeminiJourneyDraft, + previous: PartialJourneyDraft["experiences"], + narrative = "", +) { + const removed = new Set(Array.isArray(draft.removeExperienceNumbers) ? draft.removeExperienceNumbers : []); + const experiences = previous.map(experience => ({ ...experience })); + const changedFields: Record = {}; + const candidates = Array.isArray(draft.experiences) ? draft.experiences : []; + + for (const candidate of candidates) { + const parsed = draftChangesSchema.safeParse(candidate); + if (!parsed.success) continue; + const { experienceNumber: target, ...changes } = parsed.data; + const experienceNumber = target ?? ( + previous.length === 1 && previous[0]?.title === "Untitled experience" && previous[0].context === narrative + ? 1 + : undefined + ); + if (experienceNumber === undefined || previous.length === 0) { + const { title, context, timelineSummary } = changes; + const description = context ?? (previous.length === 0 ? narrative : ""); + if (!description) continue; + const newFields = Object.fromEntries(Object.entries(changes).filter(([, value]) => value != null)); + experiences.push({ + ...newFields, + title: title ?? "Untitled experience", + context: description, + timelineSummary: timelineSummary ?? description, + id: randomUUID(), goalIds: [], proofs: [], isVerified: false, + }); + continue; + } + + const existing = previous[experienceNumber - 1]; + if (!existing || removed.has(experienceNumber)) continue; + const updated = experiences[experienceNumber - 1]!; + const keys = (Object.keys(changes) as (keyof typeof changes)[]).filter(key => changes[key] !== undefined); + for (const key of keys) { + if (changes[key] === null) delete updated[key]; + } + Object.assign(updated, Object.fromEntries(Object.entries(changes).filter(([, value]) => value != null))); + if (keys.length) changedFields[existing.id] = [...(changedFields[existing.id] ?? []), ...keys]; + } + + if (!previous.length && !experiences.length && narrative) { + experiences.push({ + title: "Untitled experience", + context: narrative, + timelineSummary: narrative, + id: randomUUID(), goalIds: [], proofs: [], isVerified: false, + }); + } + return { + experiences: experiences.filter((_, index) => index >= previous.length || !removed.has(index + 1)), + changedFields, + }; +} diff --git a/backend/src/processors/journey/generateUserSummary.processor.ts b/backend/src/processors/journey/generateUserSummary.processor.ts index 70e529e..8a87917 100644 --- a/backend/src/processors/journey/generateUserSummary.processor.ts +++ b/backend/src/processors/journey/generateUserSummary.processor.ts @@ -10,7 +10,8 @@ export interface UserSummary { } export async function generateUserSummary( - clerkId: string + clerkId: string, + timeoutMs = 10_000, ): Promise { const session = getSession(); try { @@ -67,8 +68,9 @@ export async function generateUserSummary( subtopics, }), schema: userSummarySchema, + timeoutMs, }); } finally { await closeSession(session); } -} \ No newline at end of file +} diff --git a/backend/src/processors/journey/journeySchema.ts b/backend/src/processors/journey/journeySchema.ts index 416c237..f37be00 100644 --- a/backend/src/processors/journey/journeySchema.ts +++ b/backend/src/processors/journey/journeySchema.ts @@ -57,6 +57,13 @@ export const proofStatusSchema = z.enum([ "verified", "rejected", "skipped", + "failed", +]); +export const experienceVerificationStatusSchema = z.enum([ + "pending", + "verified", + "rejected", + "failed", ]); export const applicationStatusSchema = z.enum([ "accepted", @@ -104,7 +111,7 @@ export const journeyProofSchema = z .object({ id: z.string().trim().min(1), sourceType: proofSourceTypeSchema, - url: z.string().trim().min(1), + url: z.string().trim().min(1).nullable(), status: proofStatusSchema, verifiedAt: nullableDateTimeSchema, reason: z.string().trim().min(1).nullable().optional(), @@ -132,6 +139,8 @@ export const journeyExperienceSchema = z applicationStatus: applicationStatusSchema.nullable().optional(), achievements: z.array(z.string().trim().min(1)).nullable().optional(), isVerified: z.boolean().optional(), + verificationStatus: experienceVerificationStatusSchema.optional(), + verificationMocked: z.boolean().optional(), goalIds: z.array(z.string().trim().min(1)), skills: z.array(journeySkillSchema), proofs: z.array(journeyProofSchema), @@ -191,6 +200,7 @@ export const submitExperienceSchema = z export const submitJourneySchema = z .object({ experiences: z.array(submitExperienceSchema).min(1), + mockVerification: z.boolean().optional(), }) .strict(); diff --git a/backend/src/processors/journey/partialJourneyDraft.schema.ts b/backend/src/processors/journey/partialJourneyDraft.schema.ts index a41f321..7b2ec76 100644 --- a/backend/src/processors/journey/partialJourneyDraft.schema.ts +++ b/backend/src/processors/journey/partialJourneyDraft.schema.ts @@ -8,14 +8,20 @@ export const partialJourneyDraftSchema: Schema = { items: { type: SchemaType.OBJECT, properties: { + experienceNumber: { + type: SchemaType.INTEGER, + description: "Existing experience number. Omit for a new experience.", + }, title: { type: SchemaType.STRING, }, startDate: { + nullable: true, type: SchemaType.STRING, description: "Format: MM YYYY. Example: 01 2024", }, endDate: { + nullable: true, type: SchemaType.STRING, description: "Format: MM YYYY. Example: 08 2024", }, @@ -23,15 +29,19 @@ export const partialJourneyDraftSchema: Schema = { type: SchemaType.STRING, }, challengeFaced: { + nullable: true, type: SchemaType.STRING, }, outcome: { + nullable: true, type: SchemaType.STRING, }, organization: { + nullable: true, type: SchemaType.STRING, }, applicationStatus: { + nullable: true, type: SchemaType.STRING, format: "enum", enum: [ @@ -42,12 +52,14 @@ export const partialJourneyDraftSchema: Schema = { ], }, achievements: { + nullable: true, type: SchemaType.ARRAY, items: { type: SchemaType.STRING, }, }, skills: { + nullable: true, type: SchemaType.ARRAY, items: { type: SchemaType.OBJECT, @@ -66,22 +78,23 @@ export const partialJourneyDraftSchema: Schema = { ], }, }, + required: ["name", "type"], }, }, timelineSummary: { type: SchemaType.STRING, }, decisionReason: { + nullable: true, type: SchemaType.STRING, }, }, - required: [ - "title", - "context", - "timelineSummary", - ], }, }, + removeExperienceNumbers: { + type: SchemaType.ARRAY, + items: { type: SchemaType.INTEGER }, + }, }, required: [ "experiences", diff --git a/backend/src/processors/journey/submitJourney.processor.ts b/backend/src/processors/journey/submitJourney.processor.ts index ce51283..19f4750 100644 --- a/backend/src/processors/journey/submitJourney.processor.ts +++ b/backend/src/processors/journey/submitJourney.processor.ts @@ -15,14 +15,17 @@ import { updateUserSummary } from "../../services/user.service.js"; import { validateExperienceDuplicate } from "./staticAnalysis/experienceDuplicate.validator.js"; import { deleteJourneySession } from "../../services/journeySession.service.js"; import { addExperienceReputation } from "../../services/reputation.service.js"; -import { verifyProof } from "./verifyProof.processor.js"; +import { MAX_PROOF_FILE_SIZE, uploadProofToCloudinary, verifyProof } from "./verifyProof.processor.js"; import { z } from "zod"; function normalizeJourneyExperience( experience: z.infer ): JourneyExperience { + const { verificationStatus, verificationMocked, ...fields } = experience; return { - ...experience, + ...fields, + ...(verificationStatus !== undefined && { verificationStatus }), + ...(verificationMocked !== undefined && { verificationMocked }), endDate: experience.endDate ?? null, challengeFaced: experience.challengeFaced ?? null, outcome: experience.outcome ?? null, @@ -66,6 +69,7 @@ async function inferTransition( systemPrompt: TRANSITION_INFERENCE_SYSTEM_PROMPT, userPrompt: buildTransitionInferencePrompt(current, top5), schema: transitionInferenceSchema, + timeoutMs: 10_000, }); } export async function submitJourney( @@ -81,29 +85,61 @@ export async function submitJourney( ); } const validJourney = validation.data; - const submittedExperiences = validJourney.experiences; - const verifiedExperiences: JourneyExperience[] = []; - + const { experiences: submittedExperiences, mockVerification } = validJourney; + const fileProofs = submittedExperiences.flatMap(({ proofs }) => + proofs.filter(({ sourceType, url }) => !url && (sourceType === "image" || sourceType === "pdf")) + ); + if (proofFile && fileProofs.length !== 1) { + throw new Error("Attach one photo or document per submission and select it as proof."); + } + if (proofFile && proofFile.size > MAX_PROOF_FILE_SIZE) { + throw new Error("Attachments must be 10 MB or smaller."); + } for (const experience of submittedExperiences) { - const verifiedProofs = await Promise.all( - experience.proofs.map((proof) => - verifyProof( - experience, - proof, - proofFile - ) - ) - ); + const isDuplicate = await validateExperienceDuplicate(userId, { + title: experience.title, + organization: experience.organization ?? undefined, + description: experience.context, + achievements: experience.achievements ?? undefined, + outcome: experience.outcome ?? undefined, + }); + + if (isDuplicate) { + throw new Error( + `Submission rejected: An experience matching "${experience.title}" already exists in your journey footprint.` + ); + } + } + + const uploadedProofUrl = mockVerification && proofFile ? await uploadProofToCloudinary(proofFile) : null; + const experiencesToSave = await Promise.all(submittedExperiences.map(async experience => { + const proofs = mockVerification + ? experience.proofs.map((proof) => ({ + ...proof, + url: proof.url ?? (proof === fileProofs[0] ? uploadedProofUrl : null), + status: "skipped", + verifiedAt: null, + reason: null, + })) + : await Promise.all(experience.proofs.map(proof => + verifyProof(experience, proof, proof === fileProofs[0] ? proofFile : null) + )); + const isVerified = !mockVerification && proofs.some(proof => proof.status === "verified"); + const verificationStatus = mockVerification || isVerified + ? "verified" + : proofs.some(proof => proof.status === "failed") ? "failed" : "rejected"; const { decisionReason, ...experienceWithoutDecisionReason } = experience; const parsed = journeyExperienceSchema.safeParse({ ...experienceWithoutDecisionReason, - proofs: verifiedProofs, - isVerified: verifiedProofs.some( - (proof) => proof.status === "verified" - ), + proofs, + isVerified, + ...(mockVerification !== undefined && { + verificationStatus, + verificationMocked: mockVerification, + }), endDate: experience.endDate ?? null, challengeFaced: experience.challengeFaced ?? null, @@ -121,24 +157,8 @@ export async function submitJourney( const normalized: JourneyExperience = normalizeJourneyExperience(parsed.data); - verifiedExperiences.push(normalized); - } - - for (const exp of verifiedExperiences) { - const isDuplicate = await validateExperienceDuplicate(userId, { - title: exp.title, - organization: exp.organization ?? undefined, - description: exp.context, - achievements: exp.achievements ?? undefined, - outcome: exp.outcome ?? undefined, - }); - - if (isDuplicate) { - throw new Error( - `Submission rejected: An experience matching "${exp.title}" already exists in your journey footprint.` - ); - } - } + return normalized; + })); const transitions = submittedExperiences.flatMap((experience) => { const decisionReason = experience.decisionReason?.trim(); @@ -151,8 +171,8 @@ export async function submitJourney( }]; }); const username = await getUsernameByUserId(userId); - await createExperiences(username, verifiedExperiences); - for (const experience of verifiedExperiences) { + await createExperiences(username, experiencesToSave); + for (const experience of experiencesToSave) { await generateExperienceEmbedding({ id: experience.id, title: experience.title, @@ -165,17 +185,20 @@ export async function submitJourney( experience.achievements ?? null, skills: experience.skills.map((s) => s.name), - }); + }).catch(error => console.warn("Could not generate experience embedding", experience.id, error)); } const inferredTransitions: TransitionInference[] = []; - for (const transition of transitions) { + const inferred = await Promise.allSettled(transitions.map(async transition => { const candidates = await inferTransitionCandidates(transition.toExperienceId, transition.decisionLabel); - const inferred = await inferTransition(candidates.current, candidates.top5); - inferredTransitions.push(inferred); + return inferTransition(candidates.current, candidates.top5); + })); + for (const result of inferred) { + if (result.status === "fulfilled") inferredTransitions.push(result.value); + else console.warn("Could not infer journey transition", result.reason); } const validatedTransitions = inferredTransitions .map((transition): JourneyTransition | null => { - const currentExperience = verifiedExperiences.find( + const currentExperience = experiencesToSave.find( (experience) => experience.title === transition.currentTitle ); if (!currentExperience) { @@ -184,7 +207,7 @@ export async function submitJourney( ); return null; } - const previousExperience = verifiedExperiences.find( + const previousExperience = experiencesToSave.find( (experience) => experience.title === transition.fromTitle ); if (!previousExperience) { @@ -218,13 +241,25 @@ export async function submitJourney( .filter( (t): t is JourneyTransition => t !== null ); - await createTransitions(validatedTransitions); - const verifiedCount = verifiedExperiences.filter((experience) => experience.isVerified).length; - await addExperienceReputation(userId, verifiedExperiences.length, verifiedCount); - const { summary, expertiseAreas } = await generateUserSummary(userId); - await updateUserSummary(userId, summary, expertiseAreas); - const goalIds = [...new Set(verifiedExperiences.flatMap((experience) => experience.goalIds))]; - const goals = await getGoalsByIds(goalIds); + const savedTransitions = await createTransitions(validatedTransitions) + .then(() => validatedTransitions) + .catch(error => { + console.warn("Could not save inferred journey transitions", error); + return []; + }); + const verifiedCount = experiencesToSave.filter((experience) => experience.isVerified).length; + const goalIds = [...new Set(experiencesToSave.flatMap((experience) => experience.goalIds))]; + const [, , goals] = await Promise.all([ + addExperienceReputation(userId, experiencesToSave.length, verifiedCount) + .catch(error => console.warn("Could not update experience reputation", error)), + generateUserSummary(userId, 10_000) + .then(({ summary, expertiseAreas }) => updateUserSummary(userId, summary, expertiseAreas)) + .catch(error => console.warn("Could not update journey summary", error)), + getGoalsByIds(goalIds).catch(error => { + console.warn("Could not load saved journey goals", error); + return []; + }), + ]); try { await deleteJourneySession(conversationId); } catch (redisError) { @@ -232,10 +267,10 @@ export async function submitJourney( } return { goals, - experiences: verifiedExperiences.map( + experiences: experiencesToSave.map( ({ proofs, ...experience }) => experience ), - transitions: validatedTransitions, + transitions: savedTransitions, }; -} \ No newline at end of file +} diff --git a/backend/src/processors/journey/verifyProof.processor.ts b/backend/src/processors/journey/verifyProof.processor.ts index 868f25c..8b38dc6 100644 --- a/backend/src/processors/journey/verifyProof.processor.ts +++ b/backend/src/processors/journey/verifyProof.processor.ts @@ -1,6 +1,7 @@ import { geminiClient } from "../../config/gemini.config.js"; import type { JourneyProof } from "../../types/journey/Journey.types.js"; import { PROOF_VERIFICATION_SYSTEM_PROMPT, buildProofVerificationPrompt } from "../../prompts/onboarding/proofVerification.prompt.js"; +import { z } from "zod"; import { journeyProofSchema } from "./journeySchema.js"; import { SchemaType, type Schema } from "@google/generative-ai"; import { cloudinary } from "../../config/cloudinary.config.js"; @@ -8,9 +9,9 @@ import { PDFParse } from "pdf-parse"; import type { SubmitExperience, SubmitProof } from "./journeySchema.js"; -const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB limit +export const MAX_PROOF_FILE_SIZE = 10 * 1024 * 1024; // 10MB limit -function uploadProofToCloudinary( +export function uploadProofToCloudinary( file: Express.Multer.File ): Promise { return new Promise((resolve, reject) => { @@ -18,10 +19,11 @@ function uploadProofToCloudinary( { folder: "pathfinder/proofs", resource_type: "auto", + timeout: 10_000, }, (error, result) => { if (error || !result) { - reject(error); + reject(error ?? new Error("Cloudinary returned no upload result")); return; } @@ -33,11 +35,18 @@ function uploadProofToCloudinary( }); } +const proofVerdictSchema = z.object({ + status: z.enum(["verified", "rejected"]), + reason: z.string().trim().min(1), +}); + const temporaryLlmResponseSchema: Schema = { type: SchemaType.OBJECT, properties: { status: { type: SchemaType.STRING, + format: "enum", + enum: ["verified", "rejected"], description: "Whether the proof supports the claimed experience: must be 'verified' or 'rejected'", }, reason: { @@ -61,8 +70,9 @@ interface GitHubParseResult { function parseGitHubUrl(url: string): GitHubParseResult | null { try { const parsed = new URL(url); - if (parsed.hostname !== "github.com" && parsed.hostname !== "www.github.com") return null; + if (parsed.protocol !== "https:" || !["github.com", "www.github.com"].includes(parsed.hostname)) return null; const parts = parsed.pathname.split("/").filter(Boolean); + if (parts.some(part => !/^[\w.-]+$/.test(part))) return null; if (parts.length === 0) return null; const owner = parts[0]; @@ -82,21 +92,20 @@ function parseGitHubUrl(url: string): GitHubParseResult | null { } // Pull Request: github.com/owner/repo/pull/num - if (parts.length >= 4 && parts[2] === "pull") { + if (parts.length === 4 && parts[2] === "pull") { const id = parts[3]; - if (!id) return null; + if (!id || !/^\d+$/.test(id)) return null; return { type: "pull", owner, repo, id }; } // Commit: github.com/owner/repo/commit/sha - if (parts.length >= 4 && parts[2] === "commit") { + if (parts.length === 4 && parts[2] === "commit") { const id = parts[3]; - if (!id) return null; + if (!id || !/^[a-f0-9]+$/i.test(id)) return null; return { type: "commit", owner, repo, id }; } - // Fallback to repository - return { type: "repository", owner, repo }; + return null; } catch { return null; } @@ -109,6 +118,7 @@ async function fetchReadme(owner: string, repo: string): Promise { try { const res = await fetch(`https://api.github.com/repos/${owner}/${repo}/readme`, { headers: { "User-Agent": "PathFinder-Proof-Verification" }, + signal: AbortSignal.timeout(4_000), }); if (!res.ok) return "No README available or failed to fetch"; const data = (await res.json()) as any; @@ -122,39 +132,6 @@ async function fetchReadme(owner: string, repo: string): Promise { } } -/** - * Resolves local file paths or remote URLs with file safety validation. - */ -export async function fetchProofFile( - url: string -): Promise<{ buffer: Buffer; mimeType: string }> { - const res = await fetch(url); - if (!res.ok) { - throw new Error( - `Failed to fetch ${url}` - ); - } - const arrayBuffer = await res.arrayBuffer(); - if (arrayBuffer.byteLength > MAX_FILE_SIZE) { - throw new Error("File exceeds 10MB."); - } - return { - buffer: Buffer.from(arrayBuffer), - mimeType: - res.headers.get("content-type") ?? - getMimeTypeFromUrl(url), - }; -} - -function getMimeTypeFromUrl(urlOrPath: string): string { - const ext = urlOrPath.split(".").pop()?.toLowerCase(); - if (ext === "pdf") return "application/pdf"; - if (ext === "png") return "image/png"; - if (ext === "jpg" || ext === "jpeg") return "image/jpeg"; - if (ext === "webp") return "image/webp"; - return "application/octet-stream"; -} - /** * Standalone Proof Verification Processor. * Verifies if the submitted proof supports the claimed experience. @@ -165,61 +142,36 @@ export async function verifyProof( proof: SubmitProof, uploadedFile: Express.Multer.File | null ): Promise { - const sourceType = proof.sourceType; - const url = proof.url ?? ""; - let cloudinaryUrl = proof.url ?? ""; + const { sourceType } = proof; + const url = proof.url ?? null; + let storedUrl = url; + const unsuccessful = (status: "rejected" | "failed" | "skipped", reason: string): JourneyProof => ({ + id: proof.id, sourceType, url: storedUrl, status, verifiedAt: null, reason, + }); try { if (sourceType === "image" || sourceType === "pdf") { - if (!uploadedFile) { - return { - id: proof.id, - sourceType: proof.sourceType, - url: "", - status: "rejected", - verifiedAt: null, - reason: "Uploaded file is missing.", - }; - } - - try { - cloudinaryUrl = await uploadProofToCloudinary( - uploadedFile - ); - } catch (uploadErr: any) { - return { - id: proof.id, - sourceType: proof.sourceType, - url: "", - status: "rejected", - verifiedAt: null, - reason: - "Failed to upload proof: " + - uploadErr.message, - }; - } + if (!uploadedFile?.buffer.length) return unsuccessful("rejected", "The attached file is missing or empty."); + if (uploadedFile.size > MAX_PROOF_FILE_SIZE) return unsuccessful("rejected", "The attachment exceeds 10 MB."); + const supported = sourceType === "pdf" + ? uploadedFile.mimetype === "application/pdf" + : ["image/jpeg", "image/png", "image/webp", "image/heic", "image/heif"].includes(uploadedFile.mimetype); + if (!supported) return unsuccessful("skipped", "Use a PDF or a supported image format for verification."); + storedUrl = await uploadProofToCloudinary(uploadedFile); } let verificationContext = ""; let imagePart: any = null; if (sourceType === "github") { - const parsed = parseGitHubUrl(url); - if (!parsed) { - return { - id: proof.id, - sourceType: proof.sourceType, - url: cloudinaryUrl, - status: "rejected", - verifiedAt: null, - reason: `Invalid GitHub URL: ${url}`, - }; - } + const parsed = url && parseGitHubUrl(url); + if (!parsed) return unsuccessful("rejected", "Use a GitHub profile, repository, pull request, or commit URL."); - const headers = { "User-Agent": "PathFinder-Proof-Verification" }; + const request = { headers: { "User-Agent": "PathFinder-Proof-Verification" }, signal: AbortSignal.timeout(8_000) }; let payload: any = { type: parsed.type }; if (parsed.type === "repository") { - const res = await fetch(`https://api.github.com/repos/${parsed.owner}/${parsed.repo}`, { headers }); + const res = await fetch(`https://api.github.com/repos/${parsed.owner}/${parsed.repo}`, request); + if (res.status === 404) return unsuccessful("rejected", "GitHub could not find public evidence at that URL."); if (!res.ok) throw new Error(`GitHub Repository API error (${res.status}): ${res.statusText}`); const data = (await res.json()) as any; payload.repository = { @@ -235,7 +187,8 @@ export async function verifyProof( payload.readme = await fetchReadme(parsed.owner, parsed.repo!); } else if (parsed.type === "pull") { - const res = await fetch(`https://api.github.com/repos/${parsed.owner}/${parsed.repo}/pulls/${parsed.id}`, { headers }); + const res = await fetch(`https://api.github.com/repos/${parsed.owner}/${parsed.repo}/pulls/${parsed.id}`, request); + if (res.status === 404) return unsuccessful("rejected", "GitHub could not find public evidence at that URL."); if (!res.ok) throw new Error(`GitHub Pull Request API error (${res.status}): ${res.statusText}`); const data = (await res.json()) as any; payload.pullRequest = { @@ -251,7 +204,8 @@ export async function verifyProof( }; } else if (parsed.type === "commit") { - const res = await fetch(`https://api.github.com/repos/${parsed.owner}/${parsed.repo}/commits/${parsed.id}`, { headers }); + const res = await fetch(`https://api.github.com/repos/${parsed.owner}/${parsed.repo}/commits/${parsed.id}`, request); + if (res.status === 404) return unsuccessful("rejected", "GitHub could not find public evidence at that URL."); if (!res.ok) throw new Error(`GitHub Commit API error (${res.status}): ${res.statusText}`); const data = (await res.json()) as any; payload.commit = { @@ -264,7 +218,8 @@ export async function verifyProof( }; } else if (parsed.type === "user") { - const res = await fetch(`https://api.github.com/users/${parsed.owner}`, { headers }); + const res = await fetch(`https://api.github.com/users/${parsed.owner}`, request); + if (res.status === 404) return unsuccessful("rejected", "GitHub could not find public evidence at that URL."); if (!res.ok) throw new Error(`GitHub User API error (${res.status}): ${res.statusText}`); const data = (await res.json()) as any; payload.userProfile = { @@ -282,87 +237,24 @@ export async function verifyProof( verificationContext = JSON.stringify(payload, null, 2); } else if (sourceType === "pdf") { - let fileData; + const parser = new PDFParse({ data: uploadedFile!.buffer }); try { - fileData = await fetchProofFile(cloudinaryUrl); - } catch (err: unknown) { - const message = err instanceof Error ? err.message : String(err); - return { - id: proof.id, - sourceType: proof.sourceType, - url: cloudinaryUrl, - status: "rejected", - verifiedAt: null, - reason: `Failed to retrieve PDF file: ${message}`, - }; - } - - let extractedText = ""; - let pdfMetadata: any = {}; - try { - const parser = new PDFParse({ data: fileData.buffer }); const parsedText = await parser.getText(); - extractedText = parsedText.text; - - try { - const parsedInfo = await parser.getInfo(); - pdfMetadata = parsedInfo.info || {}; - } catch { - // Info parsing is optional - } - } catch (err: unknown) { - const message = err instanceof Error ? err.message : String(err); - return { - id: proof.id, - sourceType: proof.sourceType, - url: cloudinaryUrl, - status: "rejected", - verifiedAt: null, - reason: `Failed to parse PDF content: ${message}`, - }; + if (!parsedText.text.trim()) return unsuccessful("skipped", "The PDF contains no extractable text."); + verificationContext = parsedText.text.slice(0, 30_000); + } finally { + await parser.destroy(); } - - verificationContext = JSON.stringify({ - text: extractedText || "No text extracted from PDF.", - metadata: pdfMetadata, - }, null, 2); - } else if (sourceType === "image") { - let fileData; - try { - fileData = await fetchProofFile(cloudinaryUrl); - } catch (err: unknown) { - const message = err instanceof Error ? err.message : String(err); - return { - id: proof.id, - sourceType: proof.sourceType, - url: cloudinaryUrl, - status: "rejected", - verifiedAt: null, - reason: `Failed to retrieve image file: ${message}`, - }; - } - imagePart = { inlineData: { - data: fileData.buffer.toString("base64"), - mimeType: fileData.mimeType, + data: uploadedFile!.buffer.toString("base64"), + mimeType: uploadedFile!.mimetype, }, }; - - verificationContext = JSON.stringify({ - description: "Analyzing uploaded visual proof", - hasImageAttached: true, - }, null, 2); + verificationContext = "Analyze the attached image."; } else { - return { - id: proof.id, - sourceType: proof.sourceType, - url: cloudinaryUrl, - status: "rejected", - verifiedAt: null, - reason: `Unsupported proof source type: ${sourceType}`, - }; + return unsuccessful("skipped", "Generic links are not supported for verification."); } const model = geminiClient.getGenerativeModel({ @@ -394,22 +286,22 @@ export async function verifyProof( contents.push(imagePart); } - const result = await model.generateContent(contents); + const result = await model.generateContent(contents, { timeout: 15_000 }); const text = result.response.text(); if (!text) { throw new Error("Gemini returned empty verification response"); } - const verificationObj = JSON.parse(text) as { status: "verified" | "rejected"; reason: string }; + const verificationObj = proofVerdictSchema.parse(JSON.parse(text)); // Validate against the single source of truth Zod schema: journeyProofSchema const candidateResult = { id: proof.id, sourceType: proof.sourceType, - url: cloudinaryUrl, - status: verificationObj.status === "verified" ? "verified" : "rejected", + url: storedUrl, + status: verificationObj.status, verifiedAt: verificationObj.status === "verified" ? new Date().toISOString() : null, - reason: verificationObj.reason || "No reason provided", + reason: verificationObj.reason, }; const validated = journeyProofSchema.safeParse(candidateResult); @@ -423,17 +315,8 @@ export async function verifyProof( reason: validated.data.reason ?? null, }; - } catch (err: unknown) { - const message = err instanceof Error ? err.message : String(err); - return { - id: proof.id, - sourceType: proof.sourceType, - url: cloudinaryUrl, - status: "rejected", - verifiedAt: null, - reason: `Verification failed during analysis: ${message}`, - }; + } catch (error) { + console.warn("Proof verification failed", proof.id, error instanceof Error ? error.name : "Unknown error"); + return unsuccessful("failed", "The evidence could not be processed."); } } - - diff --git a/backend/src/prompts/onboarding/journeyDraft.prompt.ts b/backend/src/prompts/onboarding/journeyDraft.prompt.ts index 0968b3d..5effcfd 100644 --- a/backend/src/prompts/onboarding/journeyDraft.prompt.ts +++ b/backend/src/prompts/onboarding/journeyDraft.prompt.ts @@ -1,67 +1,47 @@ -export const JOURNEY_DRAFT_SYSTEM_PROMPT = ` -You are the Journey Draft Builder for PathFinder AI. -Your sole directive is to accurately extract structural milestones from a user's natural language story into a structured Journey Draft. - ---- CRITICAL OPERATIONAL LAWS --- -1. STRICT MATCHING: If a detail is mentioned in the input, you MUST extract it. Do not skip an optional field (like 'organization', 'outcome', 'achievements', or 'decisionReason') if the narrative contains clues or explicit statements satisfying it. -2. DECISION REASON CAPTURE: Pay extreme attention to WHY, WHEN, or HOW a user transitioned from one experience to the next. Triggers, motivations, pivots, lay-offs, graduations, sudden realizations, or discovering opportunities must be aggressively captured as the "decisionReason" for the NEXT experience it caused. -3. NO FABRICATION: Do not invent details. If an optional field is completely absent from the narrative, omit it. -4. SINGLE EXPERIENCE ARCHITECTURE: Do not split a single continuous job/project into multiple sub-blocks unless the user explicitly defines it as completely separate roles. - ---- FIELD DEFINITIONS & RULES --- -- title: Concise, punchy title (5-8 words). (e.g., "Full-Stack Engineer at FinTech Startup") -- context: Exact narrative facts. Preserve user wording. Do not enrich, expand, or add fluff. -- timelineSummary: One-sentence timeline description focusing purely on ACTION/WHAT HAPPENED, not what was learned. -- startDate: Format: "MM YYYY" (e.g., "01 2024"). -- endDate: Format: "MM YYYY". Omit if ongoing/unmentioned. -- organization: Populate ONLY when a specific, identifiable name is stated (e.g., "Google", "MIT", "HackerEarth"). NEVER use generic terms like "College", "Company", "Startup", "Client". Omit if name isn't given. -- challengeFaced: The clear friction point, obstacle, or difficulty mentioned. -- outcome: A concrete, tangible end result (e.g., "Received PPO", "Won 1st Place", "Product Shipped", "Application Rejected"). Do NOT list skills/technologies here. Omit if no structural result occurred. -- applicationStatus: Must strictly be one of: ["accepted", "rejected", "waitlisted", "pending"]. Only use if an application context exists. -- achievements: Measurable or externally recognized accomplishments (e.g., "Raised $50k funding", "Published paper in IEEE", "Secured 1st rank"). Do NOT list ordinary tasks, daily jobs, or learning tools. -- skills: Skills or tools explicitly stated. Never infer. -- decisionReason: The causal link or motivation for stepping into THIS specific experience. Capture the internal or external trigger. - * Look for connecting phrases: "Because of that...", "So I decided to...", "After graduating...", "I got laid off so I...", "I wanted to learn X so I started...". - * Apply this to the arriving experience, not the departing one. +import type { GeminiExperience } from "../../types/journey/GeminiJourneyDraft.types.js"; +import type { JourneyMessage } from "../../types/journey/JourneySession.types.js"; ---- PROHIBITED FIELDS --- -Do NOT create goals, goalIds, proofs, verification info, or id fields. - ---- FEW-SHOT PARSING EXAMPLES --- +export const JOURNEY_DRAFT_SYSTEM_PROMPT = ` +Build and revise a PathFinder journey draft using facts the user provides. The input contains the current draft, recent user messages, and the latest message. The latest message takes precedence for corrections. -Input Narrative: -"I was working at Stripe as a junior dev starting in June 2023. The project scaled like crazy but handling database locks under peak loads was a total nightmare. Eventually, we shipped the v2 engine successfully. However, in August 2024 I got passed over for a promotion, so I quit to start building my own micro-SaaS app called FormFlow. It was tough finding users initially, but we ended up hitting $2k MRR by December 2024." +- Add a new item only for a distinct experience the user actually describes. Include its title, context, and a one-sentence timelineSummary. Keep a continuous role or project in one experience. +- To revise an existing item, return its experienceNumber from the current draft and only fields affected by the latest message. Keep unrelated fields and experiences out of the response. Use null to explicitly clear an optional field. Use removeExperienceNumbers only when the user asks to remove an entire experience. If a target is ambiguous, leave it unchanged. +- An item titled "Untitled experience" is a starter draft. If the user repeats or adds to its description, fill its missing fields from the story and keep its experienceNumber. +- Use recent messages to resolve references or recover earlier details when the latest message supplies enough context to create a draft. For a question, greeting, or message with no new facts, return an empty experiences array. +- Use MM YYYY for startDate and endDate when the month and year are known. Leave missing dates blank. An ongoing role has no endDate. A milestone reached during a role does not establish an end date. +- Keep title concise, context faithful to the user's account, and timelineSummary focused on what happened. Update related text if a correction makes it inaccurate. +- Fill organization only for a named organization. Distinguish challengeFaced (the obstacle), outcome (the result), and achievements (measurable or recognized accomplishments). +- Use applicationStatus only for an explicit application. Return stated skills as objects with name and type (Technical, Soft, Domain, or ExtraCurricular). +- Put decisionReason on the experience the decision led to. Capture the user's stated motivation. +- Omit facts the user did not supply. Do not generate goals, proof records, verification information, or IDs. -Expected Output Extraction Structure: -[ - { - "title": "Junior Developer at Stripe", - "context": "Worked as a junior developer at Stripe starting in June 2023. Handled a project that scaled rapidly.", - "timelineSummary": "Built core features and managed scaling requirements as a junior developer.", - "startDate": "06 2023", - "endDate": "08 2024", - "organization": "Stripe", - "challengeFaced": "Handling complex database locks under peak transaction loads.", - "outcome": "Successfully shipped the v2 engine.", - "skills": ["Database Management", "Scaling Systems"] - }, - { - "title": "Founder of FormFlow Micro-SaaS", - "context": "Quit previous role to build an independent micro-SaaS application called FormFlow. Managed to grow it to a steady income.", - "timelineSummary": "Founded and scaled FormFlow micro-SaaS from scratch to thousands in recurring revenue.", - "startDate": "08 2024", - "endDate": "12 2024", - "organization": "FormFlow", - "challengeFaced": "Finding initial active users to gain early traction.", - "outcome": "Hit $2k Monthly Recurring Revenue (MRR).", - "achievements": ["Built and launched a product", "Hit $2k MRR independently"], - "decisionReason": "Quit and shifted to build this micro-SaaS because I was passed over for a promotion at Stripe." - } -] +Example: if experience 1 is the only internship and the user says "My internship started in July 2024, and we reduced processing time by 30%", return +{"experiences":[{"experienceNumber":1,"startDate":"07 2024","outcome":"Reduced processing time by 30%","achievements":["Reduced processing time by 30%"]}]}. `; export function buildJourneyDraftPrompt( - narrative: string + narrative: string, + previous: GeminiExperience[], + history: JourneyMessage[], ): string { - return narrative.trim(); -} \ No newline at end of file + const currentDraft = previous.map((experience, index) => ({ + experienceNumber: index + 1, + title: experience.title, + context: experience.context, + timelineSummary: experience.timelineSummary, + startDate: experience.startDate, + endDate: experience.endDate, + organization: experience.organization, + challengeFaced: experience.challengeFaced, + outcome: experience.outcome, + applicationStatus: experience.applicationStatus, + achievements: experience.achievements, + skills: experience.skills, + decisionReason: experience.decisionReason, + })); + return JSON.stringify({ + currentDraft, + recentMessages: history.filter(({ role }) => role === "user").slice(-8).map(({ content }) => content), + latestMessage: narrative, + }); +} diff --git a/backend/src/routes/journey.routes.ts b/backend/src/routes/journey.routes.ts index a2fc4c7..9bf8685 100644 --- a/backend/src/routes/journey.routes.ts +++ b/backend/src/routes/journey.routes.ts @@ -1,14 +1,26 @@ import { Router } from "express"; import multer from "multer"; import { requireAuth } from "../middleware/auth.middleware.js"; +import { MAX_PROOF_FILE_SIZE } from "../processors/journey/verifyProof.processor.js"; import { startJourneyController, continueJourneyController, submitGoalController,submitJourneyController } from "../controllers/journey.controller.js"; const router = Router(); -const upload = multer({storage: multer.memoryStorage(),}); +const uploadProof = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_PROOF_FILE_SIZE } }).single("proof"); router.post("/start", requireAuth, startJourneyController); router.post("/message", requireAuth, continueJourneyController); router.post("/submit/goal",requireAuth,submitGoalController); -router.post("/submit", requireAuth,upload.single("proof"),submitJourneyController); +router.post("/submit", requireAuth, (req, res, next) => { + uploadProof(req, res, (error: unknown) => { + if (error instanceof multer.MulterError) { + const tooLarge = error.code === "LIMIT_FILE_SIZE"; + res.status(tooLarge ? 413 : 400).json({ + error: tooLarge ? "Attachments must be 10 MB or smaller." : "Attach one photo or document per submission.", + }); + return; + } + next(error); + }); +}, submitJourneyController); export default router; diff --git a/backend/src/services/journeyMapping.ts b/backend/src/services/journeyMapping.ts index d4bcc75..dc22228 100644 --- a/backend/src/services/journeyMapping.ts +++ b/backend/src/services/journeyMapping.ts @@ -42,7 +42,7 @@ export function mapJourneyExperience( organization: experience.organization ?? null, applicationStatus: experience.applicationStatus ?? null, achievements: experience.achievements ?? null, - isVerified: experience.isVerified ?? false, + isVerified: !experience.verificationMocked && (experience.isVerified ?? false), timelineSummary: experience.timelineSummary, goalIds: [], skills: skills @@ -54,6 +54,15 @@ export function mapJourneyExperience( }; } +export function mapOwnerJourneyExperience(record: JourneyRecord): Omit { + const experience = record.get("e").properties; + return { + ...mapJourneyExperience(record), + ...(experience.verificationStatus !== undefined && { verificationStatus: experience.verificationStatus }), + ...(experience.verificationMocked !== undefined && { verificationMocked: experience.verificationMocked }), + }; +} + export function attachExperienceGoals( experiences: Pick[], records: JourneyRecord[] diff --git a/backend/src/services/user.service.ts b/backend/src/services/user.service.ts index 2153eb0..889a2c0 100644 --- a/backend/src/services/user.service.ts +++ b/backend/src/services/user.service.ts @@ -1,7 +1,7 @@ import type { JourneyExperience, JourneyTransition } from "../processors/journey/journeySchema.js"; import type { JourneyGoal } from "../types/journey/Journey.types.js"; import { closeSession, getSession } from "./neo4j.service.js"; -import { attachExperienceGoals, mapJourneyExperience, mapJourneyGoal, mapJourneyTransition } from "./journeyMapping.js"; +import { attachExperienceGoals, mapOwnerJourneyExperience, mapJourneyGoal, mapJourneyTransition } from "./journeyMapping.js"; export interface UpdateProfileInput { clerkId: string; @@ -144,7 +144,7 @@ export async function getUserJourney( { clerkId } ); - const experiences = experiencesResult.records.map(mapJourneyExperience); + const experiences = experiencesResult.records.map(mapOwnerJourneyExperience); const goalRelationshipResult = await session.run( ` MATCH (u:User {clerkId: $clerkId})-[:HAS_EXPERIENCE]->(e:Experience)-[:CONTRIBUTED_TO]->(g:Goal) @@ -207,4 +207,4 @@ export async function updateUserSummary( } finally { await closeSession(session); } -} \ No newline at end of file +} diff --git a/backend/src/types/journey/GeminiJourneyDraft.types.ts b/backend/src/types/journey/GeminiJourneyDraft.types.ts index ae76be9..f72e138 100644 --- a/backend/src/types/journey/GeminiJourneyDraft.types.ts +++ b/backend/src/types/journey/GeminiJourneyDraft.types.ts @@ -16,5 +16,8 @@ export interface GeminiExperience { } export interface GeminiJourneyDraft { - experiences: GeminiExperience[]; -} \ No newline at end of file + experiences: (Partial<{ [K in keyof GeminiExperience]: GeminiExperience[K] | null }> & { + experienceNumber?: number; + })[]; + removeExperienceNumbers?: number[]; +} diff --git a/backend/src/types/journey/Journey.types.ts b/backend/src/types/journey/Journey.types.ts index 81b9127..4d366eb 100644 --- a/backend/src/types/journey/Journey.types.ts +++ b/backend/src/types/journey/Journey.types.ts @@ -25,7 +25,8 @@ export type SkillType = "Technical" | "Soft" | "Domain" | "ExtraCurricular"; export type ProofSourceType = "image" | "pdf" | "github" | "link"; -export type ProofStatus = "pending" | "verified" | "rejected" | "skipped"; +export type ProofStatus = "pending" | "verified" | "rejected" | "skipped" | "failed"; +export type ExperienceVerificationStatus = "pending" | "verified" | "rejected" | "failed"; export type ApplicationStatus = "accepted" | "rejected" | "waitlisted" | "pending"; @@ -61,7 +62,7 @@ export interface JourneySkill { export interface JourneyProof { id: string; sourceType: ProofSourceType; - url: string; + url: string | null; status: ProofStatus; verifiedAt?: string | null; reason?: string | null; @@ -79,6 +80,8 @@ export interface JourneyExperience { applicationStatus: ApplicationStatus | null; achievements: string[] | null; isVerified: boolean; + verificationStatus?: ExperienceVerificationStatus; + verificationMocked?: boolean; goalIds: string[]; skills: JourneySkill[]; proofs: JourneyProof[]; diff --git a/backend/src/types/journey/JourneySession.types.ts b/backend/src/types/journey/JourneySession.types.ts index 8ff6a88..d7344b7 100644 --- a/backend/src/types/journey/JourneySession.types.ts +++ b/backend/src/types/journey/JourneySession.types.ts @@ -1,3 +1,5 @@ +import type { PartialJourneyDraft } from "./PartialJourney.types.js"; + export interface JourneyMessage { role: "assistant" | "user"; content: string; @@ -19,8 +21,8 @@ export interface JourneySession { userId: string; state: JourneyState; conversationHistory: JourneyMessage[]; - journeyDraft: unknown | null; + journeyDraft: PartialJourneyDraft | null; currentExperienceIndex: number; createdAt: number; updatedAt: number; -} \ No newline at end of file +} diff --git a/backend/tests/journeyDraft.test.ts b/backend/tests/journeyDraft.test.ts new file mode 100644 index 0000000..ec02879 --- /dev/null +++ b/backend/tests/journeyDraft.test.ts @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { buildJourneyDraftPrompt } from "../src/prompts/onboarding/journeyDraft.prompt.js"; +import { applyJourneyDraftChanges } from "../src/processors/journey/finalizeJourneyDraft.processor.js"; + +const internship = { + title: "Engineering internship", + context: "Automated reporting with Python.", + timelineSummary: "Automated reporting during an internship.", + startDate: "06 2024", + endDate: "08 2024", + organization: "Cedar Labs", +}; + +test("chat corrections retain existing experience IDs, unrelated fields, goals and proofs", () => { + const initial = applyJourneyDraftChanges({ experiences: [internship, { ...internship, title: "Second role" }] }, []); + const first = { ...initial.experiences[0]!, goalIds: ["goal-1"], proofs: [{ + id: "proof-1", url: "https://example.test/proof", sourceType: "link" as const, status: "pending" as const, + }] }; + const second = initial.experiences[1]!; + const result = applyJourneyDraftChanges({ + experiences: [{ experienceNumber: 1, startDate: "07 2024", endDate: null, outcome: "Shipped a weekly report" }], + }, [first, second]); + + const { endDate, ...expected } = first; + assert.equal(endDate, "08 2024"); + assert.deepEqual(result.experiences, [{ ...expected, startDate: "07 2024", outcome: "Shipped a weekly report" }, second]); + assert.deepEqual(result.changedFields, { [first.id]: ["startDate", "endDate", "outcome"] }); +}); + +test("only explicit removals delete experiences and invalid corrections preserve the current draft", () => { + const initial = applyJourneyDraftChanges({ experiences: [internship] }, []).experiences; + const draft = applyJourneyDraftChanges({ + experiences: [{ experienceNumber: 5, title: "Unmatched correction" }, { experienceNumber: 1, startDate: "2024" }], + }, initial); + assert.deepEqual(draft.experiences, initial); + const revised = applyJourneyDraftChanges({ + experiences: [{ ...internship, title: "New role" }], removeExperienceNumbers: [1], + }, draft.experiences); + assert.equal(revised.experiences.length, 1); + assert.equal(revised.experiences[0]!.title, "New role"); + assert.notEqual(revised.experiences[0]!.id, initial[0]!.id); +}); + +test("a first message opens a draft even with incomplete extraction or a malformed optional field", () => { + const narrative = "I worked as an engineering intern at Cedar Labs in June 2024."; + const result = applyJourneyDraftChanges({ + experiences: [{ experienceNumber: 1, title: "Engineering internship", startDate: "06 2024", endDate: "ongoing" }], + }, [], narrative); + const experience = result.experiences[0]!; + assert.equal(experience.title, "Engineering internship"); + assert.equal(experience.startDate, "06 2024"); + assert.equal(experience.endDate, undefined); + assert.equal(experience.context, narrative); + assert.equal(experience.timelineSummary, narrative); +}); + +test("empty or failed extraction keeps the user's text in a starter draft and never overwrites an existing draft", () => { + const narrative = "I automated a weekly report."; + const initial = applyJourneyDraftChanges({ experiences: [] }, [], narrative); + assert.equal(initial.experiences[0]?.context, narrative); + assert.equal(initial.experiences[0]?.title, "Untitled experience"); + assert.deepEqual( + applyJourneyDraftChanges({ experiences: [] }, initial.experiences, "Change the date."), + initial, + ); + const recovered = applyJourneyDraftChanges({ + experiences: [{ title: "Automating weekly reports", startDate: "06 2024" }], + }, initial.experiences, narrative); + assert.equal(recovered.experiences.length, 1); + assert.equal(recovered.experiences[0]?.id, initial.experiences[0]?.id); + assert.equal(recovered.experiences[0]?.startDate, "06 2024"); +}); + +test("extraction prompt distinguishes the current draft, recent user turns and latest correction", () => { + const previous = { ...internship, id: "private-id", goalIds: ["goal-1"], proofs: [] }; + const prompt = JSON.parse(buildJourneyDraftPrompt("It started in July.", [previous], [ + { role: "user", content: "My internship", timestamp: 1 }, + { role: "assistant", content: "An assistant turn", timestamp: 2 }, + ])); + assert.deepEqual(prompt.currentDraft, [{ experienceNumber: 1, ...internship }]); + assert.deepEqual(prompt.recentMessages, ["My internship"]); + assert.equal(prompt.latestMessage, "It started in July."); +}); diff --git a/backend/tests/journeyMapping.test.ts b/backend/tests/journeyMapping.test.ts index ac8cf9d..7a32a89 100644 --- a/backend/tests/journeyMapping.test.ts +++ b/backend/tests/journeyMapping.test.ts @@ -5,6 +5,7 @@ import { attachExperienceGoals, mapJourneyExperience, mapJourneyGoal, + mapOwnerJourneyExperience, mapJourneyTransition, } from "../src/services/journeyMapping.js"; @@ -81,6 +82,23 @@ test("experience mapping retains existing optional values without replacing empt } }); +test("owner mapping retains persisted verification status without exposing mock verification publicly", () => { + const mocked = record({ + e: { properties: { ...experience, isVerified: false, verificationStatus: "verified", verificationMocked: true } }, + skills: [], + }); + const pending = record({ + e: { properties: { ...experience, isVerified: false, verificationStatus: "pending", verificationMocked: false } }, + skills: [], + }); + assert.equal(mapOwnerJourneyExperience(mocked).verificationStatus, "verified"); + assert.equal(mapOwnerJourneyExperience(mocked).verificationMocked, true); + assert.equal(mapJourneyExperience(mocked).isVerified, false); + assert.equal("verificationStatus" in mapJourneyExperience(mocked), false); + assert.equal("verificationMocked" in mapJourneyExperience(mocked), false); + assert.equal(mapOwnerJourneyExperience(pending).verificationStatus, "pending"); +}); + test("goal relationships attach to their experience while unlinked experiences remain empty", () => { const experiences = [ { id: "experience-2", goalIds: [] }, diff --git a/backend/tests/proofVerification.test.ts b/backend/tests/proofVerification.test.ts new file mode 100644 index 0000000..3d71660 --- /dev/null +++ b/backend/tests/proofVerification.test.ts @@ -0,0 +1,54 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { randomUUID } from "node:crypto"; +import { journeyProofSchema, submitExperienceSchema } from "../src/processors/journey/journeySchema.js"; + +process.env.GEMINI_API_KEY ??= "fixture"; +const { verifyProof } = await import("../src/processors/journey/verifyProof.processor.js"); +const { geminiClient } = await import("../src/config/gemini.config.js"); + +const experience = submitExperienceSchema.parse({ + id: randomUUID(), title: "Software internship", context: "Built a reporting tool", + timelineSummary: "Built a reporting tool", startDate: "06 2024", goalIds: [], isVerified: false, +}); +const github = { id: "github-proof", sourceType: "github", url: "https://github.com/example/reporting/commit/abcdef" } as const; + +test("missing uploads and unsupported links return persistable, unverified results", async () => { + const missing = await verifyProof(experience, { id: "file", sourceType: "pdf" }, null); + assert.equal(missing.status, "rejected"); + assert.equal(missing.url, null); + assert.equal(journeyProofSchema.safeParse(missing).success, true); + const unsupported = await verifyProof(experience, { ...github, sourceType: "link" }, null); + assert.equal(unsupported.status, "skipped"); + assert.equal(unsupported.verifiedAt, null); +}); + +test("inline verification distinguishes a valid verdict from missing evidence and processing errors", async t => { + let httpStatus = 200; + let verdict = '{"status":"verified","reason":"The commit supports the claim."}'; + t.mock.method(globalThis, "fetch", async () => new Response( + JSON.stringify({ commit: { message: "Add reporting tool" } }), { status: httpStatus }, + )); + t.mock.method(geminiClient, "getGenerativeModel", () => ({ + async generateContent() { + return { response: { text: () => verdict } }; + }, + })); + + const verified = await verifyProof(experience, github, null); + assert.equal(verified.status, "verified"); + assert.ok(verified.verifiedAt); + + verdict = '{"status":"rejected","reason":"The evidence does not support the claim."}'; + assert.equal((await verifyProof(experience, github, null)).status, "rejected"); + + verdict = '{"status":"unknown","reason":"Invalid response."}'; + const failed = await verifyProof(experience, github, null); + assert.equal(failed.status, "failed"); + assert.equal(failed.verifiedAt, null); + + httpStatus = 404; + assert.equal((await verifyProof(experience, github, null)).status, "rejected"); + httpStatus = 503; + assert.equal((await verifyProof(experience, github, null)).status, "failed"); +}); diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 7ab6886..a6aed34 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -20,8 +20,8 @@ Users begin onboarding with a prompt asking them to describe their career or ent ``` "I started as a System Engineer at TCS, but I wanted to move into product engineering. Over the next four months I focused on system design, built a distributed error tracking platform, and eventually secured a backend role at Vercel." ``` -* **Conversational Context**: Each submitted message is stored in the onboarding session. The extractor receives only the latest message, not the stored conversation history; the current processor returns a draft rather than an AI follow-up question. -* **Session Persistence**: **Upstash Redis** retains session history and the latest draft for 24 hours. Storing history does not itself make extraction context-aware. +* **Conversational Context**: The extractor receives the current draft, the eight most recent user messages, and the latest message. Follow-up turns return field updates, additions, or explicit removals. The server applies those changes to the existing draft and keeps experience IDs stable. +* **Session Persistence**: **Upstash Redis** retains session history and the latest draft for 24 hours. In the desktop form, direct edits and proof attachments stay local until submission. Chat updates replace only the affected draft fields. --- @@ -53,7 +53,7 @@ The submitted narrative is sent to the **Gemini structured extractor**. Voice in ``` * **Draft Verification UI**: The extracted draft is sent to the client. The user reviews the experience cards inside the Expo App form, modifies dates, associates goals, and adds verification links. * **Editable Journey Forms**: The generated draft is automatically populated into Goal and Experience forms inside the Expo application. Users can review, modify, or enrich the extracted information before submission. -* **Proof Attachment**: Users can add GitHub, PDF or image proof metadata. The current multipart endpoint accepts one uploaded file named `proof`; it does not accept independent uploaded files for every proof. Verification happens before experiences are persisted in Neo4j. +* **Proof Attachment**: The multipart endpoint accepts one uploaded file named `proof` up to 10 MB. The inline verifier checks GitHub, PDF, and supported image evidence before saving experiences. Missing or unsupported evidence can be saved without verification. Provider or processing failures are distinct from an unsuccessful check in the owner's desktop Journey. Desktop mock verification skips analysis and saves an owner-only Verified result. --- diff --git a/frontend/api/journey.api.ts b/frontend/api/journey.api.ts index f598ecf..499a604 100644 --- a/frontend/api/journey.api.ts +++ b/frontend/api/journey.api.ts @@ -15,6 +15,8 @@ export interface JourneyExperience { applicationStatus: string | null; achievements: string[]; isVerified: boolean; + verificationStatus?: 'pending' | 'verified' | 'rejected' | 'failed'; + verificationMocked?: boolean; goalIds: string[]; skills: { name: string; type: string | null }[]; proofs: { id: string; sourceType: string; url?: string; localUri?: string; status: string; verifiedAt: string | null; reason: string | null; filename?: string; mimeType?: string }[]; @@ -74,6 +76,8 @@ export interface StartJourneyResponse { export interface SendMessageResponse { success: boolean; conversationId: string; + changedFields?: Record; + extractionUnavailable?: boolean; journeyDraft: { goals: JourneyGoal[]; experiences: any[]; @@ -175,29 +179,22 @@ export async function submitJourney( const response = await fetch(file.uri); const blob = await response.blob(); - formData.append("proof", blob, file.name); + formData.append("proof", blob.type ? blob : blob.slice(0, blob.size, file.type), file.name); } else { const uploadFile = new File(file.uri); formData.append("proof", uploadFile, file.name); } - const response = await fetch( - `${process.env.EXPO_PUBLIC_API_BASE_URL}/journey/submit`, + return apiFetch( + "/journey/submit", { method: "POST", - headers: { - Authorization: `Bearer ${token}`, - }, body: formData, - } + }, + token, + true, ); - - if (!response.ok) { - throw new Error(await response.text()); - } - - return response.json(); } return apiFetch( @@ -213,4 +210,4 @@ export async function submitJourney( }, token ); -} \ No newline at end of file +} diff --git a/frontend/app/(tabs)/journey.tsx b/frontend/app/(tabs)/journey.tsx index b71e67c..d6cd02b 100644 --- a/frontend/app/(tabs)/journey.tsx +++ b/frontend/app/(tabs)/journey.tsx @@ -198,6 +198,7 @@ export default function JourneyPage() { journey={journey} imageUrl={clerkUser?.hasImage ? clerkUser.imageUrl : undefined} onViewGraph={() => setShowGraph(true)} + onRefresh={loadJourney} /> ) : <> {/* Header */} diff --git a/frontend/app/share-journey.tsx b/frontend/app/share-journey.tsx index 524c240..280c2b0 100644 --- a/frontend/app/share-journey.tsx +++ b/frontend/app/share-journey.tsx @@ -2,7 +2,7 @@ import { useState, useRef, useEffect } from 'react'; import { View, Text, FlatList, TextInput, TouchableOpacity, KeyboardAvoidingView, Platform, - ActivityIndicator, Alert, SafeAreaView, ScrollView, Modal + ActivityIndicator, Alert, SafeAreaView, ScrollView, Modal, Switch } from 'react-native'; import { useRouter } from 'expo-router'; import { useAuth } from '@clerk/clerk-expo'; @@ -12,6 +12,9 @@ import { Feather } from '@expo/vector-icons'; import Animated, { FadeIn, FadeInDown, FadeInUp, Layout } from 'react-native-reanimated'; import * as ImagePicker from 'expo-image-picker'; import * as DocumentPicker from 'expo-document-picker'; +import { useDesktopLayout } from '../utils/useDesktopLayout'; +import { DesktopExperienceChat } from '../components/desktop/DesktopExperienceChat'; +import { DesktopButton } from '../components/desktop/DesktopUI'; interface ChatMessage { id: string; @@ -22,6 +25,8 @@ interface ChatMessage { export default function ShareJourneyPage() { const router = useRouter(); const { getToken } = useAuth(); + const desktop = useDesktopLayout(); + const [mockVerification, setMockVerification] = useState(false); const displayAlert = (title: string, message: string, onPress?: () => void) => { if (Platform.OS === 'web') { @@ -44,12 +49,18 @@ export default function ShareJourneyPage() { const [isLoading, setIsLoading] = useState(false); const [isInitializing, setIsInitializing] = useState(true); + const [sessionError, setSessionError] = useState(null); + const [sessionAttempt, setSessionAttempt] = useState(0); + const [draftNotice, setDraftNotice] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const [journeyDraft, setJourneyDraft] = useState(null); const [editableExperiences, setEditableExperiences] = useState([]); const [userGoals, setUserGoals] = useState([]); const flatListRef = useRef(null); + const sendingMessage = useRef(false); + const messageSequence = useRef(0); + const hasOpenedDraft = useRef(false); const [newGoalTitle, setNewGoalTitle] = useState(''); const [newGoalDesc, setNewGoalDesc] = useState(''); @@ -164,38 +175,45 @@ export default function ShareJourneyPage() { useEffect(() => { async function initSession() { + setIsInitializing(true); + setSessionError(null); try { const token = await getToken(); if (!token) throw new Error('Unauthenticated'); - try { - const journeyData = await getUserJourney(token); - if (journeyData && journeyData.goals) { - setUserGoals(journeyData.goals); - } - } catch (e) { - console.warn('Failed to load existing goals:', e); - } - const res = await startJourneySession(token); if (res.success && res.conversationId) { setConversationId(res.conversationId); setMessages([{ id: Date.now().toString(), text: res.message, sender: 'ai' }]); + void getUserJourney(token).then(({ goals }) => { + setUserGoals(current => { + const byId = new Map(goals.map(goal => [goal.id, goal])); + for (const goal of current) byId.set(goal.id, goal); + return [...byId.values()]; + }); + }).catch(error => console.warn('Failed to load existing goals:', error)); + } else { + throw new Error('No journey session returned'); } } catch (err) { console.warn('Failed to start journey session', err); + setSessionError(err instanceof Error && err.message === 'Unauthenticated' + ? 'Sign in to start an experience.' + : 'Could not start the chat. Try again.'); } finally { setIsInitializing(false); } } initSession(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [sessionAttempt]); - const sendMessage = async () => { - if (!inputText.trim() || !conversationId) return; - const userText = inputText; - const userMsg: ChatMessage = { id: Date.now().toString(), text: userText, sender: 'user' }; + const sendMessage = async (text: string) => { + const userText = text.trim(); + if (!userText || !conversationId || sendingMessage.current || isSubmitting) return; + sendingMessage.current = true; + const turn = ++messageSequence.current; + const userMsg: ChatMessage = { id: `user-${turn}`, text: userText, sender: 'user' }; setMessages(prev => [...prev, userMsg]); setInputText(''); @@ -208,22 +226,62 @@ export default function ShareJourneyPage() { const res = await sendJourneyMessage(token, conversationId, userText); if (res.success) { + const experiences = res.journeyDraft.experiences; + const firstDraft = !editableExperiences.length && experiences.length > 0; + const notice = res.extractionUnavailable + ? firstDraft + ? 'Automatic fill took too long or was unavailable. Your message is in the description. Fill in the remaining fields or try again in chat.' + : 'Automatic fill was unavailable. Your draft is still saved. You can retry your message or edit the form.' + : firstDraft && experiences.some(experience => experience.title === 'Untitled experience') + ? 'Your message is in the description. Add a title and fill in the remaining details.' + : null; + setDraftNotice(notice); + if (res.extractionUnavailable && !firstDraft) setInputText(userText); + const draftChanged = !res.changedFields || + Object.values(res.changedFields).some(fields => fields.length > 0) || + experiences.length !== editableExperiences.length || + experiences.some(experience => !editableExperiences.some(current => current.id === experience.id)); setJourneyDraft(res.journeyDraft); - setEditableExperiences(res.journeyDraft?.experiences || []); - setUserGoals(res.journeyDraft?.goals || []); + setEditableExperiences(current => { + const currentById = new Map(current.map(experience => [experience.id, experience])); + return experiences.map(experience => { + const edited = currentById.get(experience.id); + if (!edited || !res.changedFields) return experience; + const updated = { ...edited }; + for (const field of res.changedFields[experience.id] ?? []) { + updated[field] = experience[field]; + } + return updated; + }); + }); + setUserGoals(current => { + const goals = new Map(current.map(goal => [goal.id, goal])); + for (const goal of res.journeyDraft.goals) goals.set(goal.id, goal); + return [...goals.values()]; + }); setMessages(prev => [...prev, { - id: Date.now().toString(), + id: `assistant-${turn}`, sender: 'ai', - text: "Got it! I've updated your journey draft. Keep telling me more, or switch to the Form view when you're ready to review." + text: notice ?? (experiences.length + ? draftChanged + ? 'I updated your draft. You can keep chatting or review the changes in the form.' + : 'The draft is unchanged. Name the experience and tell me what you want to update.' + : 'There are no experiences in the draft. You can describe another one here.'), }]); - setActiveTab('form'); + if (experiences.length && (!desktop || !hasOpenedDraft.current)) { + hasOpenedDraft.current = true; + setActiveTab('form'); + } } else { throw new Error("Failed to process message"); } } catch (err: any) { console.warn('Failed to send message:', err); + setMessages(prev => prev.filter(message => message.id !== userMsg.id)); + setInputText(current => current || userText); displayAlert("Error", "Could not process your message. Please try again."); } finally { + sendingMessage.current = false; setIsLoading(false); } }; @@ -239,7 +297,7 @@ export default function ShareJourneyPage() { const token = await getToken(); if (!token) throw new Error("Not authenticated"); - const payload = { ...journeyDraft, experiences: editableExperiences }; + const payload = { ...journeyDraft, ...(desktop ? { mockVerification } : {}) }; // Extract files to upload let fileToUpload: | { id: string; uri: string; name: string; type: string; } | undefined; @@ -247,9 +305,13 @@ export default function ShareJourneyPage() { const { tempGoalInput, ...cleanedExp } = exp; // Convert empty decisionReason to null cleanedExp.decisionReason = cleanedExp.decisionReason?.trim() || null; + cleanedExp.endDate = cleanedExp.endDate?.trim() || null; if (cleanedExp.proofs) { cleanedExp.proofs = cleanedExp.proofs.map((p: any) => { if (p.localUri) { + if (desktop && fileToUpload) { + throw new Error('Attach up to one photo or document per submission.'); + } fileToUpload = { id: p.id, uri: p.localUri, @@ -270,9 +332,13 @@ export default function ShareJourneyPage() { const res = await submitJourney(token, conversationId, payload, fileToUpload); if (res.success) { + if (desktop) { + router.replace('/(tabs)/journey'); + return; + } displayAlert( "Journey Saved! 🚀", - "Your experiences have been verified and added to your Life Graph.", + "Your experiences have been added to your Life Graph.", () => router.replace('/(tabs)/journey') ); } else { @@ -330,9 +396,13 @@ export default function ShareJourneyPage() { return ( - - Review & Edit Draft - + + + Review & Edit Draft + + {desktop && setActiveTab('chat')} />} + + {draftNotice && {draftNotice}} {/* Goal Form Section */} @@ -378,7 +448,7 @@ export default function ShareJourneyPage() { {experiences.map((exp: any, index: number) => ( + {desktop && ( + + Organization + updateExperience(index, 'organization', value.trim() ? value : null)} + placeholder="Organization name" + placeholderTextColor="#94A3B8" + /> + + )} + Associated Goal @@ -499,6 +582,32 @@ export default function ShareJourneyPage() { textAlignVertical="top" /> + {desktop && ( + + Application status + + {(['accepted', 'rejected', 'waitlisted', 'pending'] as const).map(status => ( + updateExperience(index, 'applicationStatus', exp.applicationStatus === status ? null : status)} + style={{ paddingHorizontal: 12, paddingVertical: 8, borderRadius: 16, backgroundColor: exp.applicationStatus === status ? L.teal : '#F1F5F9' }} + > + {status} + + ))} + + {exp.achievements?.length > 0 && ( + + Achievements + {exp.achievements.map((achievement: string, index: number) => ( + • {achievement} + ))} + + )} + + )} What led you to this experience? ))} + {desktop && ( + + + + Mock verification + + Turning this on skips the verification check and shows Verified only in your desktop Journey. With it off, proof is checked when you submit. + + + + )} + {isSubmitting ? ( - + + + {desktop && {mockVerification ? 'Saving…' : 'Checking proof and saving…'}} + ) : ( Approve & Submit Journey @@ -628,6 +758,7 @@ export default function ShareJourneyPage() { }}> setActiveTab('chat')} + disabled={isSubmitting} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, paddingVertical: 8, paddingHorizontal: 16, @@ -687,9 +818,27 @@ export default function ShareJourneyPage() { + ) : desktop && sessionError ? ( + + {sessionError} + {sessionError === 'Sign in to start an experience.' + ? router.replace('/')} /> + : setSessionAttempt(attempt => attempt + 1)} />} + ) : ( - {activeTab === 'chat' ? ( + {activeTab === 'chat' && desktop && conversationId ? ( + setActiveTab('form')} + hasDraft={editableExperiences.length > 0} + busy={isLoading || isSubmitting} + /> + ) : activeTab === 'chat' ? ( messages.length <= 1 ? ( @@ -710,7 +859,7 @@ export default function ShareJourneyPage() { editable={!isLoading} /> sendMessage(inputText)} disabled={isLoading || !inputText.trim()} style={{ position: 'absolute', top: 14, right: 14, width: 34, height: 34, borderRadius: 17, justifyContent: 'center', alignItems: 'center', backgroundColor: inputText.trim() ? '#D06757' : '#F1F5F9', }}> sendMessage(inputText)} disabled={isLoading || !inputText.trim()} > @@ -805,4 +954,4 @@ export default function ShareJourneyPage() { ); -} \ No newline at end of file +} diff --git a/frontend/components/desktop/DesktopExperienceChat.tsx b/frontend/components/desktop/DesktopExperienceChat.tsx new file mode 100644 index 0000000..0a2be21 --- /dev/null +++ b/frontend/components/desktop/DesktopExperienceChat.tsx @@ -0,0 +1,118 @@ +import { useRef } from 'react'; +import { ActivityIndicator, FlatList, StyleSheet, Text, TextInput, View } from 'react-native'; +import { L } from '../../constants/colors'; +import { DesktopButton } from './DesktopUI'; + +const samples = [ + { + title: 'Software internship', + text: 'From June 2024 to August 2024, I was a backend engineering intern at Cedar Labs. I used Python and PostgreSQL to automate a weekly reporting job. Duplicate records were making the reports unreliable, so I added validation and reconciliation. The job shipped to the operations team and cut reporting time from four hours to one.', + }, + { + title: 'Hackathon project', + text: 'In February 2025, I joined the River City Hackathon because I wanted to help volunteers find open food pantry shifts. I built the scheduling interface with React and TypeScript. The challenge was handling overlapping shifts without confusing users. We demoed a working prototype and placed second out of 24 teams.', + }, + { + title: 'Graduate application', + text: 'I applied to the data science master’s program at Lakeview University from October 2024 to March 2025. I wanted to study how public transit data could inform city planning. The hardest part was explaining a career change in my statement. I used technical writing and data visualization to explain my portfolio. I was waitlisted in March 2025.', + }, + { + title: 'Research assistantship', + text: 'From January 2025 to September 2025, I was a research assistant at Meridian Institute. I used R and statistics to study how tree cover affects neighborhood temperatures. Missing sensor readings made it difficult to compare sites. I built a reproducible cleaning workflow, and our team presented a poster at the institute’s research symposium.', + }, + { + title: 'Career pivot', + text: 'From March 2023 to May 2024, I was a customer support specialist at Harbor Tools. Repeat billing questions were our biggest problem. I used customer interviewing and SQL to identify the three most common issues, and our new help articles reduced repeat billing tickets by 20%. Seeing how many tickets came from confusing onboarding made me move into product operations at Harbor Tools in June 2024. I used process mapping to redesign onboarding handoffs and cut average setup time from six days to four. I am still in that role.', + }, +]; + +interface Props { + messages: { id: string; text: string; sender: 'user' | 'ai' }[]; + helperMessage: string; + input: string; + onChangeInput: (value: string) => void; + onSend: (value: string) => void; + onReview: () => void; + hasDraft: boolean; + busy: boolean; +} + +export function DesktopExperienceChat({ messages, helperMessage, input, onChangeInput, onSend, onReview, hasDraft, busy }: Props) { + const list = useRef>(null); + return ( + + + + Add Experience + + {hasDraft ? 'Send a correction, add details, or describe another experience.' : 'Describe what you did, when it happened, and what came out of it.'} + + + {hasDraft && } + + message.id} + style={{ flex: 1 }} + contentContainerStyle={styles.messages} + onContentSizeChange={() => { if (messages.length) list.current?.scrollToEnd({ animated: true }); }} + ListEmptyComponent={ + + {!!helperMessage && {helperMessage.trim()}} + + Try a sample + Choose a fictional example to send it to the chat. + + {samples.map(sample => ( + onSend(sample.text)} /> + ))} + + + + } + renderItem={({ item }) => ( + + {item.text} + + )} + /> + {busy && + + Updating your draft… + } + + + onSend(input)} /> + + + ); +} + +const styles = StyleSheet.create({ + chat: { flex: 1, width: '100%', maxWidth: 840, alignSelf: 'center', paddingHorizontal: 28, paddingVertical: 20, gap: 14 }, + heading: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 16 }, + headingCopy: { flex: 1, gap: 4 }, + title: { color: L.navy, fontFamily: 'Manrope_700Bold', fontSize: 30 }, + description: { color: '#53675D', fontSize: 14, lineHeight: 21, fontFamily: 'Inter_400Regular' }, + messages: { gap: 12, paddingBottom: 8 }, + samples: { gap: 8, padding: 18, backgroundColor: '#EDF3EF', borderColor: '#D4E1DB', borderWidth: 1, borderRadius: 14 }, + label: { color: L.navy, fontSize: 15, fontFamily: 'Manrope_700Bold' }, + sampleButtons: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginTop: 4 }, + bubble: { alignSelf: 'flex-start', maxWidth: '88%', backgroundColor: '#E7F0EA', padding: 13, borderRadius: 14 }, + userBubble: { alignSelf: 'flex-end', backgroundColor: L.navy }, + bubbleText: { color: L.navy, fontSize: 14, lineHeight: 22, fontFamily: 'Inter_400Regular' }, + userText: { color: '#fff' }, + progress: { flexDirection: 'row', gap: 8, alignItems: 'center' }, + composer: { flexDirection: 'row', alignItems: 'flex-end', gap: 12, padding: 12, backgroundColor: '#fff', borderWidth: 1, borderColor: '#D4E1DB', borderRadius: 14 }, + input: { flex: 1, minHeight: 58, maxHeight: 132, padding: 8, color: L.navy, fontSize: 15, lineHeight: 22, fontFamily: 'Inter_400Regular', textAlignVertical: 'top' }, +}); diff --git a/frontend/components/desktop/DesktopJourney.tsx b/frontend/components/desktop/DesktopJourney.tsx index 13aba14..afdebf0 100644 --- a/frontend/components/desktop/DesktopJourney.tsx +++ b/frontend/components/desktop/DesktopJourney.tsx @@ -6,6 +6,13 @@ import { calculateDuration, formatToMonthYear } from '../../utils/helpers'; import { L } from '../../constants/colors'; import { DesktopAvatar, DesktopBadge, DesktopButton, DesktopChips, DesktopHeading, DesktopPage, DesktopSectionTitle, desktopStyles as d } from './DesktopUI'; +const verificationLabels = { + pending: 'Pending', + verified: 'Verified', + rejected: 'Not verified', + failed: 'Verification failed', +} as const; + function GoalCard({ goal }: { goal: JourneyGoal }) { const [expanded, setExpanded] = useState(false); const ongoing = ['ONGOING', 'ACTIVE'].includes(goal.status?.toUpperCase()); @@ -37,6 +44,7 @@ function Field({ label, value }: { label: string; value?: string | null }) { function ExperienceCard({ experience: exp, journey }: { experience: JourneyExperience; journey: UserJourneyResponse }) { const [expanded, setExpanded] = useState(false); + const verificationStatus = exp.verificationStatus ?? (exp.isVerified ? 'verified' : undefined); const transition = journey.transitions.find(t => t.toExperienceId === exp.id); const previous = transition ? journey.experiences.find(e => e.id === transition.fromExperienceId) : null; const linkedGoals = (exp.goalIds || []).map(id => journey.goals.find(g => g.id === id)?.title).filter((title): title is string => !!title); @@ -52,7 +60,13 @@ function ExperienceCard({ experience: exp, journey }: { experience: JourneyExper {exp.title} {exp.organization || 'TechNova Global'} - {exp.isVerified && } + {verificationStatus && ( + + )} {!expanded && !!exp.timelineSummary && {exp.timelineSummary}} @@ -80,11 +94,14 @@ function ExperienceCard({ experience: exp, journey }: { experience: JourneyExper ; } -export function DesktopJourney({ journey, imageUrl, onViewGraph }: { journey: UserJourneyResponse; imageUrl?: string; onViewGraph: () => void }) { +export function DesktopJourney({ journey, imageUrl, onViewGraph, onRefresh }: { journey: UserJourneyResponse; imageUrl?: string; onViewGraph: () => void; onRefresh: () => void }) { const { width } = useWindowDimensions(); return } /> + action={ + + + } /> diff --git a/frontend/components/landing/desktopLanding.css b/frontend/components/landing/desktopLanding.css index 063b196..72fa3de 100644 --- a/frontend/components/landing/desktopLanding.css +++ b/frontend/components/landing/desktopLanding.css @@ -51,7 +51,7 @@ align-items: center; gap: 34px; color: #e3e5eb; - font-size: 14px; + font-size: 16px; } .pf-landing .continuity .links a:hover { color: #ff9652; @@ -101,6 +101,7 @@ background: #ff6900; color: white; font-size: 15px; + letter-spacing: inherit; line-height: 24px; font-weight: 400; } @@ -113,8 +114,8 @@ height: 25px; } .pf-landing .continuity .legal { - font-size: 11px; - line-height: 17px; + font-size: 12px; + line-height: 18px; color: #acb3c0; margin-top: 12px; } @@ -132,7 +133,6 @@ font-size: clamp(23px, 1.81vw, 30px); font-weight: 400; line-height: 1.19; - letter-spacing: -0.02em; } .pf-landing .continuity .journey ol { list-style: none; @@ -189,14 +189,13 @@ } .pf-landing .continuity .stage { font-family: ArchivoNarrow_400Regular, Arial, sans-serif; - font-size: 14px; + font-size: 15px; line-height: 19px; font-weight: 400; - letter-spacing: -0.018em; } .pf-landing .continuity .quote { - font-size: 13px; - line-height: 18px; + font-size: 15px; + line-height: 21px; color: #56616a; margin-top: 2px; } @@ -228,7 +227,6 @@ 400 16px/1.65 ArchivoNarrow_400Regular, Arial, sans-serif; - letter-spacing: normal; text-align: left; color-scheme: light; } @@ -300,7 +298,7 @@ } .pf-story .st-label { font: - 400 11px/1.4 ArchivoNarrow_700Bold, + 400 13px/1.4 ArchivoNarrow_700Bold, Arial, sans-serif; letter-spacing: 0.14em; @@ -313,20 +311,18 @@ 400 clamp(30px, 3vw, 46px)/1.15 ArchivoNarrow_700Bold, Arial, sans-serif; - letter-spacing: -0.03em; max-width: 24ch; text-wrap: balance; } .pf-story .st-copy { color: var(--st-muted); - font-size: 15px; + font-size: 16px; line-height: 1.75; margin-top: 18px; max-width: 59ch; } .pf-story .st-comparison h3 { font-size: 19px; - letter-spacing: -0.02em; line-height: 1.3; margin: 0 0 20px; } @@ -359,7 +355,7 @@ line-height: 1.5; } .pf-story .st-platform small { - font-size: 10px; + font-size: 13px; color: var(--st-muted); } .pf-story .st-merge { @@ -396,7 +392,7 @@ .pf-story .st-unified { padding: 18px 20px 17px; background: var(--st-orange); - color: var(--st-navy); + color: #fff; border-radius: 11px; } .pf-story .st-unified h4 { @@ -406,7 +402,6 @@ font-weight: 400; font-size: 20px; line-height: 1.2; - letter-spacing: -0.02em; } .pf-story .st-unified h4 svg { width: 20px; @@ -424,7 +419,7 @@ border: 1px solid #8e3d0080; padding: 3px 9px; border-radius: 20px; - font-size: 11px; + font-size: 13px; font-weight: 400; line-height: 1.4; } @@ -444,7 +439,7 @@ gap: 12px; padding: 13px 0; border-bottom: 1px solid var(--st-border); - font-size: 15px; + font-size: 16px; line-height: 1.6; } .pf-story .st-question-list li:before { @@ -497,13 +492,13 @@ height: 19px; } .pf-story .st-step-list b { - font-size: 14px; + font-size: 15px; display: block; line-height: 1.5; } .pf-story .st-step-list p { color: #456154; - font-size: 12px; + font-size: 14px; line-height: 1.5; max-width: 19ch; margin: 4px 0 0; @@ -528,7 +523,7 @@ max-width: 19ch; } .pf-story .st-trust-community .st-copy { - font-size: 14px; + font-size: 16px; max-width: 51ch; } .pf-story .st-trust-note { @@ -546,13 +541,13 @@ } .pf-story .st-trust-note p { color: var(--st-muted); - font-size: 12px; + font-size: 14px; max-width: 42ch; } .pf-story .st-trust-note b { display: block; color: #355848; - font-size: 12px; + font-size: 14px; margin-bottom: 3px; } .pf-story .st-network { @@ -569,7 +564,7 @@ display: flex; align-items: center; gap: 6px; - font-size: 11px; + font-size: 13px; font-weight: 400; color: #49524d; } @@ -594,7 +589,7 @@ } .pf-story .st-langs li { font: - 400 14px/1.4 ArchivoNarrow_400Regular, + 400 15px/1.4 ArchivoNarrow_400Regular, 'Nirmala UI', Arial, sans-serif; @@ -628,10 +623,10 @@ height: 17px; } .pf-story .st-a11y-feature b { - font-size: 15px; + font-size: 16px; } .pf-story .st-a11y-feature p { - font-size: 13px; + font-size: 15px; color: var(--st-muted); line-height: 1.55; margin-top: 3px; @@ -665,7 +660,6 @@ 400 clamp(32px, 3.4vw, 52px)/1.15 ArchivoNarrow_700Bold, Arial, sans-serif; - letter-spacing: -0.03em; color: #f9f6ef; max-width: 36ch; } @@ -720,7 +714,7 @@ } .pf-story .st-tech { flex-basis: 100%; - font-size: 10px; + font-size: 12px; color: #a0a5af; } .pf-story .st-contact { @@ -767,6 +761,7 @@ min-height: 0; overflow-y: auto; font-family: ArchivoNarrow_400Regular, Arial, sans-serif; + letter-spacing: 0.015em; color: #152238; background: #faf9f6; } diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 00386ce..44ade40 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -3244,21 +3244,6 @@ "license": "MIT", "peer": true }, - "node_modules/@clerk/clerk-js/node_modules/jayson/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/@clerk/clerk-js/node_modules/jayson/node_modules/ws": { "version": "7.5.11", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz", @@ -5102,21 +5087,6 @@ "node": "^20.19.4 || ^22.13.0 || ^24.3.0 || >= 25.0.0" } }, - "node_modules/@react-native/dev-middleware/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/@react-native/dev-middleware/node_modules/ws": { "version": "7.5.12", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.12.tgz", @@ -9784,21 +9754,6 @@ "hermes-estree": "0.35.0" } }, - "node_modules/metro/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/metro/node_modules/ws": { "version": "7.5.12", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.12.tgz", @@ -10691,21 +10646,6 @@ "ws": "^7" } }, - "node_modules/react-devtools-core/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/react-devtools-core/node_modules/ws": { "version": "7.5.11", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz", @@ -11377,21 +11317,6 @@ "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", "license": "MIT" }, - "node_modules/react-native/node_modules/utf-8-validate": { - "version": "5.0.10", - "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", - "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/react-native/node_modules/ws": { "version": "7.5.11", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz", From 69b53a6ada9d4ff41c0efb4786be5b3775f4f635 Mon Sep 17 00:00:00 2001 From: Rohita Date: Sat, 14 Nov 2026 11:33:49 +0530 Subject: [PATCH 2/3] feat(journey): sort experiences newest first and complete ongoing items --- backend/src/controllers/user.controller.ts | 34 ++++++++- backend/src/routes/user.routes.ts | 5 +- backend/src/services/user.service.ts | 45 ++++++++++++ frontend/api/journey.api.ts | 10 +++ frontend/app/(tabs)/journey.tsx | 35 +++++++-- .../components/desktop/DesktopJourney.tsx | 21 ++++-- frontend/components/journey/EndDateAction.tsx | 72 +++++++++++++++++++ .../components/journey/ExpandableCards.tsx | 13 +++- frontend/tests/journey-graph.test.mjs | 19 +++++ frontend/utils/helpers.ts | 13 +++- 10 files changed, 249 insertions(+), 18 deletions(-) create mode 100644 frontend/components/journey/EndDateAction.tsx diff --git a/backend/src/controllers/user.controller.ts b/backend/src/controllers/user.controller.ts index 1bcb70e..59ce515 100644 --- a/backend/src/controllers/user.controller.ts +++ b/backend/src/controllers/user.controller.ts @@ -1,5 +1,6 @@ import type { Request, Response } from "express"; -import { updateProfile, getUserJourney, } from "../services/user.service.js"; +import { updateProfile, getUserJourney, completeJourneyItem } from "../services/user.service.js"; +import { toNeo4jDate } from "../utils/helper.js"; export async function updateProfileController( req: Request, @@ -43,4 +44,33 @@ export async function getJourneyController( error: message, }); } -} \ No newline at end of file +} + +export async function completeJourneyItemController(req: Request, res: Response): Promise { + const { kind, id } = req.params; + const endDate = req.body?.endDate; + if ((kind !== "experience" && kind !== "goal") || typeof id !== "string" || !id) { + res.status(400).json({ error: "Choose an experience or goal." }); + return; + } + if (typeof endDate !== "string" || !/^(0[1-9]|1[0-2]) [1-9]\d{3}$/.test(endDate)) { + res.status(400).json({ error: "Enter the end date in MM YYYY format." }); + return; + } + + try { + const result = await completeJourneyItem(req.userId, kind, id, toNeo4jDate(endDate)); + if (!result) { + res.status(404).json({ error: "Journey item not found." }); + } else if (result.outcome === "completed") { + res.status(409).json({ error: "This item is already closed. Refresh your Journey to see its latest status." }); + } else if (result.outcome === "invalid-date") { + res.status(400).json({ error: "The end date must be on or after the start month." }); + } else { + res.json({ endDate: result.endDate, status: result.status }); + } + } catch (error) { + console.error("Could not complete journey item", error); + res.status(500).json({ error: "Could not save the end date." }); + } +} diff --git a/backend/src/routes/user.routes.ts b/backend/src/routes/user.routes.ts index 5007963..f11407c 100644 --- a/backend/src/routes/user.routes.ts +++ b/backend/src/routes/user.routes.ts @@ -1,11 +1,12 @@ import { Router } from "express"; import { requireAuth } from "../middleware/auth.middleware.js"; -import { updateProfileController, getJourneyController, } from "../controllers/user.controller.js"; +import { updateProfileController, getJourneyController, completeJourneyItemController } from "../controllers/user.controller.js"; const router = Router(); router.patch("/profile", requireAuth, updateProfileController); router.get("/journey", requireAuth, getJourneyController); +router.patch("/journey/:kind/:id/end-date", requireAuth, completeJourneyItemController); -export default router; \ No newline at end of file +export default router; diff --git a/backend/src/services/user.service.ts b/backend/src/services/user.service.ts index 889a2c0..32937c1 100644 --- a/backend/src/services/user.service.ts +++ b/backend/src/services/user.service.ts @@ -140,6 +140,7 @@ export async function getUserJourney( MATCH (u:User {clerkId: $clerkId})-[:HAS_EXPERIENCE]->(e:Experience) OPTIONAL MATCH (e)-[:BUILT_SKILL]->(s:Skill) RETURN e, collect(DISTINCT s) AS skills + ORDER BY e.startDate DESC, e.id `, { clerkId } ); @@ -181,6 +182,50 @@ export async function getUserJourney( } } +export async function completeJourneyItem( + clerkId: string, + kind: "experience" | "goal", + id: string, + endDate: string, +) { + const session = getSession(); + const relationship = kind === "goal" ? "HAS_GOAL" : "HAS_EXPERIENCE"; + const label = kind === "goal" ? "Goal" : "Experience"; + try { + // Lock the item before checking its end date so simultaneous saves cannot overwrite it. + const result = await session.run( + ` + MATCH (:User {clerkId: $clerkId})-[:${relationship}]->(item:${label} {id: $id}) + SET item._completionLock = true + REMOVE item._completionLock + WITH item, date($endDate) AS requestedDate + WITH item, requestedDate, + CASE + WHEN item.endDate = requestedDate THEN 'saved' + WHEN item.endDate IS NOT NULL THEN 'completed' + WHEN $isGoal AND NOT (toLower(coalesce(item.status, '')) IN ['ongoing', 'active']) THEN 'completed' + WHEN requestedDate < date.truncate('month', item.startDate) THEN 'invalid-date' + ELSE 'saved' + END AS outcome + FOREACH (_ IN CASE WHEN outcome = 'saved' AND item.endDate IS NULL THEN [1] ELSE [] END | + SET item.endDate = requestedDate + ${kind === "goal" ? ", item.status = 'achieved'" : ""} + ) + RETURN outcome, toString(item.endDate) AS endDate, item.status AS status + `, + { clerkId, id, endDate, isGoal: kind === "goal" }, + ); + const record = result.records[0]; + return record ? { + outcome: record.get("outcome") as "saved" | "completed" | "invalid-date", + endDate: record.get("endDate") as string | null, + status: record.get("status") as string | null, + } : null; + } finally { + await closeSession(session); + } +} + export async function updateUserSummary( clerkId: string, summary: string, diff --git a/frontend/api/journey.api.ts b/frontend/api/journey.api.ts index 499a604..98c603f 100644 --- a/frontend/api/journey.api.ts +++ b/frontend/api/journey.api.ts @@ -73,6 +73,16 @@ export interface StartJourneyResponse { conversationId: string; } +export type JourneyItemKind = 'experience' | 'goal'; + +export function completeJourneyItem(token: string, kind: JourneyItemKind, id: string, endDate: string) { + return apiFetch<{ endDate: string; status: string | null }>( + `/user/journey/${kind}/${encodeURIComponent(id)}/end-date`, + { method: 'PATCH', body: JSON.stringify({ endDate }) }, + token, + ); +} + export interface SendMessageResponse { success: boolean; conversationId: string; diff --git a/frontend/app/(tabs)/journey.tsx b/frontend/app/(tabs)/journey.tsx index d6cd02b..02752f3 100644 --- a/frontend/app/(tabs)/journey.tsx +++ b/frontend/app/(tabs)/journey.tsx @@ -6,8 +6,8 @@ import { import { useFocusEffect } from 'expo-router'; import { useAuth, useUser } from '@clerk/clerk-expo'; -import { getUserJourney, UserJourneyResponse } from '../../api/journey.api'; -import { calculateDuration, formatToMonthYear } from '../../utils/helpers'; +import { completeJourneyItem, getUserJourney, type JourneyItemKind, type UserJourneyResponse } from '../../api/journey.api'; +import { calculateDuration, formatToMonthYear, sortJourneyExperiences } from '../../utils/helpers'; import { buildJourneyGraphElements, createJourneyGraphHtml } from '../../utils/journeyGraph'; import { ExpandableGoalCard, ExpandableExperienceCard } from '../../components/journey/ExpandableCards'; import { L } from '../../constants/colors'; @@ -34,6 +34,7 @@ export default function JourneyPage() { const [showGraph, setShowGraph] = useState(false); const webViewRef = React.useRef(null); const [selectedNodeId, setSelectedNodeId] = useState(null); + const experiences = useMemo(() => sortJourneyExperiences(journey?.experiences ?? []), [journey?.experiences]); const graphHtml = useMemo( () => createJourneyGraphHtml(buildJourneyGraphElements(journey), { mode: 'personal', screenWidth }), [journey], @@ -60,6 +61,27 @@ export default function JourneyPage() { } }; + const handleCompleteItem = async (kind: JourneyItemKind, id: string, endDate: string) => { + const token = await getToken(); + if (!token) throw new Error('Not authenticated'); + const saved = await completeJourneyItem(token, kind, id, endDate); + setJourney(current => { + if (!current) return current; + if (kind === 'goal') { + return { + ...current, + goals: current.goals.map(goal => goal.id === id + ? { ...goal, endDate: saved.endDate, status: saved.status ?? goal.status } + : goal), + }; + } + return { + ...current, + experiences: current.experiences.map(exp => exp.id === id ? { ...exp, endDate: saved.endDate } : exp), + }; + }); + }; + useEffect(() => { if (Platform.OS === 'web') { const handleWebMessage = (event: MessageEvent) => { @@ -195,10 +217,11 @@ export default function JourneyPage() { {desktop ? ( setShowGraph(true)} onRefresh={loadJourney} + onCompleteItem={handleCompleteItem} /> ) : <> {/* Header */} @@ -247,6 +270,9 @@ export default function JourneyPage() { topics={goal.topics || []} subtopics={goal.subtopics || ['Microservices', 'Event-Driven']} duration={calculateDuration(goal.startDate, goal.endDate)} + onSetEndDate={!goal.endDate && ['ongoing', 'active'].includes(goal.status?.toLowerCase()) + ? date => handleCompleteItem('goal', goal.id, date) + : undefined} /> ))} @@ -264,7 +290,7 @@ export default function JourneyPage() { {/* Timeline Rail */} - {journey.experiences.map((exp) => { + {experiences.map((exp) => { const matchingTransition = journey.transitions.find(t => t.toExperienceId === exp.id); const fromExperience = matchingTransition ? journey.experiences.find(e => e.id === matchingTransition.fromExperienceId) @@ -293,6 +319,7 @@ export default function JourneyPage() { linkedGoalTitles={linkedGoalTitles} transitionLabel={calculatedTransitionLabel} transitionDecision={matchingTransition?.decisionLabel} + onSetEndDate={!exp.endDate ? date => handleCompleteItem('experience', exp.id, date) : undefined} /> ); diff --git a/frontend/components/desktop/DesktopJourney.tsx b/frontend/components/desktop/DesktopJourney.tsx index afdebf0..b047cd0 100644 --- a/frontend/components/desktop/DesktopJourney.tsx +++ b/frontend/components/desktop/DesktopJourney.tsx @@ -1,7 +1,8 @@ import { useState } from 'react'; import { LayoutAnimation, StyleSheet, Text, TouchableOpacity, View, useWindowDimensions } from 'react-native'; import { Feather } from '@expo/vector-icons'; -import type { JourneyExperience, JourneyGoal, UserJourneyResponse } from '../../api/journey.api'; +import type { JourneyExperience, JourneyGoal, JourneyItemKind, UserJourneyResponse } from '../../api/journey.api'; +import { EndDateAction } from '../journey/EndDateAction'; import { calculateDuration, formatToMonthYear } from '../../utils/helpers'; import { L } from '../../constants/colors'; import { DesktopAvatar, DesktopBadge, DesktopButton, DesktopChips, DesktopHeading, DesktopPage, DesktopSectionTitle, desktopStyles as d } from './DesktopUI'; @@ -13,7 +14,7 @@ const verificationLabels = { failed: 'Verification failed', } as const; -function GoalCard({ goal }: { goal: JourneyGoal }) { +function GoalCard({ goal, onSetEndDate }: { goal: JourneyGoal; onSetEndDate: (endDate: string) => Promise }) { const [expanded, setExpanded] = useState(false); const ongoing = ['ONGOING', 'ACTIVE'].includes(goal.status?.toUpperCase()); return @@ -31,6 +32,7 @@ function GoalCard({ goal }: { goal: JourneyGoal }) { {!!goal.topics?.length && } {!!(goal.subtopics || ['Microservices', 'Event-Driven']).length && } + {ongoing && !goal.endDate && } } ; } @@ -42,7 +44,7 @@ function Field({ label, value }: { label: string; value?: string | null }) { return value ? {value} : null; } -function ExperienceCard({ experience: exp, journey }: { experience: JourneyExperience; journey: UserJourneyResponse }) { +function ExperienceCard({ experience: exp, journey, onSetEndDate }: { experience: JourneyExperience; journey: UserJourneyResponse; onSetEndDate: (endDate: string) => Promise }) { const [expanded, setExpanded] = useState(false); const verificationStatus = exp.verificationStatus ?? (exp.isVerified ? 'verified' : undefined); const transition = journey.transitions.find(t => t.toExperienceId === exp.id); @@ -89,12 +91,19 @@ function ExperienceCard({ experience: exp, journey }: { experience: JourneyExper {!!transition?.decisionLabel && "{transition.decisionLabel}"} } {!!exp.skills?.length && s.name)} />} + {!exp.endDate && } } ; } -export function DesktopJourney({ journey, imageUrl, onViewGraph, onRefresh }: { journey: UserJourneyResponse; imageUrl?: string; onViewGraph: () => void; onRefresh: () => void }) { +export function DesktopJourney({ journey, imageUrl, onViewGraph, onRefresh, onCompleteItem }: { + journey: UserJourneyResponse; + imageUrl?: string; + onViewGraph: () => void; + onRefresh: () => void; + onCompleteItem: (kind: JourneyItemKind, id: string, endDate: string) => Promise; +}) { const { width } = useWindowDimensions(); return {journey.goals.length > 0 && - {journey.goals.map(goal => )} + {journey.goals.map(goal => onCompleteItem('goal', goal.id, date)} />)} } {journey.experiences.length > 0 && - {journey.experiences.map(exp => )} + {journey.experiences.map(exp => onCompleteItem('experience', exp.id, date)} />)} } diff --git a/frontend/components/journey/EndDateAction.tsx b/frontend/components/journey/EndDateAction.tsx new file mode 100644 index 0000000..fe20f8c --- /dev/null +++ b/frontend/components/journey/EndDateAction.tsx @@ -0,0 +1,72 @@ +import { useRef, useState } from 'react'; +import { ActivityIndicator, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native'; +import { L } from '../../constants/colors'; + +export function EndDateAction({ label, onSave }: { label: string; onSave: (endDate: string) => Promise }) { + const [editing, setEditing] = useState(false); + const [endDate, setEndDate] = useState(''); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const savingRef = useRef(false); + + const save = async () => { + if (savingRef.current) return; + const date = endDate.trim(); + if (!/^(0[1-9]|1[0-2]) [1-9]\d{3}$/.test(date)) { + setError('Enter an end date in MM YYYY format.'); + return; + } + savingRef.current = true; + setSaving(true); + setError(null); + try { + await onSave(date); + setEditing(false); + } catch (error) { + setError(error instanceof Error ? error.message : 'Could not save the end date.'); + } finally { + savingRef.current = false; + setSaving(false); + } + }; + + if (!editing) { + return setEditing(true)}> + {label} + ; + } + + return + End date (MM YYYY) + + {error && {error}} + + + {saving ? : Save end date} + + { setEditing(false); setEndDate(''); setError(null); }}> + Cancel + + + ; +} + +const styles = StyleSheet.create({ + editor: { gap: 8, marginTop: 12 }, + input: { backgroundColor: '#fff', color: L.navy, borderColor: L.border, borderWidth: 1, borderRadius: 8, padding: 10, width: 135 }, + actions: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }, + button: { alignSelf: 'flex-start', paddingHorizontal: 12, paddingVertical: 9, borderRadius: 8, minHeight: 36, justifyContent: 'center' }, + primary: { backgroundColor: L.teal }, + primaryText: { color: '#fff', fontWeight: '600' }, + text: { color: L.navy, fontWeight: '600' }, +}); diff --git a/frontend/components/journey/ExpandableCards.tsx b/frontend/components/journey/ExpandableCards.tsx index 3dc5e86..ce27346 100644 --- a/frontend/components/journey/ExpandableCards.tsx +++ b/frontend/components/journey/ExpandableCards.tsx @@ -2,6 +2,7 @@ import { useState } from 'react'; import { View, Text, TouchableOpacity, LayoutAnimation, Platform, UIManager } from 'react-native'; import { Feather } from '@expo/vector-icons'; import { L } from '../../constants/colors'; +import { EndDateAction } from './EndDateAction'; // Enable LayoutAnimation for Android if (Platform.OS === 'android' && UIManager.setLayoutAnimationEnabledExperimental) { @@ -15,6 +16,7 @@ export interface ExpandableGoalCardProps { topics?: string[]; subtopics?: string[]; duration?: string; + onSetEndDate?: (endDate: string) => Promise; } export function ExpandableGoalCard({ @@ -23,7 +25,8 @@ export function ExpandableGoalCard({ description, topics = [], subtopics = [], - duration = "" + duration = "", + onSetEndDate, }: ExpandableGoalCardProps) { const [expanded, setExpanded] = useState(false); @@ -163,6 +166,7 @@ export function ExpandableGoalCard({ + {onSetEndDate && } )} @@ -184,6 +188,7 @@ export interface ExpandableExperienceCardProps { linkedGoalTitles?: string[]; transitionLabel?: string; transitionDecision?: string; + onSetEndDate?: (endDate: string) => Promise; } export function ExpandableExperienceCard({ @@ -199,7 +204,8 @@ export function ExpandableExperienceCard({ skills = [], linkedGoalTitles = [], transitionLabel, - transitionDecision + transitionDecision, + onSetEndDate, }: ExpandableExperienceCardProps) { const [expanded, setExpanded] = useState(false); @@ -372,9 +378,10 @@ export function ExpandableExperienceCard({ )} + {onSetEndDate && } )} ); -} \ No newline at end of file +} diff --git a/frontend/tests/journey-graph.test.mjs b/frontend/tests/journey-graph.test.mjs index ec18eb4..00e0d36 100644 --- a/frontend/tests/journey-graph.test.mjs +++ b/frontend/tests/journey-graph.test.mjs @@ -31,6 +31,25 @@ const { groupCommunityPaths, layoutCommunityPath, PATH_CARD_WIDTH, PATH_CARD_HEI const { buildPublicJourneyUrl } = loadTypeScript( fileURLToPath(new URL('../utils/publicJourneyUrl.ts', import.meta.url)), ); +const { sortJourneyExperiences } = loadTypeScript( + fileURLToPath(new URL('../utils/helpers.ts', import.meta.url)), +); + +test('Journey puts ongoing experiences first and reorders completed experiences by end date', () => { + const experiences = [ + { id: 'recent-start', startDate: '2026-05-01', endDate: '2026-10-01' }, + { id: 'earlier-end', startDate: '2026-02-01', endDate: '2026-05-01' }, + { id: 'still-ongoing', startDate: '2025-10-01', endDate: null }, + { id: 'closing', startDate: '2025-11-01', endDate: null }, + ]; + const ids = list => sortJourneyExperiences(list).map(experience => experience.id); + assert.deepEqual(ids(experiences), ['closing', 'still-ongoing', 'recent-start', 'earlier-end']); + const updated = experiences.map(experience => experience.id === 'closing' + ? { ...experience, endDate: '2026-11-01' } + : experience); + assert.deepEqual(ids(updated), ['still-ongoing', 'closing', 'recent-start', 'earlier-end']); + assert.equal(experiences[0].id, 'recent-start'); +}); const graphNode = id => ({ id, title: `Experience ${id}`, authorUsername: 'alex' }); const graphEdge = (fromId, toId) => ({ fromId, toId, label: `${fromId} to ${toId}` }); diff --git a/frontend/utils/helpers.ts b/frontend/utils/helpers.ts index f6e8383..3c51ce7 100644 --- a/frontend/utils/helpers.ts +++ b/frontend/utils/helpers.ts @@ -46,4 +46,15 @@ export function formatToMonthYear(dateStr: string | null | undefined): string { ]; const month = months[monthIndex]; return month ? `${month}-${year}` : dateStr; -} \ No newline at end of file +} + +export function sortJourneyExperiences( + experiences: readonly T[], +): T[] { + return [...experiences].sort((a, b) => { + if (!a.endDate && b.endDate) return -1; + if (a.endDate && !b.endDate) return 1; + return (b.endDate ?? b.startDate).localeCompare(a.endDate ?? a.startDate) + || b.startDate.localeCompare(a.startDate); + }); +} From b99ca229bad21fcc077ad5681a95a196b5de996c Mon Sep 17 00:00:00 2001 From: Rohita Date: Sat, 14 Nov 2026 11:40:46 +0530 Subject: [PATCH 3/3] fix(frontend): restore missing optional peers in lockfile --- frontend/package-lock.json | 75 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 44ade40..00386ce 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -3244,6 +3244,21 @@ "license": "MIT", "peer": true }, + "node_modules/@clerk/clerk-js/node_modules/jayson/node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, "node_modules/@clerk/clerk-js/node_modules/jayson/node_modules/ws": { "version": "7.5.11", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz", @@ -5087,6 +5102,21 @@ "node": "^20.19.4 || ^22.13.0 || ^24.3.0 || >= 25.0.0" } }, + "node_modules/@react-native/dev-middleware/node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, "node_modules/@react-native/dev-middleware/node_modules/ws": { "version": "7.5.12", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.12.tgz", @@ -9754,6 +9784,21 @@ "hermes-estree": "0.35.0" } }, + "node_modules/metro/node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, "node_modules/metro/node_modules/ws": { "version": "7.5.12", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.12.tgz", @@ -10646,6 +10691,21 @@ "ws": "^7" } }, + "node_modules/react-devtools-core/node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, "node_modules/react-devtools-core/node_modules/ws": { "version": "7.5.11", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz", @@ -11317,6 +11377,21 @@ "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", "license": "MIT" }, + "node_modules/react-native/node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, "node_modules/react-native/node_modules/ws": { "version": "7.5.11", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.11.tgz",