Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

18.0 KB
Raw Blame
// Career → Coach (ported from apps/web/src/features/career/coach.tsx): conversations about the whole search, with what
// each message shares chosen in the composer.
import type { MessageContext, ThreadSummary } from "./chat";
import type { IconName } from "@/ui";
import { plural } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Pressable, View } from "react-native";
import { coachStarters } from "@reactive-resume/schema/career-starters";
import { formatList } from "@reactive-resume/utils/locale";
import { refreshThreads, useThreads } from "./chat";
import { ChatView, ContextChip, type ChatHistory } from "./chat-view";
import { ChatWelcome } from "./chat-welcome";
import {
	ConnectionNotice,
	ModelButton,
	ModelSheet,
	ProviderGate,
	useConversationProvider,
	useMemoryNote,
	useWebSearch,
	WebResearchChip,
} from "./provider";
import { usableStories } from "./sent";
import { useDeleteThread, useThreadTime, useThreadTitle } from "./threads";
import { client, orpc } from "@/api/client";
import { useSession } from "@/auth/session";
import { useHasAIProvider } from "@/features/ai/providers";
import { useApplications } from "@/features/applications/queries";
import { useNow, useOpportunities } from "@/features/career/hooks";
import { PracticeHandoff } from "@/features/career/prepare-now";
import { collectInterviews } from "@/features/career/scheduling";
import { StoryEditor } from "@/features/career/stories";
import { Button, Icon, IconButton, ListRow, Sheet, Text, TextField, showToast, useTheme } from "@/ui";

type Chips = { application: boolean; memory: boolean; web: boolean; offers: boolean };
const DEFAULT_CHIPS: Chips = { application: true, memory: true, web: false, offers: true };

/** Expo Router gives one value or several for `?offers=`; at most two offers are compared. */
export function offerIdsFrom(value: string | string[] | undefined) {
	return (Array.isArray(value) ? value : value ? [value] : [])
		.flatMap((item) => item.split(","))
		.map((item) => item.trim())
		.filter(Boolean)
		.slice(0, 2);
}

/** Shared, switched-on facts and usable stories, as the server's career context counts them (web: useCoachKnowledge). */
function useCoachKnowledge() {
	const session = useSession();
	const enabled = session.status === "signed-in";
	const factsOptions = orpc.career.facts.queryOptions({ input: { applicationId: null, all: true } });
	const storiesOptions = orpc.career.stories.queryOptions({ input: { applicationId: null } });
	const facts = useQuery({ ...factsOptions, queryKey: [...factsOptions.queryKey, session.server], enabled });
	const stories = useQuery({ ...storiesOptions, queryKey: [...storiesOptions.queryKey, session.server], enabled });
	const active = (facts.data ?? []).filter((fact) => fact.status === "active" && fact.applicationId === null);
	const usable = usableStories(active, stories.data ?? []);
	return {
		all: facts.data ?? [],
		allStories: stories.data ?? [],
		isPending: facts.isPending || stories.isPending,
		isError: facts.isError || stories.isError,
		retry: () => {
			void facts.refetch();
			void stories.refetch();
		},
		facts: active.length,
		stories: usable.length,
		factIds: active.map((fact) => fact.id),
		storyIds: usable.map((story) => story.id),
	};
}

type CoachScreenProps = {
	/** Saved offers to compare, from Offers → Plan what to ask (M6-T1). */
	offerIds: string[];
};

