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
30 changes: 27 additions & 3 deletions backend/src/processors/journey/continueJourney.processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ 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 retrySessionTimeout<T>(operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (error) {
if (!(error instanceof Error) || error.name !== "TimeoutError") throw error;
return operation();
}
}

async function loadDraftGoals(userId: string) {
let deadline: ReturnType<typeof setTimeout> | undefined;
try {
Expand All @@ -26,9 +35,19 @@ export async function continueJourney(
conversationId: string,
message: string
) {
const session = await getJourneySession(conversationId);
const session = await retrySessionTimeout(() => getJourneySession(conversationId));
if (!session || session.userId !== userId) return null;

const lastMessage = session.conversationHistory.at(-1);
if (session.journeyDraft && session.lastDraftChanges && lastMessage?.role === "user" && lastMessage.content === message) {
return {
conversationId,
journeyDraft: session.journeyDraft,
changedFields: session.lastDraftChanges,
extractionUnavailable: false,
};
}

const userMessage: JourneyMessage = {
role: "user",
content: message,
Expand All @@ -48,9 +67,14 @@ export async function continueJourney(
const { experiences, changedFields } = applyJourneyDraftChanges(geminiDraft, previous, message);
const journeyDraft = { goals: await goalsRequest, experiences };

session.conversationHistory.push(userMessage);
if (!extractionUnavailable) {
session.conversationHistory.push(userMessage);
session.lastDraftChanges = changedFields;
} else {
delete session.lastDraftChanges;
}
session.journeyDraft = journeyDraft;
session.updatedAt = Date.now();
await updateJourneySession(conversationId, session);
await retrySessionTimeout(() => updateJourneySession(conversationId, session));
return { conversationId, journeyDraft, changedFields, extractionUnavailable };
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ export function applyJourneyDraftChanges(
const { title, context, timelineSummary } = changes;
const description = context ?? (previous.length === 0 ? narrative : "");
if (!description) continue;
if (experiences.some(experience =>
experience.title.toLowerCase() === (title ?? "Untitled experience").toLowerCase() &&
experience.context.replace(/\s+/g, " ").toLowerCase() === description.replace(/\s+/g, " ").toLowerCase() &&
experience.startDate === (changes.startDate ?? undefined)
)) continue;
const newFields = Object.fromEntries(Object.entries(changes).filter(([, value]) => value != null));
experiences.push({
...newFields,
Expand Down
1 change: 1 addition & 0 deletions backend/src/types/journey/JourneySession.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface JourneySession {
state: JourneyState;
conversationHistory: JourneyMessage[];
journeyDraft: PartialJourneyDraft | null;
lastDraftChanges?: Record<string, string[]>;
currentExperienceIndex: number;
createdAt: number;
updatedAt: number;
Expand Down
8 changes: 8 additions & 0 deletions backend/tests/journeyDraft.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ test("empty or failed extraction keeps the user's text in a starter draft and ne
assert.equal(recovered.experiences[0]?.startDate, "06 2024");
});

test("duplicate extracted experiences in one turn or a later turn keep the original ID", () => {
const duplicate = { ...internship, title: internship.title.toUpperCase(), context: "Automated reporting with Python." };
const initial = applyJourneyDraftChanges({ experiences: [internship, duplicate] }, []);
assert.equal(initial.experiences.length, 1);
const retried = applyJourneyDraftChanges({ experiences: [duplicate] }, initial.experiences);
assert.deepEqual(retried.experiences.map(experience => experience.id), [initial.experiences[0]!.id]);
});

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], [
Expand Down
20 changes: 14 additions & 6 deletions frontend/api/journey.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,20 @@ export interface StartJourneyResponse {

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 async function completeJourneyItem(token: string, kind: JourneyItemKind, id: string, endDate: string) {
const endpoint = `/user/journey/${kind}/${encodeURIComponent(id)}/end-date`;
try {
return await apiFetch<{ endDate: string; status: string | null }>(
endpoint,
{ method: 'PATCH', body: JSON.stringify({ endDate }) },
token,
);
} catch (error) {
if (error instanceof Error && error.message === `Endpoint ${endpoint} not implemented on the backend yet.`) {
throw new Error('The connected API does not support saving end dates. Check the API URL and update the running backend.');
}
throw error;
}
}

export interface SendMessageResponse {
Expand Down
7 changes: 4 additions & 3 deletions frontend/app/share-journey.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ interface ChatMessage {

export default function ShareJourneyPage() {
const router = useRouter();
const { getToken } = useAuth();
const { getToken, isLoaded } = useAuth();
const desktop = useDesktopLayout();
const [mockVerification, setMockVerification] = useState(false);

Expand Down Expand Up @@ -174,6 +174,7 @@ export default function ShareJourneyPage() {
};

useEffect(() => {
if (!isLoaded) return;
async function initSession() {
setIsInitializing(true);
setSessionError(null);
Expand Down Expand Up @@ -206,7 +207,7 @@ export default function ShareJourneyPage() {
}
initSession();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sessionAttempt]);
}, [isLoaded, sessionAttempt]);

const sendMessage = async (text: string) => {
const userText = text.trim();
Expand Down Expand Up @@ -279,7 +280,7 @@ export default function ShareJourneyPage() {
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.");
displayAlert("Message not sent", "Your message is back in the chat box. Please try sending it again.");
} finally {
sendingMessage.current = false;
setIsLoading(false);
Expand Down
Loading