Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=
6 changes: 3 additions & 3 deletions backend/src/ai/gemini.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ export class GeminiProvider {
userPrompt,
schema,
temperature,
timeoutMs,
}: {
systemPrompt: string;
userPrompt: string;
schema: Schema;
temperature?: number;
timeoutMs?: number;
}): Promise<T> {
const model =
geminiClient.getGenerativeModel({
Expand All @@ -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();
Expand Down
3 changes: 2 additions & 1 deletion backend/src/config/upstash.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!,
});
signal: () => AbortSignal.timeout(5_000),
});
21 changes: 17 additions & 4 deletions backend/src/controllers/journey.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,24 @@ export async function continueJourneyController(
): Promise<void> {
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,
Expand Down Expand Up @@ -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({
Expand All @@ -127,4 +140,4 @@ export async function submitJourneyController(
error: message,
});
}
}
}
34 changes: 32 additions & 2 deletions backend/src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -43,4 +44,33 @@ export async function getJourneyController(
error: message,
});
}
}
}

export async function completeJourneyItemController(req: Request, res: Response): Promise<void> {
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." });
}
}
46 changes: 37 additions & 9 deletions backend/src/processors/journey/continueJourney.processor.ts
Original file line number Diff line number Diff line change
@@ -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<typeof setTimeout> | undefined;
try {
return await Promise.race([
getUserGoals(userId),
new Promise<Awaited<ReturnType<typeof getUserGoals>>>(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 };
}
return { conversationId, journeyDraft, changedFields, extractionUnavailable };
}
11 changes: 7 additions & 4 deletions backend/src/processors/journey/createGraph.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
12 changes: 8 additions & 4 deletions backend/src/processors/journey/extractJourneyDraft.processor.ts
Original file line number Diff line number Diff line change
@@ -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<GeminiJourneyDraft> {

return geminiProvider.generateStructuredJson<GeminiJourneyDraft>({
systemPrompt: JOURNEY_DRAFT_SYSTEM_PROMPT,
userPrompt: buildJourneyDraftPrompt(narrative),
userPrompt: buildJourneyDraftPrompt(narrative, previous, history),
schema: partialJourneyDraftSchema,
timeoutMs: 15_000,
});

}
}
99 changes: 78 additions & 21 deletions backend/src/processors/journey/finalizeJourneyDraft.processor.ts
Original file line number Diff line number Diff line change
@@ -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<PartialJourneyDraft> {
const existingGoals = await getUserGoals(userId);
const experiences =
draft.experiences.map((experience) => {
return {
...experience,
id:randomUUID(),
goalIds: [],
proofs: [],
isVerified: false,
};
});
return {
goals: existingGoals,
experiences,
};
}
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<string, string[]> = {};
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,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export interface UserSummary {
}

export async function generateUserSummary(
clerkId: string
clerkId: string,
timeoutMs = 10_000,
): Promise<UserSummary> {
const session = getSession();
try {
Expand Down Expand Up @@ -67,8 +68,9 @@ export async function generateUserSummary(
subtopics,
}),
schema: userSummarySchema,
timeoutMs,
});
} finally {
await closeSession(session);
}
}
}
Loading
Loading