mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 20:29:18 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The chat-feature eval catalog runs real agent conversations and grades the saved outcome > - Chat-eval cohort 16 (OpenCode with a DeepSeek model) had three failures that were not product failures of the chat agent > - One setup check compared time zone names, one observer read a form before it filled, and one grader accepted only exact query digests > - An eval that fails valid behavior hides real regressions behind noise, so each check must grade the outcome, not an incidental detail > - This pull request fixes the three checks, and it fixes a first-frame empty display name on the Profile page > - The benefit is that these three cases now fail only for the behavior they test ## Linked Issues or Issue Description **What happened?** Three chat-eval cases failed in cohort 16 (OpenCode, `openrouter/deepseek/deepseek-v4.1-flash-1017`) on correct behavior. (1) `activity.routine-audit`: setup threw "Browser timezone override did not apply (America/Buenos_Aires)". At 11:00-11:59 UTC the picker selects `America/Argentina/Buenos_Aires`, and Chrome reports that zone by its alias `America/Buenos_Aires`. The check compared names. (2) `navigation-preferences.edit-profile`: the name saved correctly, but the observer read the display-name field once, right after reload, and got an empty value. (3) `budgets-costs.spend-breakdown`: the answer was correct, but the grader accepted company cost reports only for `period=all` or `period=month`. The agent read `costs/by-agent` and `costs/summary` for the requested week, and that range covers the unpriced run. **Expected behavior** Each case passes when the product and the agent do the requested work. Each case fails when they do not. **Steps to reproduce** 1. Run `chat-features.runner-opencode.local.activity.routine-audit` between 11:00 and 11:59 UTC. 2. Run `chat-features.runner-opencode.local.navigation-preferences.edit-profile` and look at `profileAfterReload`. 3. Grade the retained cohort 16 observation of `budgets-costs.spend-breakdown` with the old grader. **Additional context** The run tool inputs are saved only as SHA-256 digests, so a grader binds a read by recomputing the digest of inputs it can check. For the cohort 16 spend-breakdown reads, the inputs were recovered this way: `from=2026-11-09T00:00:00.000Z`, `to=2026-11-16T00:00:00.000Z`. ## What Changed - `internal-routine-audit.ts`: the browser override check compares the UTC offset of the requested and reported zones, now and 182 days later, instead of the zone names. An unknown zone or a different clock still fails setup. - `identity-profile.ts`: after reload, `settledFieldValue` waits up to 15 s for the display name to reach the saved value, then records what the person sees. The grade still fails a name that does not arrive. - `ProfileSettings.tsx`: unedited fields show the session's saved name and image from the first frame. Before, a session restored from the saved read cache rendered an empty name until an effect filled it. - `identity-accounting.ts`: `readSavedAccounting` also accepts a company cost report whose checked `from`/`to` covers the unpriced run's cost event. The run log keeps only the input digest, so the grader recomputes digests for covering ranges: UTC day boundaries (with or without milliseconds or seconds, date-only, end of day), local midnights at each whole-hour offset, and the run's own `startedAt` and cost-event instants. A pending run (no cost event) counts only through `costs/summary`, `costs/data-quality` or its own run record, because the other reports sum cost events. A link to the run does not count, because the run id is in the task description. The run-log redaction is not changed. - Oracle versions bumped: `routine-audit.v7`, `spend-breakdown.structural.v6`, `identity-profile.v4`. ## Verification - Red/green: each new test fails on the old code and passes on the new code. - `internal-remaining.test.ts`: every candidate zone, reported by its own name, its ICU name and known browser aliases, passes at every hour in January and July. A different clock, a zone with daylight saving time and an unknown name fail. - `identity-personal.test.ts`: the settled read returns the saved name after empty reads, and returns a wrong name when the saved name never arrives. - `ProfileSettings.test.tsx`: the first rendered frame with a cached session shows "Alex Chen", not `""`. - `identity-accounting.test.ts`: the cohort 16 week-range reads pass, as do other covering ranges. Negative controls fail: no reads, run-list reads with unchecked inputs, ranges that exclude the run, another company, a denied read, a read by another run, and a read of a different run record with a link to the target run. - The retained cohort 16 spend-breakdown observation passes the new grader, and fails with its reads removed. - `pnpm test:e2e:runner:unit`: 686 files passed. `pnpm test:e2e:runner:typecheck` passed. `ui` ProfileSettings tests passed. `scripts/check-token-gates.mjs` is clean. - One narrow paid run of the three cases on this branch (result in a comment below). ## Risks - Low risk. The changes are in eval code, plus a small Profile page state change. - A covering range in a form outside the recomputed set (for example 08:00 at -03:00) is not recognized. That is a false negative, not a false pass. - The Profile page now keeps an unedited field in step with the session. A refetch still resets drafts, as before. ## Model Used - Claude, model ID `claude-opus-5-5`, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
296 lines
12 KiB
TypeScript
296 lines
12 KiB
TypeScript
import { useEffect, useId, useRef, useState } from "react";
|
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { Camera, LoaderCircle, Save, Trash2, UserRoundPen } from "lucide-react";
|
|
import type { AuthSession, CurrentUserProfile, UpdateCurrentUserProfile } from "@paperclipai/shared";
|
|
import { authApi } from "@/api/auth";
|
|
import { useAccountBoundMutation } from "@/hooks/useAccountBoundMutation";
|
|
import { assetsApi } from "@/api/assets";
|
|
import { QueryErrorState, useQueryView } from "@/components/QueryView";
|
|
import { useBreadcrumbs } from "../context/BreadcrumbContext";
|
|
import { useCompany } from "../context/CompanyContext";
|
|
import { queryKeys } from "../lib/queryKeys";
|
|
import { InboxAgentPolicyControl } from "@/components/InboxAgentPolicyControl";
|
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
import { Card } from "@/components/ui/card";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Label } from "@/components/ui/label";
|
|
import { describeError } from "@/api/errors";
|
|
|
|
function deriveInitials(name: string) {
|
|
const parts = name.trim().split(/\s+/).filter(Boolean);
|
|
if (parts.length >= 2) return `${parts[0]?.[0] ?? ""}${parts[parts.length - 1]?.[0] ?? ""}`.toUpperCase();
|
|
return name.slice(0, 2).toUpperCase();
|
|
}
|
|
|
|
export function ProfileSettings() {
|
|
const { setBreadcrumbs } = useBreadcrumbs();
|
|
const { selectedCompanyId, selectedCompany } = useCompany();
|
|
const queryClient = useQueryClient();
|
|
const avatarInputId = useId();
|
|
const avatarInputRef = useRef<HTMLInputElement | null>(null);
|
|
// Unedited fields show the session's saved values from the first frame; a
|
|
// restored session must not render an empty name until an effect fills it.
|
|
const [nameDraft, setName] = useState<string | null>(null);
|
|
const [imageDraft, setImage] = useState<string | null>(null);
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
const sessionQuery = useQuery({
|
|
queryKey: queryKeys.auth.session,
|
|
queryFn: () => authApi.getSession(),
|
|
});
|
|
const sessionView = useQueryView(sessionQuery);
|
|
const name = nameDraft ?? sessionQuery.data?.user.name ?? "";
|
|
const image = imageDraft ?? sessionQuery.data?.user.image ?? "";
|
|
|
|
useEffect(() => {
|
|
setBreadcrumbs([
|
|
{ label: "Settings", href: "/company/settings" },
|
|
{ label: "Profile" },
|
|
]);
|
|
}, [setBreadcrumbs]);
|
|
|
|
useEffect(() => {
|
|
setName(null);
|
|
setImage(null);
|
|
}, [sessionQuery.data]);
|
|
|
|
function syncSessionProfile(profile: CurrentUserProfile) {
|
|
queryClient.setQueryData<AuthSession | null>(queryKeys.auth.session, (current) => {
|
|
if (!current) return current;
|
|
return {
|
|
...current,
|
|
user: {
|
|
...current.user,
|
|
...profile,
|
|
},
|
|
};
|
|
});
|
|
}
|
|
|
|
// A restored session can show one account while the cookie belongs to
|
|
// another, and the server saves for the cookie's user. Account-bound
|
|
// mutations wait for a verified session and abort if the user changed.
|
|
async function persistProfile(input: UpdateCurrentUserProfile, assertCurrentAccount: () => void) {
|
|
assertCurrentAccount();
|
|
const profile = await authApi.updateProfile(input);
|
|
assertCurrentAccount();
|
|
syncSessionProfile(profile);
|
|
return profile;
|
|
}
|
|
|
|
function resolveProfileName() {
|
|
return name.trim() || sessionQuery.data?.user.name || "Board";
|
|
}
|
|
|
|
const updateMutation = useAccountBoundMutation({
|
|
mutationFn: (input: UpdateCurrentUserProfile, { assertCurrentAccount }) => persistProfile(input, assertCurrentAccount),
|
|
onSuccess: (profile) => {
|
|
setActionError(null);
|
|
setName(profile.name ?? "");
|
|
setImage(profile.image ?? "");
|
|
},
|
|
onError: (error) => {
|
|
setActionError(describeError(error).body);
|
|
},
|
|
});
|
|
|
|
const uploadAvatarMutation = useAccountBoundMutation({
|
|
mutationFn: async (file: File, { assertCurrentAccount }) => {
|
|
if (!selectedCompanyId) {
|
|
throw new Error("Select an organization before uploading a profile avatar.");
|
|
}
|
|
|
|
const asset = await assetsApi.uploadImage(
|
|
selectedCompanyId,
|
|
file,
|
|
`profiles/${sessionQuery.data?.user.id ?? "board-user"}`,
|
|
);
|
|
return persistProfile({ name: resolveProfileName(), image: asset.contentPath }, assertCurrentAccount);
|
|
},
|
|
onSuccess: (profile) => {
|
|
setActionError(null);
|
|
setName(profile.name ?? "");
|
|
setImage(profile.image ?? "");
|
|
},
|
|
onError: (error) => {
|
|
setActionError(describeError(error).body);
|
|
},
|
|
});
|
|
|
|
const removeAvatarMutation = useAccountBoundMutation({
|
|
mutationFn: (_input, { assertCurrentAccount }) => persistProfile({ name: resolveProfileName(), image: null }, assertCurrentAccount),
|
|
onSuccess: (profile) => {
|
|
setActionError(null);
|
|
setName(profile.name ?? "");
|
|
setImage(profile.image ?? "");
|
|
},
|
|
onError: (error) => {
|
|
setActionError(describeError(error).body);
|
|
},
|
|
});
|
|
|
|
if (sessionQuery.isLoading || sessionView.kind === "reconnecting") {
|
|
return <div className="text-sm text-muted-foreground">Loading profile...</div>;
|
|
}
|
|
|
|
if (sessionView.kind === "error") {
|
|
return (
|
|
<QueryErrorState
|
|
size="page"
|
|
error={sessionQuery.error}
|
|
action="load your profile"
|
|
onRetry={sessionView.retry}
|
|
retrying={sessionView.isFetching}
|
|
/>
|
|
);
|
|
}
|
|
|
|
if (!sessionQuery.data) {
|
|
return <div className="text-sm text-destructive">Failed to load profile.</div>;
|
|
}
|
|
|
|
const currentName = name.trim() || sessionQuery.data.user.name || "Board";
|
|
const currentImage = image.trim() || null;
|
|
const initials = deriveInitials(currentName);
|
|
const isSavingProfile = updateMutation.isPending || uploadAvatarMutation.isPending || removeAvatarMutation.isPending;
|
|
const uploadHint = selectedCompany
|
|
? `Stored in Paperclip file storage for ${selectedCompany.name}.`
|
|
: "Select an organization to upload an avatar into Paperclip storage.";
|
|
|
|
return (
|
|
<div className="max-w-6xl space-y-6">
|
|
<div className="space-y-2">
|
|
<div className="flex items-center gap-2">
|
|
<UserRoundPen className="h-5 w-5 text-muted-foreground" />
|
|
<h1 className="text-lg font-semibold">Profile</h1>
|
|
</div>
|
|
<p className="text-sm text-muted-foreground">
|
|
Control how your account appears in the sidebar and other board surfaces.
|
|
</p>
|
|
</div>
|
|
|
|
{actionError ? (
|
|
<div className="rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive">
|
|
{actionError}
|
|
</div>
|
|
) : null}
|
|
|
|
<section className="space-y-8">
|
|
<Card className="block relative overflow-hidden rounded-(--rad-28) border-border/70">
|
|
<div className="absolute inset-x-0 top-0 h-32 bg-(image:--gradient-extract-26)" />
|
|
<div className="absolute inset-0 bg-(image:--gradient-extract-7)" />
|
|
<div className="relative p-6 pt-10">
|
|
<div className="flex flex-wrap items-end gap-5 rounded-(--rad-24) border border-border/70 bg-background/92 p-5 shadow-(--shadow-extract-18) backdrop-blur-sm">
|
|
<div className="space-y-3">
|
|
<label
|
|
htmlFor={avatarInputId}
|
|
className="group relative block cursor-pointer rounded-full focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background"
|
|
>
|
|
<input
|
|
ref={avatarInputRef}
|
|
id={avatarInputId}
|
|
type="file"
|
|
accept="image/*"
|
|
className="sr-only"
|
|
disabled={!selectedCompanyId || isSavingProfile}
|
|
onChange={(event) => {
|
|
const file = event.target.files?.[0];
|
|
if (!file) return;
|
|
uploadAvatarMutation.mutate(file);
|
|
event.target.value = "";
|
|
}}
|
|
/>
|
|
<span className="absolute inset-0 z-10 rounded-full bg-black/0 transition-colors group-hover:bg-black/14 group-focus-within:bg-black/14" />
|
|
<span className="absolute bottom-1 right-1 z-20 flex size-9 items-center justify-center rounded-full border border-background bg-primary text-primary-foreground shadow-sm">
|
|
{uploadAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Camera className="size-4" />}
|
|
</span>
|
|
<Avatar size="lg" className="data-[size=lg]:size-24 ring-4 ring-background shadow-xl">
|
|
{currentImage ? <AvatarImage src={currentImage} alt={currentName} /> : null}
|
|
<AvatarFallback>{initials}</AvatarFallback>
|
|
</Avatar>
|
|
</label>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<Button
|
|
type="button"
|
|
variant="secondary"
|
|
onClick={() => avatarInputRef.current?.click()}
|
|
disabled={!selectedCompanyId || isSavingProfile}
|
|
>
|
|
{uploadAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Camera className="size-4" />}
|
|
{currentImage ? "Change photo" : "Upload photo"}
|
|
</Button>
|
|
{currentImage ? (
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={() => removeAvatarMutation.mutate()}
|
|
disabled={isSavingProfile}
|
|
>
|
|
{removeAvatarMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
|
|
Remove
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="min-w-0 flex-1 space-y-2 pb-1">
|
|
<div>
|
|
<h2 className="truncate text-2xl font-semibold text-foreground">{currentName}</h2>
|
|
<p className="truncate text-sm text-muted-foreground">{sessionQuery.data.user.email ?? "No email"}</p>
|
|
</div>
|
|
<p className="max-w-2xl text-sm leading-6 text-muted-foreground">
|
|
Click the avatar to upload a new image. {uploadHint}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
<form
|
|
className="grid gap-6 md:grid-cols-2"
|
|
onSubmit={(event) => {
|
|
event.preventDefault();
|
|
updateMutation.mutate({ name: resolveProfileName(), image: image.trim() || null });
|
|
}}
|
|
>
|
|
<div className="space-y-2">
|
|
<Label htmlFor="profile-name">Display name</Label>
|
|
<Input
|
|
id="profile-name"
|
|
value={name}
|
|
onChange={(event) => setName(event.target.value)}
|
|
maxLength={120}
|
|
placeholder="Board"
|
|
/>
|
|
<p className="text-xs text-muted-foreground">
|
|
Shown in the sidebar account footer and comment author surfaces.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="profile-email">Email</Label>
|
|
<Input
|
|
id="profile-email"
|
|
value={sessionQuery.data.user.email ?? ""}
|
|
readOnly
|
|
disabled
|
|
/>
|
|
<p className="text-xs text-muted-foreground">
|
|
Email is managed by your auth session and is read-only here.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="md:col-span-2 flex justify-end">
|
|
<Button type="submit" disabled={isSavingProfile || !name.trim()}>
|
|
{updateMutation.isPending ? <LoaderCircle className="size-4 animate-spin" /> : <Save className="size-4" />}
|
|
{updateMutation.isPending ? "Saving..." : "Save profile"}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
|
|
<InboxAgentPolicyControl companyId={selectedCompanyId} />
|
|
</section>
|
|
</div>
|
|
);
|
|
}
|