A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: keep palette questions through AI setup
Amruth Pillai62c132fcf07f
diff --git a/apps/mobile/app/builder/[id]/assistant.tsx b/apps/mobile/app/builder/[id]/assistant.tsxindex 09ce1dc67..28ada9280 100644--- a/apps/mobile/app/builder/[id]/assistant.tsx+++ b/apps/mobile/app/builder/[id]/assistant.tsx@@ -1,11 +1,11 @@import { Stack, useLocalSearchParams } from "expo-router";import { AssistantScreen } from "@/features/assistant/assistant-screen";-type Params = { id: string; thread?: string; ask?: string; prepare?: string; applicationId?: string };+type Params = { id: string; thread?: string; ask?: string; draft?: string; prepare?: string; applicationId?: string };-/** `?thread=` opens a conversation, `?ask=` sends a question in a new one, `?prepare=1` offers next-step starters. */+/** `?thread=` opens a conversation, `?ask=` sends, `?draft=` prefills, `?prepare=1` offers next-step starters. */export default function AssistantRoute() {- const { id, thread, ask, prepare, applicationId } = useLocalSearchParams<Params>();+ const { id, thread, ask, draft, prepare, applicationId } = useLocalSearchParams<Params>();return (<><Stack.Screen options={{ headerShown: false }} />@@ -13,6 +13,7 @@ export default function AssistantRoute() {resumeId={id}threadId={thread}ask={ask}+ draft={draft}prepare={prepare === "1"}applicationId={applicationId}/>diff --git a/apps/mobile/app/letter/[id]/assistant.tsx b/apps/mobile/app/letter/[id]/assistant.tsxindex 92563147b..249b39bc6 100644--- a/apps/mobile/app/letter/[id]/assistant.tsx+++ b/apps/mobile/app/letter/[id]/assistant.tsx@@ -1,14 +1,14 @@import { Stack, useLocalSearchParams } from "expo-router";import { LetterAssistantScreen } from "@/features/assistant/assistant-screen";-type Params = { id: string; thread?: string; ask?: string; applicationId?: string };+type Params = { id: string; thread?: string; ask?: string; draft?: string; applicationId?: string };export default function LetterAssistantRoute() {- const { id, thread, ask, applicationId } = useLocalSearchParams<Params>();+ const { id, thread, ask, draft, applicationId } = useLocalSearchParams<Params>();return (<><Stack.Screen options={{ headerShown: false }} />- <LetterAssistantScreen letterId={id} threadId={thread} ask={ask} applicationId={applicationId} />+ <LetterAssistantScreen letterId={id} threadId={thread} ask={ask} draft={draft} applicationId={applicationId} /></>);}diff --git a/apps/mobile/scripts/power-user-repairs.test.mjs b/apps/mobile/scripts/power-user-repairs.test.mjsindex 6458425d3..6423125a2 100644--- a/apps/mobile/scripts/power-user-repairs.test.mjs+++ b/apps/mobile/scripts/power-user-repairs.test.mjs@@ -68,6 +68,7 @@ const routes = {letter: (id) => `/letter/${id}`,application: (id) => `/applications/${id}`,assistant: (id) => `/builder/${id}/assistant`,+ letterAssistant: (id) => `/letter/${id}/assistant`,new: () => "/new",newJob: () => "/applications?create=1",career: (p) => `/career/${p}`,@@ -388,6 +389,9 @@ let count = 9;let failed = false;let resumesPending = false;let resumeCount = 0;+const searchAi = { isUnavailable: false, hasAIProvider: true, isLoading: false, retry: () => calls.push("ai-retry") };+let searchScope = "fixture-account";+let latestSearchDocument = [];const inputs = [];const letters = Array.from({ length: 209 }, (_, i) => ({id: `letter-${i + 1}`,@@ -399,9 +403,9 @@ const letters = Array.from({ length: 209 }, (_, i) => ({}));const { SearchScreen } = load("features/search/search-screen.tsx", {"./rank": load("features/search/rank.ts"),- "@/features/ai/providers": { useHasAIProvider: () => ({ isUnavailable: false, hasAIProvider: true }) },+ "@/features/ai/providers": { useHasAIProvider: () => searchAi, AIProviderSetupSheet: "AIProviderSetupSheet" },"@/auth/session": {- getAccountScope: () => "fixture-account",+ getAccountScope: () => searchScope,useSession: () => ({ status: "signed-in", server: "fixture-server" }),},"@/shell/use-is-tablet": { useIsTablet: () => false },@@ -438,7 +442,7 @@ const { SearchScreen } = load("features/search/search-screen.tsx", {if (!enabled) return state({ data: undefined, isPending: true });return input.type === "letter"? state({ data: failed ? undefined : letters.slice(0, Math.min(input.limit, count)), isError: failed })- : state();+ : state({ data: latestSearchDocument });},},});@@ -505,3 +509,140 @@ libraryContinuation.props.onPress();assert.deepEqual(calls.at(-1), { pathname: "/documents", params: { q: "resume", type: "resume" } });console.log("PASS native pending Enter and 100-resume filtered library continuation");reset();++searchAi.hasAIProvider = false;+tree = render(SearchScreen);+nodes(tree)+ .find((node) => node.type === "TextInput")+ .props.onChangeText("Keep my fictional question");+tree = render(SearchScreen);+const beforeSetup = calls.length;+nodes(tree)+ .find((node) => node.type === "ListRow" && node.props.title.startsWith("Connect an AI provider to ask"))+ .props.onPress();+tree = render(SearchScreen);+assert.equal(calls.length, beforeSetup, "provider setup must not dismiss Search to Settings");+assert.equal(nodes(tree).find((node) => node.type === "AIProviderSetupSheet").props.open, true);+nodes(tree)+ .find((node) => node.type === "AIProviderSetupSheet")+ .props.onClose();+tree = render(SearchScreen);+assert.equal(nodes(tree).find((node) => node.type === "TextInput").props.value, "Keep my fictional question");+assert.equal(nodes(tree).find((node) => node.type === "AIProviderSetupSheet").props.open, false);+searchAi.hasAIProvider = true;+for (const type of ["resume", "letter"]) {+ latestSearchDocument = [{ id: `named-${type}`, type, name: `Fictional named ${type}` }];+ tree = render(SearchScreen);+ const ask = nodes(tree).find((node) => node.type === "ListRow" && node.props.title.startsWith("Ask about"));+ assert.ok(ask.props.title.includes(`Fictional named ${type}`));+ ask.props.onPress();+ assert.deepEqual(+ calls.at(-1),+ {+ pathname: type === "resume" ? `/builder/named-${type}/assistant` : `/letter/named-${type}/assistant`,+ params: { draft: "Keep my fictional question" },+ },+ "the named document receives an unsent draft, never the auto-send ask parameter",+ );+}+const queuedNamedAsk = nodes(tree).find((node) => node.type === "ListRow" && node.props.title.startsWith("Ask about"));+const beforeQueuedNamedAsk = calls.length;+searchScope = "replacement-account";+queuedNamedAsk.props.onPress();+assert.equal(calls.length, beforeQueuedNamedAsk, "queued named Ask cannot navigate under a replacement account");+searchScope = "fixture-account";+searchAi.isUnavailable = true;+tree = render(SearchScreen);+const beforeRetry = calls.length;+nodes(tree)+ .find((node) => node.type === "ListRow" && node.props.title === "Try again")+ .props.onPress();+assert.deepEqual(calls.slice(beforeRetry), ["ai-retry"]);+Object.assign(searchAi, { isUnavailable: false, hasAIProvider: true });+searchAi.hasAIProvider = false;+tree = render(SearchScreen);+nodes(tree)+ .find((node) => node.type === "ListRow" && node.props.title.startsWith("Connect an AI provider to ask"))+ .props.onPress();+searchScope = "replacement-account";+render(SearchScreen);+tree = render(SearchScreen);+assert.equal(nodes(tree).find((node) => node.type === "TextInput").props.value, "");+assert.equal(nodes(tree).find((node) => node.type === "AIProviderSetupSheet").props.open, false);+searchScope = "fixture-account";+searchAi.hasAIProvider = true;+reset();+console.log("PASS native palette setup retains question, binds named document and hands over unsent draft");++const { AssistantScreen, LetterAssistantScreen } = load("features/assistant/assistant-screen.tsx", {+ "./chat": { useThreads: () => ({ data: [], refetch() {} }) },+ "./chat-view": { ChatView: "ChatView", ContextChip: "ContextChip" },+ "./chat-welcome": { ChatWelcome: "ChatWelcome" },+ "./document": {+ useResumeAssistantDocument: () => ({ kind: "resume", id: "named-resume", name: "Fictional resume", locked: false }),+ useLetterAssistantDocument: () => ({ kind: "letter", id: "named-letter", name: "Fictional letter", locked: false }),+ },+ "./handoff": { takeAssistantHandoff: () => null },+ "./proposals": { publishProposals() {} },+ "./provider": {+ ConnectionNotice: "ConnectionNotice",+ ModelButton: "ModelButton",+ ModelSheet: "ModelSheet",+ ProviderGate: "ProviderGate",+ useConversationProvider: () => ({ provider: { id: "fictional" }, label: "Fictional provider", choose() {} }),+ },+ "./threads": { PastConversations: "PastConversations" },+ "./translate-resume": { TranslateResume: "TranslateResume" },+ "react-native-safe-area-context": { SafeAreaProvider: "SafeAreaProvider", SafeAreaView: "SafeAreaView" },+ "@/api/client": {+ client: { agent: { threads: { start: () => assert.fail("Opening a draft must not start a thread") } } },+ },+ "@/auth/session": { getAccountScope: () => "fixture-account", useSession: () => ({ status: "signed-in" }) },+ "@/draft": {+ useResumeStore: (select) => select({ document: {}, status: "saved" }),+ useLetterStore: (select) => select({ document: {}, status: "saved" }),+ },+ "@/features/ai/providers": { useHasAIProvider: () => ({ usableProviders: [{ id: "fictional" }] }) },+ "@/features/write/unlock": { useUnlockResume: () => ({}) },+});+for (const [component, id] of [+ [AssistantScreen, { resumeId: "named-resume" }],+ [LetterAssistantScreen, { letterId: "named-letter" }],+]) {+ for (const mode of ["draft", "ask"]) {+ reset();+ const outer = render(() => component({ ...id, [mode]: "Fictional task" }));+ tree = render(() => outer.type(outer.props));+ const chat = nodes(tree).find((node) => node.type === "ChatView");+ assert.equal(chat.props.threadId, null);+ assert.equal(chat.props.draft, mode === "draft" ? "Fictional task" : undefined);+ assert.equal(chat.props.prompt, mode === "ask" ? "Fictional task" : null);+ nodes(tree)+ .find((node) => node.type === "IconButton" && node.props.label === "New conversation")+ .props.onPress();+ tree = render(() => outer.type(outer.props));+ assert.equal(+ nodes(tree).find((node) => node.type === "ChatView").props.draft,+ undefined,+ "a new conversation must not replay initial draft",+ );+ }+}+reset();+console.log("PASS native resume and letter draft links fill composer without auto-send; legacy ask links unchanged");+for (const [path, exportName, screen] of [+ ["builder/[id]/assistant.tsx", "default", AssistantScreen],+ ["letter/[id]/assistant.tsx", "default", LetterAssistantScreen],+]) {+ const route = load("../app/" + path, {+ "expo-router": {+ ...common["expo-router"],+ useLocalSearchParams: () => ({ id: "named", draft: "Unsent route task" }),+ },+ "@/features/assistant/assistant-screen": { AssistantScreen, LetterAssistantScreen },+ })[exportName];+ const target = nodes(route()).find((node) => node.type === screen);+ assert.equal(target.props.draft, "Unsent route task");+ assert.equal(target.props.ask, undefined);+}+console.log("PASS native resume and letter routes preserve draft parameter without converting it to auto-send");diff --git a/apps/mobile/src/features/assistant/assistant-screen.tsx b/apps/mobile/src/features/assistant/assistant-screen.tsxindex 85d4767ed..49bffbf71 100644--- a/apps/mobile/src/features/assistant/assistant-screen.tsx+++ b/apps/mobile/src/features/assistant/assistant-screen.tsx@@ -29,6 +29,8 @@ export type AssistantScreenProps = {threadId?: string | undefined;/** A question to send in a new conversation as soon as the assistant can. */ask?: string | undefined;+ /** A question to review in the composer before sending. */+ draft?: string | undefined;/** Prepare for next step: the application's suggestions (fit, follow-up, interview). */prepare?: boolean | undefined;/** The application this resume was opened for. */@@ -62,7 +64,7 @@ export function AssistantScreen(props: AssistantScreenProps) {return (<DocumentAssistantScreen{...props}- key={`${getAccountScope()}:${props.resumeId}:${props.threadId}:${props.ask}:${props.prepare}`}+ key={`${getAccountScope()}:${props.resumeId}:${props.threadId}:${props.ask}:${props.draft}:${props.prepare}`}kind="resume"documentId={props.resumeId}document={document}@@ -80,7 +82,7 @@ export function LetterAssistantScreen(props: LetterAssistantScreenProps) {return (<DocumentAssistantScreen{...props}- key={`${getAccountScope()}:${props.letterId}:${props.threadId}:${props.ask}`}+ key={`${getAccountScope()}:${props.letterId}:${props.threadId}:${props.ask}:${props.draft}`}kind="letter"documentId={props.letterId}document={document}@@ -117,7 +119,7 @@ function DocumentAssistantScreen(props: DocumentAssistantScreenProps) {);// null: the document's latest conversation; "new": a new one.const [selected, setSelected] = useState<string | null>(- props.ask || props.prepare || handed ? "new" : (props.threadId ?? null),+ props.ask || props.draft || props.prepare || handed ? "new" : (props.threadId ?? null),);const [ask, setAsk] = useState(props.ask ?? null);const [prepare, setPrepare] = useState(props.prepare ?? false);@@ -129,6 +131,7 @@ function DocumentAssistantScreen(props: DocumentAssistantScreenProps) {const mine = document ? (threads.data ?? []).filter((thread) => belongsTo(thread, document)) : [];const threadId = selected === "new" ? null : (selected ?? mine[0]?.id ?? null);+ const draft = draftKey === 0 ? (props.draft ?? handed) : null;const summary = mine.find((thread) => thread.id === threadId);const { provider, stranded, label, choose } = useConversationProvider(providers, summary, threadId);@@ -240,7 +243,7 @@ function DocumentAssistantScreen(props: DocumentAssistantScreenProps) {placeholder={t`Ask, or describe a change…`}assistantName={t`Assistant`}disabled={!provider}- {...(handed && threadId === null ? { draft: handed } : {})}+ {...(draft && threadId === null ? { draft } : {})}notice={stranded ? (<ConnectionNoticediff --git a/apps/mobile/src/features/search/search-screen.tsx b/apps/mobile/src/features/search/search-screen.tsxindex f066252b6..e71f42938 100644--- a/apps/mobile/src/features/search/search-screen.tsx+++ b/apps/mobile/src/features/search/search-screen.tsx@@ -8,9 +8,9 @@ import { Stack, useRouter } from "expo-router";import { useEffect, useState } from "react";import { ActivityIndicator, BackHandler, Platform, Pressable, ScrollView, TextInput, View } from "react-native";import { rank } from "./rank";-import { client, orpc } from "@/api/client";+import { orpc } from "@/api/client";import { getAccountScope, useSession } from "@/auth/session";-import { useHasAIProvider } from "@/features/ai/providers";+import { AIProviderSetupSheet, useHasAIProvider } from "@/features/ai/providers";import { useApplications } from "@/features/applications/queries";import { routes } from "@/routes";import { useShortcutHelp } from "@/shell/shortcut-help";@@ -93,6 +93,15 @@ export function SearchScreen() {const signedIn = session.status === "signed-in";const [query, setQuery] = useState("");const [page, setPage] = useState<Page>("root");+ const [setup, setSetup] = useState(false);+ const scope = getAccountScope();+ const [owner, setOwner] = useState(scope);+ if (owner !== scope) {+ setOwner(scope);+ setSetup(false);+ setQuery("");+ setPage("root");+ }const typing = query.trim().length > 0;const resumeQuery = useDocumentSearch(@@ -301,35 +310,31 @@ export function SearchScreen() {];const available = actions.filter((action) => signedIn || !action.account);- const ask = async (question: string) => {+ const ask = (question: string) => {+ if (scope !== getAccountScope()) return;+ if (ai.isUnavailable) {+ ai.retry();+ return;+ }if (needsProvider) {- go(routes.settings("ai"));+ setSetup(true);return;}- const scope = getAccountScope();- let latest: DocumentSummary | undefined;- try {- [latest] = await client.documents.list({- type: "all",- sort: "edited",- limit: 1,- offset: 0,- tags: [],- trashed: false,- });- } catch {+ if (latestDocument.isPending) return;+ if (latestDocument.isError) {showToast({ message: t`Couldn't load this. Check your connection and try again.` });+ void latestDocument.refetch();return;}- if (scope !== getAccountScope()) return;+ const latest = latestDocument.data?.[0];if (!latest) {showToast({ message: t`Create a resume first, then ask about it.` });return;}- // The assistant routes' `?ask=` sends the question in a new conversation.+ // Search hands over a draft; the existing `ask` links still send their explicit tasks.go({pathname: latest.type === "letter" ? routes.letterAssistant(latest.id) : routes.assistant(latest.id),- params: { ask: question },+ params: { draft: question },});};@@ -582,17 +587,22 @@ export function SearchScreen() {<ListRowleading="sparkle"title={- needsProvider- ? t`Connect an AI provider to ask “${question}”`- : name- ? t`Ask about “${name}”: ${question}`- : t`Ask the assistant “${question}”`+ ai.isUnavailable+ ? ai.isLoading+ ? t`Loading providers…`+ : t`Try again`+ : needsProvider+ ? t`Connect an AI provider to ask “${question}”`+ : name+ ? t`Ask about “${name}”: ${question}`+ : t`Ask the assistant “${question}”`}onPress={() => ask(question)}/></View>) : null}</ScrollView>+ <AIProviderSetupSheet open={setup} onClose={() => setSetup(false)} /></View>);}diff --git a/apps/web/src/features/command-palette/index.tsx b/apps/web/src/features/command-palette/index.tsxindex a0a2aa258..2b58c8382 100644--- a/apps/web/src/features/command-palette/index.tsx+++ b/apps/web/src/features/command-palette/index.tsx@@ -16,7 +16,6 @@ export function CommandPalette() {options: { meta: { name: t`Command palette` }, requireReset: true },callback: () => setOpen(!open),},- { hotkey: "Escape", options: { enabled: open, conflictBehavior: "allow" }, callback: () => setOpen(false) },]);return open ? (diff --git a/apps/web/src/features/command-palette/pages/ask.test.tsx b/apps/web/src/features/command-palette/pages/ask.test.tsxindex 647a33e74..cc7510a18 100644--- a/apps/web/src/features/command-palette/pages/ask.test.tsx+++ b/apps/web/src/features/command-palette/pages/ask.test.tsx@@ -1,5 +1,5 @@// @vitest-environment happy-dom-import { fireEvent, render, screen } from "@testing-library/react";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, expect, it, vi } from "vite-plus/test";import { i18n } from "@lingui/core";import { I18nProvider } from "@lingui/react";@@ -9,13 +9,61 @@ import { useCommandPaletteStore } from "../store";import { AskCommandGroup } from "./ask";const openAssistant = vi.hoisted(() => vi.fn());+const account = vi.hoisted(() => ({ id: "fixture", generation: 0 }));+vi.mock("@/libs/auth/account-scope", () => ({ getAccountGeneration: () => account.generation }));+const providers = vi.hoisted(() => ({+ hasUsableProvider: true,+ isUnavailable: false,+ isLoading: false,+ error: null as Error | null,+ retry: vi.fn(),+}));+vi.mock("@/features/settings/integrations/hooks/use-has-usable-ai-provider", () => ({+ useHasUsableAiProvider: () => providers,+}));+vi.mock("@/features/assistant/provider-setup", () => ({ ProviderSetup: () => <p>Provider form boundary</p> }));vi.mock("@/features/assistant/open", () => ({ openAssistantFrom: openAssistant }));vi.mock("@tanstack/react-router", () => ({useNavigate: () => vi.fn(),- useRouteContext: () => ({ session: { user: { id: "fixture" } } }),+ useRouteContext: () => ({ session: { user: { id: account.id } } }),useRouterState: () => "/builder/resume-1",}));-afterEach(() => useCommandPaletteStore.getState().reset());+afterEach(() => {+ cleanup();+ useCommandPaletteStore.getState().reset();+ Object.assign(providers, { hasUsableProvider: true, isUnavailable: false, isLoading: false, error: null });+ vi.clearAllMocks();+ account.id = "fixture";+ account.generation = 0;+});++it("clears the old account's question and setup before showing another account", async () => {+ i18n.loadAndActivate({ locale: "en-US", messages: {} });+ useCommandPaletteStore.setState({ search: "Old account question" });+ providers.hasUsableProvider = false;+ const queryClient = new QueryClient();+ const view = () => (+ <I18nProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <Command>+ <CommandList>+ <AskCommandGroup />+ </CommandList>+ </Command>+ </QueryClientProvider>+ </I18nProvider>+ );+ const { rerender } = render(view());+ fireEvent.click(await screen.findByRole("option", { name: /Ask the assistant/ }));+ expect(await screen.findByRole("dialog", { name: "Set up AI" })).toBeVisible();+ account.id = "replacement";+ account.generation++;+ rerender(view());+ expect(useCommandPaletteStore.getState().search).toBe("");+ expect(screen.queryByRole("dialog", { name: "Set up AI" })).toBeNull();+ expect(openAssistant).not.toHaveBeenCalled();+ queryClient.clear();+});it.each(["question ", " question", "two words"])("keeps Ask visible for whitespace query %j", async (search) => {i18n.loadAndActivate({ locale: "en-US", messages: {} });@@ -41,3 +89,41 @@ it.each(["question ", " question", "two words"])("keeps Ask visible for whitesexpect(openAssistant).toHaveBeenLastCalledWith({ draft: search.trim() });queryClient.clear();});++it.each(["missing", "loading", "failed", "account-changed"])(+ "keeps the task in the palette when provider readiness is %s",+ async (kind) => {+ i18n.loadAndActivate({ locale: "en-US", messages: {} });+ useCommandPaletteStore.setState({ search: "Keep my question" });+ Object.assign(providers, {+ hasUsableProvider: false,+ isUnavailable: kind !== "missing",+ isLoading: kind === "loading",+ error: kind === "failed" ? new Error("Lookup unavailable") : null,+ });+ const queryClient = new QueryClient();+ render(+ <I18nProvider i18n={i18n}>+ <QueryClientProvider client={queryClient}>+ <Command>+ <CommandInput value="Keep my question" />+ <CommandList>+ <AskCommandGroup />+ </CommandList>+ </Command>+ </QueryClientProvider>+ </I18nProvider>,+ );+ const ask = await screen.findByRole("option", { name: /Ask the assistant/ });+ expect(ask).toHaveTextContent(+ kind === "loading" ? "Loading…" : kind === "failed" ? "Try again" : "Connect an AI provider",+ );+ if (kind === "account-changed") account.generation++;+ fireEvent.click(ask);+ expect(openAssistant).not.toHaveBeenCalled();+ expect(useCommandPaletteStore.getState().search).toBe("Keep my question");+ if (kind === "missing") expect(await screen.findByRole("dialog", { name: "Set up AI" })).toBeVisible();+ else expect(providers.retry).toHaveBeenCalledTimes(kind === "failed" ? 1 : 0);+ queryClient.clear();+ },+);diff --git a/apps/web/src/features/command-palette/pages/ask.tsx b/apps/web/src/features/command-palette/pages/ask.tsxindex 8b52a298c..919449161 100644--- a/apps/web/src/features/command-palette/pages/ask.tsx+++ b/apps/web/src/features/command-palette/pages/ask.tsx@@ -2,32 +2,64 @@ import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";import { useQuery } from "@tanstack/react-query";import { useNavigate, useRouteContext, useRouterState } from "@tanstack/react-router";+import { useLayoutEffect, useState } from "react";import { CommandItem } from "@reactive-resume/ui/components/command";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@reactive-resume/ui/components/dialog";import { Icon } from "@reactive-resume/ui/components/icon";import { useCommandPaletteStore } from "../store";import { BaseCommandGroup } from "./base";import { openAssistantFrom } from "@/features/assistant/open";+import { ProviderSetup } from "@/features/assistant/provider-setup";+import { useHasUsableAiProvider } from "@/features/settings/integrations/hooks/use-has-usable-ai-provider";+import { getAccountGeneration } from "@/libs/auth/account-scope";import { orpc } from "@/libs/orpc/client";/** Ask always fills a composer. Outside the editor, the user picks the document first. */export function AskCommandGroup() {- const state = useCommandPaletteStore();const { session } = useRouteContext({ strict: false });+ return session ? <AccountAskCommandGroup key={session.user.id} /> : null;+}++function AccountAskCommandGroup() {+ const state = useCommandPaletteStore();+ const reset = state.reset;+ const providers = useHasUsableAiProvider();+ const [setup, setSetup] = useState(false);+ const generation = getAccountGeneration();+ useLayoutEffect(+ () => () => {+ // Command pages remount this group; only an account change invalidates the whole task.+ if (generation !== getAccountGeneration()) reset();+ },+ [generation, reset],+ );const pathname = useRouterState({ select: (state) => state.location.pathname });const navigate = useNavigate();const picking = state.pages.at(-1) === "ask-documents";const documents = useQuery({...orpc.documents.list.queryOptions({ input: { trashed: false } }),- enabled: !!session && picking,+ enabled: picking,});const question = state.search.trim();- if (!session) return null;+ const ready = () => {+ if (generation !== getAccountGeneration()) return false;+ if (providers.isUnavailable) {+ providers.retry();+ return false;+ }+ if (!providers.hasUsableProvider) {+ setSetup(true);+ return false;+ }+ return true;+ };const choose = async (document: NonNullable<typeof documents.data>[number]) => {const draft = state.askDraft;- if (!draft) return;+ if (!draft || !ready()) return;if (document.type === "letter")await navigate({ to: "/builder/letter/$coverLetterId", params: { coverLetterId: document.id } });else await navigate({ to: "/builder/$resumeId", params: { resumeId: document.id } });+ if (generation !== getAccountGeneration()) return;openAssistantFrom({ draft });state.reset();};@@ -38,6 +70,7 @@ export function AskCommandGroup() {<CommandItemvalue={`ask ${question}`}onSelect={() => {+ if (!ready()) return;if (pathname.startsWith("/builder/")) {openAssistantFrom({ draft: question });state.reset();@@ -46,11 +79,23 @@ export function AskCommandGroup() {state.pushPage("ask-documents");}}}+ disabled={providers.isLoading}><Icon name="sparkle" size={16} /><span className="min-w-0 truncate"><Trans>Ask the assistant “{question}”</Trans></span>+ {!providers.hasUsableProvider && (+ <span className="ms-auto shrink-0 text-xs text-ink-2">+ {providers.isLoading ? (+ <Trans>Loading…</Trans>+ ) : providers.error ? (+ <Trans>Try again</Trans>+ ) : (+ <Trans>Connect an AI provider</Trans>+ )}+ </span>+ )}</CommandItem></BaseCommandGroup>)}@@ -83,6 +128,16 @@ export function AskCommandGroup() {)))}</BaseCommandGroup>+ <Dialog open={setup} onOpenChange={setSetup}>+ <DialogContent closeLabel={t`Close`} className="max-h-[85svh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>+ <Trans>Set up AI</Trans>+ </DialogTitle>+ </DialogHeader>+ <ProviderSetup />+ </DialogContent>+ </Dialog></>);}diff --git a/docs/guides/using-the-assistant.mdx b/docs/guides/using-the-assistant.mdxindex 5ef26c754..67ad5ddb5 100644--- a/docs/guides/using-the-assistant.mdx+++ b/docs/guides/using-the-assistant.mdx@@ -26,6 +26,10 @@ You can also reach it from elsewhere:- In the command bar (<kbd>⌘</kbd> <kbd>K</kbd>), type a question and choose **Ask the assistant**. Outside the editor, choose the document first. The question appears in its composer; review it and press send when ready. See [Using the command bar](/guides/using-the-command-bar).+If no tested provider is enabled, the command bar names that requirement and opens provider setup in place. Closing or+finishing setup keeps your question; choose Ask again to continue. Native Search uses the same setup-before-opening flow+and leaves the question unsent in the named document.+For job search and interview coaching, open **Career → Coach**, or select **Open workspace** in an application and then **Ask the coach**. That coach works with your Knowledge and application context. This guide covers editing resumes and letters; [Career and Application Workspaces](/guides/career-overview) covers the career coach.Both chats start with **What should we work on?** and a list of suggestions. The connection menu names the connectiondiff --git a/docs/guides/using-the-command-bar.mdx b/docs/guides/using-the-command-bar.mdxindex 47fb7384d..4a2eeaf7c 100644--- a/docs/guides/using-the-command-bar.mdx+++ b/docs/guides/using-the-command-bar.mdx@@ -132,8 +132,19 @@ quotes. Choosing it prepares an unsent draft for the [assistant](/guides/using-t- **In the editor**, the question is about the document you have open. The assistant panel opens with your question in the composer. Review it and press Send.- **Anywhere else**, choose a resume or letter from the document picker. Reactive Resume opens that document and fills the composer. Nothing is sent until you press Send and approve the destination. If you have no documents, create one first.-The assistant needs an AI provider. If you haven't connected one, the assistant panel helps you set one up first. See-[Connecting an AI provider](/guides/using-ai).+The assistant needs a tested, enabled AI provider. If none is ready, the Ask row says **Connect an AI provider** before+you leave the command bar. Choose it to connect or repair a provider in place. Closing setup keeps your question here;+connecting doesn't send it. Choose Ask again when ready. Loading or failed connection lookups don't open a document.++<Frame caption="Connect a provider without losing your question">+ <img+ src="/images/guides/using-the-command-bar/palette-provider-needed.png"+ alt="The command palette keeps Tighten my fictional summary in its input and names Connect an AI provider beside Ask."+ />+</Frame>++Native Search also keeps your question while its provider setup sheet is open. The Ask row names the document it will+open; your question waits in that document's composer until you send it. See [Connecting an AI provider](/guides/using-ai).## Related guidesdiff --git a/docs/images/guides/using-the-command-bar/palette-provider-needed.png b/docs/images/guides/using-the-command-bar/palette-provider-needed.pngnew file mode 100644index 000000000..4f537a00dBinary files /dev/null and b/docs/images/guides/using-the-command-bar/palette-provider-needed.png differdiff --git a/tests/e2e/specs/ai-provider-gating.spec.ts b/tests/e2e/specs/ai-provider-gating.spec.tsindex 329843260..9a65c3351 100644--- a/tests/e2e/specs/ai-provider-gating.spec.ts+++ b/tests/e2e/specs/ai-provider-gating.spec.ts@@ -233,6 +233,92 @@ test("palette Ask picks a document and retains an unsent composer draft", async.screenshot({ path: info.outputPath("palette-unsent-draft.png") });});+for (const entry of ["library", "resume", "letter"] as const) {+ test(`palette Ask keeps its question through in-place setup from ${entry}`, async ({ authPage: page }, info) => {+ if (entry === "resume") await page.setViewportSize({ width: 390, height: 844 });+ const resume = await page.request.post("/api/openapi/resumes", {+ data: { name: "Fictional palette resume", tags: [], withSampleData: true },+ });+ await expect(resume).toBeOK();+ const resumeId = (await resume.json()) as string;+ const letter = await page.request.post("/api/openapi/cover-letters", {+ data: { name: "Fictional palette letter" },+ });+ await expect(letter).toBeOK();+ const { id: letterId } = (await letter.json()) as { id: string };+ const path =+ entry === "library"+ ? "/dashboard/applications"+ : entry === "resume"+ ? `/builder/${resumeId}`+ : `/builder/letter/${letterId}`;+ await page.goto(path);+ await expect(page.getByRole("button", { name: "Keyboard shortcuts", exact: true })).toBeVisible();+ await page.keyboard.press("ControlOrMeta+k");+ const palette = page.getByRole("dialog", { name: "Command palette", exact: true });+ const question = "Tighten my fictional summary";+ const input = palette.getByRole("combobox");+ await input.fill(question);+ const ask = palette.getByRole("option", { name: /Ask the assistant/ });+ await expect(ask).toContainText("Connect an AI provider");+ if (entry === "library") await palette.screenshot({ path: info.outputPath("palette-provider-needed.png") });+ const before = stub.requests.length;+ await ask.click();+ const setup = page.getByRole("dialog", { name: "Set up AI", exact: true });+ await expect(setup).toBeVisible();+ await expect(page).toHaveURL(new RegExp(`${path}$`));+ await page.keyboard.press("Escape");+ await expect(setup).toBeHidden();+ await expect(input).toHaveValue(question);+ expect(stub.requests.length).toBe(before);+ await ask.click();+ await setup.getByRole("button", { name: "Other · OpenAI-compatible", exact: true }).click();+ await setup.getByLabel("Base URL").fill(stub.baseURL);+ await setup.getByLabel("Model", { exact: true }).fill("stub");+ await setup.getByLabel("API key", { exact: true }).fill(entry === "library" ? "invalid-stub-key" : "stub-key");+ await setup.getByRole("button", { name: "Connect", exact: true }).click();+ await expect(page.getByRole("alertdialog")).toBeVisible();+ expect(stub.requests.length).toBe(before);+ await consent(page);+ if (entry === "library") {+ await expect(+ setup.getByText("The key was rejected. Check the key and test again.", { exact: true }),+ ).toBeVisible();+ await setup.getByRole("button", { name: "Close", exact: true }).click();+ await expect(input).toHaveValue(question);+ await expect(ask).toContainText("Connect an AI provider");+ await ask.click();+ await setup.getByRole("button", { name: "Edit", exact: true }).click();+ const edit = page.getByRole("dialog", { name: "OpenAI-compatible", exact: true });+ await edit.getByLabel("API key", { exact: true }).fill("stub-key");+ await edit.getByRole("button", { name: "Save and test", exact: true }).click();+ await consent(page);+ await expect(edit).toBeHidden();+ await setup.getByRole("button", { name: "Edit", exact: true }).click();+ const enabled = edit.getByRole("switch", { name: "Use this provider", exact: true });+ if (!(await enabled.isChecked())) await enabled.click();+ await edit.getByRole("button", { name: "Close", exact: true }).click();+ }+ await expect(setup.getByText(/^(Ready|Connected ·)/)).toBeVisible();+ await setup.getByRole("button", { name: "Close", exact: true }).click();+ await expect(input).toHaveValue(question);+ await expect(ask).not.toContainText("Connect an AI provider");+ const afterTest = stub.requests.length;+ if (entry === "library") await palette.screenshot({ path: info.outputPath("palette-provider-ready.png") });+ await ask.click();+ if (entry === "library") {+ await expect(palette).toContainText("Choose a document");+ await palette.getByRole("option", { name: "Fictional palette letter", exact: true }).click();+ await expect(page).toHaveURL(new RegExp(`/builder/letter/${letterId}$`));+ }+ await expect(page.getByLabel("Message the assistant")).toHaveValue(question);+ expect(stub.requests.length).toBe(afterTest);+ const threads = await page.request.get("/api/openapi/agent/threads");+ await expect(threads).toBeOK();+ expect(await threads.json()).toEqual([]);+ });+}+test("unavailable conversation keeps history and pending edits until an approved destination change", async ({authPage: page,}, info) => {