export function CoachScreen({ offerIds }: CoachScreenProps) {
	const { t, i18n } = useLingui();
	const { colors, space } = useTheme();
	const queryClient = useQueryClient();
	const providers = useHasAIProvider();
	const threads = useThreads();
	const knowledge = useCoachKnowledge();
	const [threadId, setThreadId] = useState<string | null>(null);
	const [draftKey, setDraftKey] = useState(0);
	const [chips, setChips] = useState<Chips>(DEFAULT_CHIPS);
	const [listOpen, setListOpen] = useState(false);
	const [renaming, setRenaming] = useState<{ id: string; title: string } | null>(null);
	const [modelOpen, setModelOpen] = useState(false);

	const conversations = (threads.data ?? []).filter((thread) => thread.scope === "career");
	const summary = threads.data?.find((thread) => thread.id === threadId);
	const { provider, stranded, label, choose } = useConversationProvider(providers, summary, threadId);
	const title = useThreadTitle();
	const web = useWebSearch(provider);
	const memory = useMemoryNote(chips.memory);

	const context: MessageContext = {
		// A career conversation has no document or posting to leave out.
		document: true,
		posting: true,
		application: chips.application,
		memory: chips.memory,
		// The message still requires Web research on and per-operation destination approval.
		web: chips.web && web.canSearch,
		...(offerIds.length > 0 && chips.offers ? { offerIds } : {}),
	};
	const knowledgeBlocks = chips.memory && (knowledge.isPending || knowledge.isError);

	// The privacy line names exactly what goes and what the coach may keep. The chips choose what this message adds;
	// earlier messages go too, except those written before Knowledge last changed.
	const privacyFor = ({ earlier, withheld }: ChatHistory) => {
		const parts = [
			t`your message`,
			...(earlier > 0 ? [t`earlier messages in this chat`] : []),
			...(chips.application ? [t`application summaries`] : []),
			...(context.offerIds ? [plural(offerIds.length, { one: "# saved offer", other: "# saved offers" })] : []),
			...(chips.memory
				? [
						t`your preferences`,
						...(knowledge.facts > 0 ? [plural(knowledge.facts, { one: "# fact", other: "# facts" })] : []),
						...(knowledge.stories > 0 ? [t`your stories`] : []),
					]
				: []),
		];
		const list = formatList(i18n.locale, parts);
		return [
			stranded
				? t`Nothing is sent until you choose a connection for this conversation.`
				: chips.memory && knowledge.isError
					? t`Knowledge couldn't load. Try again or switch Knowledge off before sending.`
					: chips.memory && knowledge.isPending
						? t`Loading Knowledge before you send…`
						: t`When you tap send, ${list} go to your ${connection}.`,
			...(withheld > 0 ? [t`Messages from before Knowledge changed aren't sent.`] : []),
			...(context.web ? [t`Search terms go to your web search service.`] : []),
			memory.note,
		]
			.filter(Boolean)
			.join(" ");
	};
	const connection = /connection$/i.test(label) ? label : t`${label} connection`;

	const newConversation = () => {
		setThreadId(null);
		setDraftKey((key) => key + 1);
		setListOpen(false);
	};

	return (
		<View style={{ flex: 1, backgroundColor: colors.surface }}>
			<View style={{ paddingHorizontal: space.s4, flexDirection: "row", alignItems: "center" }}>
				{summary ? (
					<Pressable
						accessibilityRole="button"
						accessibilityLabel={t`Rename ${title(summary)}`}
						onPress={() => {
							setRenaming({ id: summary.id, title: title(summary) });
							setListOpen(true);
						}}
						style={{ flex: 1, minHeight: 44, justifyContent: "center" }}
					>
						<Text variant="label">{title(summary)}</Text>
					</Pressable>
				) : (
					<Text variant="label" style={{ flex: 1 }}>{t`Coach`}</Text>
				)}
				<IconButton icon="clock-counter-clockwise" label={t`Conversations`} onPress={() => setListOpen(true)} />
				<IconButton icon="note-pencil" label={t`New conversation`} onPress={newConversation} />
			</View>
			<PracticeHandoff />
			<ProviderGate
				providers={providers}
				readOnly={threadId !== null}
				threadsError={threads.error}
				loading={threads.isPending}
				onRetry={() => {
					providers.retry();
					void threads.refetch();
					knowledge.retry();
				}}
				notSetUp={t`The coach isn't set up on this server. Whoever runs it needs to set ENCRYPTION_SECRET. Knowledge, Offers and your applications work without it.`}
			>
				<View
					style={{
						flexDirection: "row",
						alignItems: "center",
						gap: space.s2,
						paddingHorizontal: space.s4,
						paddingVertical: space.s2,
						borderBottomWidth: 1,
						borderColor: colors.line,
					}}
				>
					<Icon name="sparkle" size={18} color={colors.accent} />
					<View style={{ flex: 1 }}>
						<ModelButton current={provider} label={label} onPress={() => setModelOpen(true)} />
					</View>
					{chips.memory && knowledge.isError ? (
						<Button variant="link" size="sm" label={t`Retry`} onPress={knowledge.retry} />
					) : null}
				</View>
				<ChatView
					key={draftKey}
					threadId={threadId}
					createThread={async (scope) =>
						(
							await client.agent.threads.start(
								{ scope: "career", ...(provider ? { aiProviderId: provider.id } : {}) },
								{ context: { scope } },
							)
						).id
					}
					onThreadCreated={(id) => {
						setThreadId(id);
						void threads.refetch();
					}}
					context={context}
					// Recorded on each question as web does (coach-thread.tsx usedFor), for the Sent line on both.
					sent={() => ({
						facts: chips.memory ? knowledge.factIds.slice(0, 30) : [],
						stories: chips.memory ? knowledge.storyIds.slice(0, 8) : [],
						preferences: chips.memory,
						applications: chips.application,
						offers: context.offerIds ?? [],
						web: context.web === true,
					})}
					document={null}
					onRefresh={() =>
						Promise.allSettled([
							threads.refetch(),
							queryClient.invalidateQueries({ queryKey: orpc.career.key() }),
							queryClient.invalidateQueries({ queryKey: orpc.applications.key() }),
							queryClient.invalidateQueries({ queryKey: orpc.auth.getProfile.key() }),
							queryClient.invalidateQueries({ queryKey: orpc.aiProviders.key() }),
						])
					}
					connection={connection}
					privacy={privacyFor}
					remember={{ applicationId: null }}
					facts={knowledge.all}
					stories={knowledge.allStories}
					storyEditor={({ story, onChange, onSaved, onClose }) => (
						<StoryEditor
							story={null}
							facts={knowledge.all}
							proposal={{
								story,
								onChange,
								onSaved: () => {
									onSaved();
									showToast({ message: t`Your edited story is saved to Knowledge.` });
								},
							}}
							onClose={onClose}
						/>
					)}
					notice={
						stranded ? (
							<ConnectionNotice
								label={summary?.providerLabel ?? null}
								fallback={providers.usableProviders[0]}
								onUse={(id) => void choose(id)}
								onChoose={() => setModelOpen(true)}
							/>
						) : null
					}
					placeholder={t`Ask about your next career step…`}
					assistantName={t`Coach`}
					disabled={knowledgeBlocks || !provider}
					onSwitchModel={() => setModelOpen(true)}
					onFinish={() => {
						// The coach may have remembered a fact or saved a story.
						void queryClient.invalidateQueries({ queryKey: orpc.career.facts.key() });
						void queryClient.invalidateQueries({ queryKey: orpc.career.stories.key() });
					}}
					chips={
						<>
							<ContextChip
								icon="briefcase"
								label={t`Applications`}
								pressed={chips.application}
								onPress={() => setChips({ ...chips, application: !chips.application })}
							/>
							<ContextChip
								icon="brain"
								label={plural(knowledge.facts, { one: "Knowledge · # fact", other: "Knowledge · # facts" })}
								pressed={chips.memory}
								onPress={() => setChips({ ...chips, memory: !chips.memory })}
							/>
							<WebResearchChip web={web} pressed={chips.web} onPress={() => setChips({ ...chips, web: !chips.web })} />
							{memory.chip}
							{offerIds.length > 0 ? (
								<ContextChip
									icon="hand-heart"
									label={plural(offerIds.length, { one: "# saved offer", other: "# saved offers" })}
									pressed={chips.offers}
									onPress={() => setChips({ ...chips, offers: !chips.offers })}
								/>
							) : null}
						</>
					}
					empty={(send) => (
						<Starters disabled={knowledgeBlocks || !provider} offers={context.offerIds?.length ?? 0} onPick={send} />
					)}
				/>
			</ProviderGate>

			<ConversationsSheet
				open={listOpen}
				onClose={() => setListOpen(false)}
				threads={conversations}
				currentId={threadId}
				renaming={renaming}
				onRenamingChange={setRenaming}
				onNew={newConversation}
				onOpen={(id) => {
					setThreadId(id);
					setListOpen(false);
				}}
				onDeleted={(id) => {
					if (id === threadId) newConversation();
				}}
				onRenamed={() => refreshThreads(queryClient)}
			/>
			<ModelSheet
				open={modelOpen}
				onClose={() => setModelOpen(false)}
				providers={providers.usableProviders}
				currentId={provider?.id}
				onChoose={(id) => void choose(id)}
			/>
		</View>
	);
}

