Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(onboarding): address review: alphaXiv connection state, dead prof…
…ile client, egress docs

Assisted-by: claude-opus-5.5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
myles332 and claude committed Nov 5, 2026
commit 537534b87887b8b3408b8d9743ab2422318a0eb9
2 changes: 1 addition & 1 deletion arc/remote.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ permissions, and never changes a shared install itself. Installing or updating
database and cache paths visible and changeable.

A new remote machine opens agent configuration without repeating the welcome,
research profile or demo setup. Agent installations and sign-ins belong to each
alphaXiv sign-in or demo setup. Agent installations and sign-ins belong to each
machine; the account picker and paper library continue to use the laptop account.
Installing or signing in to Claude Code with a subscription first checks the
remote's public egress IP; a known datacenter address prompts once per setup,
Expand Down
10 changes: 7 additions & 3 deletions arc/storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,12 @@ endpoints out of it. Other traffic:
`orx login --alphaxiv`, to link alphaXiv to the signed-in account. orx keeps
alphaXiv's tokens owner-only in the config directory, refreshing them under
a file lock since each refresh retires the last one, and reads the user's
folders and papers with them. The chat's library picker loads paper
thumbnails from alphaXiv's public asset CDN. Agents also send research tool
folders and papers with them. It also reads the user's public alphaXiv
profile, followed topics and researcher card: the dashboard shows the
profile picture alphaXiv names, and a blank project's starter prompts are
briefed from the profile, so it reaches the agent's model provider. The
chat's library picker loads paper thumbnails from alphaXiv's public asset
CDN. Agents also send research tool
calls to alphaXiv while signed out, limited by IP. Signed-in agents read
library notes and highlights and, when requested, create folders and save
papers to them. Tool arguments (including research queries, paper and
Expand All @@ -174,7 +178,7 @@ endpoints out of it. Other traffic:
experiments or logs of its own.
- **Telemetry.** Official builds send opt-out usage events to the first-party
API under a random install ID that is not tied to an account: commands run,
harness detection states, and the research profile chosen at onboarding.
harness detection states, and a research profile when onboarding submits one.
Source builds send nothing. Events wait in an outbox in the config directory
and send in the background, so telemetry never blocks or fails a command. A
change of the telemetry choice is itself recorded, so opt-outs are visible.
Expand Down
83 changes: 61 additions & 22 deletions src/alphaxiv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ use crate::error::{anyhow, Result};
const CLIENT_ID: &str = "openresearch-desktop";

const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
const PROFILE_TTL: Duration = Duration::from_secs(600);
const MAX_PROFILE_AREAS: usize = 20;

#[derive(Debug)]
pub struct NotConnected;
Expand Down Expand Up @@ -379,7 +381,7 @@ async fn get(path: &str, query: &[(&str, &str)]) -> Result<Value> {
.await?
.json()
.await
.map_err(|_| anyhow!("alphaXiv returned an incorrect library response."))
.map_err(|_| anyhow!("alphaXiv returned an unexpected response."))
}

pub async fn folders() -> Result<Value> {
Expand Down Expand Up @@ -450,15 +452,32 @@ pub async fn me() -> Result<Value> {
Ok(serde_json::json!({ "avatarUrl": url("thumbnail").or_else(|| url("full_size")) }))
}

/// What the signed-in researcher shows publicly on alphaXiv: the token only
/// reaches library routes, so this reads the public profile its `sub` names.
/// The signed-in researcher's public alphaXiv profile, remembered briefly so
/// reopening an empty chat neither waits on alphaXiv nor changes its brief.
/// alphaXiv has no route for the caller's own profile, so this reads the public
/// one the token's `sub` names.
pub async fn research_profile() -> Result<crate::telemetry::ResearchProfile> {
type Memo = Option<(
String,
std::time::Instant,
crate::telemetry::ResearchProfile,
)>;
static MEMO: std::sync::Mutex<Memo> = std::sync::Mutex::new(None);
let id = user_id().await?;
let memo = |memo: &Memo| {
memo.as_ref()
.filter(|(user, at, _)| *user == id && at.elapsed() < PROFILE_TTL)
.map(|(_, _, profile)| profile.clone())
};
if let Some(profile) = memo(&MEMO.lock().unwrap_or_else(|e| e.into_inner())) {
return Ok(profile);
}
let (user_path, topics_path) = (
format!("/users/v3/{id}"),
format!("/users/v3/{id}/following/topics"),
);
let (user, topics) = tokio::try_join!(get(&user_path, &[]), get(&topics_path, &[]))?;
let (user, topics) = tokio::join!(get(&user_path, &[]), get(&topics_path, &[]));
let user = user?;
let text = |value: &Value, key: &str| {
value
.get(key)
Expand All @@ -473,19 +492,25 @@ pub async fn research_profile() -> Result<crate::telemetry::ResearchProfile> {
.ok(),
None => None,
};
let strings = |value: Option<&Value>, key: Option<&str>| {
value
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|item| key.map_or(Some(item), |key| item.get(key))?.as_str())
.map(str::to_owned)
.collect::<Vec<_>>()
};
let mut research_areas = strings(card.as_ref().and_then(|c| c.get("researchAreas")), None);
for topic in strings(topics.get("topics"), Some("topic")) {
if !research_areas.contains(&topic) {
research_areas.push(topic);
let areas = card
.as_ref()
.and_then(|card| card.get("researchAreas"))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str);
let followed = topics.ok();
let followed = followed
.as_ref()
.and_then(|topics| topics.get("topics"))
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|topic| topic.get("topic")?.as_str());
let mut research_areas = Vec::<String>::new();
for area in areas.chain(followed) {
if research_areas.len() < MAX_PROFILE_AREAS && !research_areas.iter().any(|a| a == area) {
research_areas.push(area.to_owned());
}
}
let card_text = |key| card.as_ref().and_then(|card| text(card, key));
Expand All @@ -498,12 +523,14 @@ pub async fn research_profile() -> Result<crate::telemetry::ResearchProfile> {
.flatten()
.collect::<Vec<_>>()
.join("\n");
Ok(crate::telemetry::ResearchProfile {
let profile = crate::telemetry::ResearchProfile {
research_areas,
other_area: None,
background: (!background.is_empty()).then_some(background),
papers: Vec::new(),
})
..Default::default()
};
*MEMO.lock().unwrap_or_else(|e| e.into_inner()) =
Some((id, std::time::Instant::now(), profile.clone()));
Ok(profile)
}

pub async fn print_library(json: bool) -> Result<()> {
Expand Down Expand Up @@ -670,7 +697,15 @@ mod tests {
.route(
"/users/v3/u1",
get(|| async {
Json(json!({ "researcherSlug": "ada", "institution": "MIT", "biography": " " }))
Json(json!({
"researcherSlug": "ada",
"institution": "MIT",
"biography": " ",
"avatar": [
{ "type": "full_size", "url": "https://cdn/full.png" },
{ "type": "thumbnail", "url": "https://cdn/thumb.png" },
],
}))
}),
)
.route(
Expand Down Expand Up @@ -754,6 +789,10 @@ mod tests {
profile.background.as_deref(),
Some("PhD student\nMIT\nLearns to walk.")
);
assert_eq!(
me().await.unwrap(),
json!({ "avatarUrl": "https://cdn/thumb.png" })
);

// Sign-out revokes the refresh token at alphaXiv and forgets both.
sign_out().await.unwrap();
Expand Down
10 changes: 2 additions & 8 deletions src/commands/up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1097,9 +1097,6 @@ fn normalize_research_profile(
background: Option<String>,
papers: Vec<crate::telemetry::ProfilePaper>,
) -> std::result::Result<crate::telemetry::ResearchProfile, ApiError> {
if research_areas.is_empty() {
return Err(bad_request("choose at least one research area"));
}
let mut normalized_areas = Vec::with_capacity(research_areas.len());
for area in research_areas {
let area = area.trim().to_string();
Expand Down Expand Up @@ -1153,7 +1150,7 @@ async fn complete_onboarding(
permission_mode,
reasoning_level: nonempty(req.reasoning_level),
};
// Onboarding no longer asks for a profile; an empty one must not erase a saved one.
// A request without areas carries no profile and must not erase a saved one.
let profile = (!req.research_areas.is_empty())
.then(|| {
normalize_research_profile(
Expand Down Expand Up @@ -10099,10 +10096,7 @@ mod tests {
}

#[test]
fn research_profile_requires_an_area_and_other_description() {
let missing_area = normalize_research_profile(vec![], None, None, vec![]).unwrap_err();
assert_eq!(missing_area.1, "choose at least one research area");

fn research_profile_requires_an_other_description() {
let missing_other =
normalize_research_profile(vec!["Other".into()], Some(" ".into()), None, vec![])
.unwrap_err();
Expand Down
19 changes: 0 additions & 19 deletions ui/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -897,20 +897,6 @@ export interface GitSettings {
githubAuthenticated: boolean;
}

/** A paper linked to the researcher profile during onboarding. */
export interface LinkedPaper {
paperId: string;
title: string | null;
}

/** The local researcher profile captured in onboarding (settings.json). */
export interface Profile {
researchAreas: string[];
otherArea: string | null;
background: string | null;
papers: LinkedPaper[];
}

/** Which literature sources discovery and paper reading may use (settings.json). */
export interface LitSourcesSettings {
alphaxiv: boolean;
Expand Down Expand Up @@ -2275,9 +2261,6 @@ export function createApi(
const saveGitSettings = (body: { userName?: string; userEmail?: string }) =>
post<GitSettings>("/api/settings/git", body);

const getProfile = (signal?: AbortSignal) => get<Profile>("/api/settings/profile", signal);

const setProfile = (body: Profile) => post<Profile>("/api/settings/profile", body);

const getLitSources = (signal?: AbortSignal) =>
get<LitSourcesSettings>("/api/settings/lit-sources", signal);
Expand Down Expand Up @@ -2728,8 +2711,6 @@ export function createApi(
getArtifactFileMetadata,
getGitSettings,
saveGitSettings,
getProfile,
setProfile,
getLitSources,
setLitSources,
getProjectDefaults,
Expand Down
1 change: 1 addition & 0 deletions ui/src/components/AccountChip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export function useSignIn() {
invalidateFamilies(["getOpenResearchAccount", "getOpenResearchSettings", "getComputeSettings"]);
void queryClient.invalidateQueries({ queryKey: workspaceKey("alphaXivFolders") });
void queryClient.invalidateQueries({ queryKey: workspaceKey("alphaXivPapers") });
void queryClient.invalidateQueries({ queryKey: workspaceKey("alphaXivMe") });
}

return (connectOnly: boolean, returnFocus: HTMLElement | null, onSignedIn?: () => void) => {
Expand Down
50 changes: 33 additions & 17 deletions ui/src/components/Onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {
type OnboardingStep,
type Project,
type UiState,
AlphaXivNotConnectedError,
type OpenResearchAccount as OpenResearchAccountInfo,
} from "../api";
import { renderNote } from "./agentNote";
import { claudeProviderLabel } from "./claudeProvider";
Expand Down Expand Up @@ -52,11 +54,6 @@ const GIT_RETRY_HINT_CLASS_NAME = [
"text-text onb-git-hint mt-2",
].join(" ");

const ONB_CARD_CLASS_NAME = [
"onb-card flex flex-col gap-1 bg-background",
"border border-border rounded-lg py-4.5 px-5",
].join(" ");

const FINISH_ERROR_CLASS_NAME = [
"onb-gate-hint mt-4.5 mx-0 mb-0 text-base font-medium leading-normal",
"text-text",
Expand Down Expand Up @@ -88,7 +85,13 @@ export function Onboarding(props: OnboardingProps) {
refreshHarnesses,
} = useWorkspace().queries;
const { queryClient, workspaceScope, isCurrentScope } = useWorkspace();
const alphaXivLinked = !!useMachines().owner.queries.useOpenResearchAccount().data?.user;
const { useOpenResearchAccount, useAlphaXivMe } = useMachines().owner.queries;
const accountQuery = useOpenResearchAccount();
const alphaXivMe = useAlphaXivMe();
const user = accountQuery.data?.user ?? null;
// An OpenResearch account without an alphaXiv connection still needs to connect it.
const connectOnly = !!user && alphaXivMe.error instanceof AlphaXivNotConnectedError;
const alphaXivLinked = !!user && !connectOnly;

const completeOnboardingMutation = useMutation({ mutationFn: completeOnboarding });

Expand Down Expand Up @@ -278,6 +281,10 @@ export function Onboarding(props: OnboardingProps) {
}
};

// Sign-in resolves several renders after the click; finish with what is true by then.
const latestFinish = useRef(finishOnboarding);
latestFinish.current = finishOnboarding;

const openAuth = (harness: Harness) => showCustomDialog({
component: AcpAuthDialog,
props: { remote, harness, onReady: (ready) => setPreferredHarness(ready.id) },
Expand Down Expand Up @@ -475,7 +482,13 @@ export function Onboarding(props: OnboardingProps) {
</div>
<h2 className="onb-title mt-0 mx-0 mb-3 text-5xl tracking-tight">{m.onboarding_alphaxiv_title()}</h2>
<p className="onb-sub text-text text-lg leading-normal mt-0 mx-0 mb-8 max-w-150">{m.onboarding_alphaxiv_description()}</p>
<AlphaXivAccountCard onSignedIn={() => void finishOnboarding()} />
<AlphaXivAccountCard
user={alphaXivLinked ? user : null}
avatarUrl={alphaXivMe.data?.avatarUrl ?? null}
connectOnly={connectOnly}
disabled={accountQuery.isLoading || finishing}
onSignedIn={() => void latestFinish.current()}
/>
{automaticSetup && !gitReady && (
<div className="mt-5" role="status">
<LocalGitCard gitVersion={gitVersion} error={gitError} />
Expand Down Expand Up @@ -707,27 +720,30 @@ function GitInstallPrompt({
);
}

function AlphaXivAccountCard({ onSignedIn }: { onSignedIn: () => void }) {
const { useOpenResearchAccount, useAlphaXivMe } = useMachines().owner.queries;
const accountQuery = useOpenResearchAccount();
const avatarUrl = useAlphaXivMe().data?.avatarUrl;
const [avatarFailed, setAvatarFailed] = useState(false);
function AlphaXivAccountCard({ user, avatarUrl, connectOnly, disabled, onSignedIn }: {
user: OpenResearchAccountInfo["user"];
avatarUrl: string | null;
connectOnly: boolean;
disabled: boolean;
onSignedIn: () => void;
}) {
const openSignIn = useSignIn();
const card = useRef<HTMLDivElement>(null);
const user = accountQuery.data?.user;
const [failedAvatar, setFailedAvatar] = useState<string | null>(null);
const initial = user && ([user.firstName, user.lastName].filter(Boolean).join(" ") || user.email).trim().charAt(0).toLocaleUpperCase();
return (
// Sign-in swaps the button for the account card; the dialog returns focus here.
<div ref={card} tabIndex={-1} className="outline-none">
{user ? (
<div className="flex items-center gap-4 rounded-lg border border-border bg-background px-5 py-4">
{avatarUrl && !avatarFailed
? <img src={avatarUrl} alt="" className="size-12 shrink-0 rounded-full object-cover" onError={() => setAvatarFailed(true)} />
{avatarUrl && avatarUrl !== failedAvatar
? <img src={avatarUrl} alt="" className="size-12 shrink-0 rounded-full object-cover" onError={() => setFailedAvatar(avatarUrl)} />
: <span className="flex size-12 shrink-0 items-center justify-center rounded-full bg-panel text-lg font-medium text-text" aria-hidden="true">{initial}</span>}
<span className="min-w-0 flex-1 text-base"><OpenResearchAccount user={user} /></span>
<StatusIndicator tone="success">{m.onboarding_signed_in()}</StatusIndicator>
</div>
) : (
<Button size="large" className="h-16 w-full justify-center text-lg" disabled={accountQuery.isLoading} onClick={() => openSignIn(false, card.current, onSignedIn)} aria-haspopup="dialog">
<Button size="large" className="h-16 w-full justify-center text-lg" disabled={disabled} onClick={() => openSignIn(connectOnly, card.current, onSignedIn)} aria-haspopup="dialog">
<LitSourceLogo source="alphaxiv" size={24} decorative />{m.account_sign_in_alphaxiv()}
</Button>
)}
Expand All @@ -743,7 +759,7 @@ function LocalGitCard({
error: boolean;
}) {
return (
<div className={ONB_CARD_CLASS_NAME}>
<div className="onb-card flex flex-col gap-1 bg-background border border-border rounded-lg py-4.5 px-5">
<div className="onb-card-head flex items-center justify-between gap-3">
<span className="onb-card-name font-semibold text-base">{m.onboarding_local_git()}</span>
<StatusIndicator tone={gitVersion ? "success" : error || gitVersion === null ? "danger" : "warning"}>
Expand Down
3 changes: 1 addition & 2 deletions ui/src/queries/invalidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ const settingsFamilies: Record<string, readonly string[]> = {
compute: ["getComputeSettings"],
openresearch: ["getOpenResearchSettings", "getOpenResearchAccount", "getComputeSettings"],
git: ["githubAccount", "repoAccess", "getProjectGitStatus"],
profile: ["getProfile"],
"lit-sources": ["getLitSources"],
projects: ["getProjectDefaults", "getProjectGitStatus"],
telemetry: ["getTelemetry"],
Expand Down Expand Up @@ -150,7 +149,7 @@ export function createInvalidation(client: WorkspaceClient) {
invalidate(["getProjectGitStatus", "getCodeTree", "getProjectStarterPrompts"], scope, (query) => query.queryKey[3] === projectId);
return;
}
if (path === "/api/projects" || path === "/api/onboarding/complete") invalidate(["listProjects", "listProjectActivity", "getUiState", "getProfile"], scope);
if (path === "/api/projects" || path === "/api/onboarding/complete") invalidate(["listProjects", "listProjectActivity", "getUiState"], scope);
}

return {
Expand Down
Loading