/** `offers`: saved offers sent with this conversation (Offers → Plan what to ask), which get their own starters. */
type StartersProps = { disabled: boolean; offers: number; onPick: (text: string) => void };

function Starters({ disabled, offers, onPick }: StartersProps) {
	const { t } = useLingui();
	const applications = useApplications();
	const opportunities = useOpportunities();
	const now = useNow();
	const open = (applications.data ?? []).filter((application) => application.status !== "closed");
	// Starters that fit the account: an upcoming interview, an offer or found roles come first when there are some.
	const accountStarters = coachStarters({
		nextInterviewCompany: collectInterviews(open, now)[0]?.application.company,
		offers: open.filter((application) => application.status === "offer").length,
		opportunities: (opportunities.data ?? []).filter((row) => !row.trackedApplicationId).length,
	}).map((starter): { icon: IconName; text: string } => {
		switch (starter.kind) {
			case "interview":
				return { icon: "microphone", text: t`Help me prepare for my ${starter.company} interview.` };
			case "offers":
				return { icon: "scales", text: t`Help me weigh the offer I have against what I want.` };
			case "opportunities":
				return { icon: "list-magnifying-glass", text: t`Which opportunities best match my priorities?` };
			case "story":
				return {
					icon: "list-numbers",
					text: t`Help me turn an accomplishment into a Situation, Task, Action, Result and Reflection story.`,
				};
			case "practice":
				return { icon: "user-sound", text: t`What interview answers should I practice?` };
			default:
				return { icon: "compass", text: t`What kinds of roles fit what I've done so far?` };
		}
	});
	// Opened from Offers → Plan what to ask: starters about the offers being decided.
	const starters: { icon: IconName; text: string }[] =
		offers > 1
			? [
					{ icon: "question", text: t`What should I ask before deciding?` },
					{ icon: "scales", text: t`Which offer fits my requirements better?` },
					{ icon: "list-checks", text: t`What's missing from these offers that I should get in writing?` },
				]
			: offers === 1
				? [
						{ icon: "question", text: t`What should I ask before deciding on this offer?` },
						{ icon: "scales", text: t`Does this offer meet what I want?` },
						{ icon: "list-checks", text: t`What's missing from this offer that I should get in writing?` },
					]
				: accountStarters;
	return (
		<ChatWelcome
			description={
				<>
					<Trans>
						Ask about your search, or bring an accomplishment you want to explain better. Answers use what's switched on
						below, and each shows what was sent with it.
					</Trans>
				</>
			}
			starters={starters.map((starter) => ({
				icon: starter.icon,
				label: starter.text,
				disabled,
				onPick: () => onPick(starter.text),
			}))}
		/>
	);
}

type ConversationsSheetProps = {
	open: boolean;
	onClose: () => void;
	threads: readonly ThreadSummary[];
	currentId: string | null;
	renaming: { id: string; title: string } | null;
	onRenamingChange: (target: { id: string; title: string } | null) => void;
	onNew: () => void;
	onOpen: (id: string) => void;
	onDeleted: (id: string) => void;
	onRenamed: () => void;
};

/** New conversation, then the career conversations: open, rename or delete. */
function ConversationsSheet(props: ConversationsSheetProps) {
	const { t } = useLingui();
	const { space } = useTheme();
	const title = useThreadTitle();
	const time = useThreadTime();
	const remove = useDeleteThread(props.onDeleted);
	const { renaming, onRenamingChange: setRenaming } = props;

	const saveName = async () => {
		const target = renaming;
		setRenaming(null);
		const next = target?.title.trim();
		if (!target || !next) return;
		try {
			await client.agent.threads.update({ id: target.id, title: next });
			props.onRenamed();
		} catch {
			showToast({ message: t`Couldn't rename the conversation. Try again.` });
		}
	};

	return (
		<Sheet open={props.open} onClose={props.onClose} title={t`Conversations`} detents={[0.7]}>
			<ListRow title={t`New conversation`} leading="note-pencil" onPress={props.onNew} />
			{props.threads.map((thread) =>
				renaming?.id === thread.id ? (
					<View key={thread.id} style={{ gap: space.s2, paddingHorizontal: space.s4 }}>
						<TextField
							label={t`Conversation name`}
							value={renaming.title}
							onChangeText={(value) => setRenaming({ id: thread.id, title: value })}
							maxLength={200}
							autoFocus
							returnKeyType="done"
							onSubmitEditing={() => void saveName()}
						/>
						<View style={{ flexDirection: "row", gap: space.s2 }}>
							<Button size="sm" label={t`Save`} onPress={() => void saveName()} />
							<Button size="sm" variant="ghost" label={t`Cancel`} onPress={() => setRenaming(null)} />
						</View>
					</View>
				) : (
					<ListRow
						key={thread.id}
						title={title(thread)}
						subtitle={time(thread.lastMessageAt)}
						selected={thread.id === props.currentId}
						onPress={() => props.onOpen(thread.id)}
						trailing={
							<View style={{ flexDirection: "row" }}>
								<IconButton
									icon="pencil-simple"
									label={t`Rename ${title(thread)}`}
									onPress={() => setRenaming({ id: thread.id, title: title(thread) })}
								/>
								<IconButton icon="trash" label={t`Delete ${title(thread)}`} onPress={() => remove.ask(thread)} />
							</View>
						}
					/>
				),
			)}
			<Text variant="caption" color="ink3" style={{ paddingHorizontal: space.s4 }}>
				<Trans>Conversations about one job live in its workspace.</Trans>
			</Text>
			{remove.dialog}
		</Sheet>
	);
}