From c38b59484c66a7c7256f3fa2e2c52e2d46db06df Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Thu, 3 Sep 2026 23:26:08 -0700 Subject: [PATCH 1/3] fix(ui): remove the Account badge and version line from the account menu (#12818) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The web UI has a sidebar account menu that opens from the user's name in the lower left > - The menu header shows an "Account"/"Local" badge and a "Paperclip " (or "Paperclip v") build line next to the user's identity > - These labels add noise to the header and repeat information that is available elsewhere: the email line already shows the sign-in state, and the opt-in "Server" debug section in the same menu shows the running commit > - This pull request removes the badge and the build line so the header shows only the user's name and email > - The benefit is a cleaner account menu that shows only identity information ## Linked Issues or Issue Description No existing issue. Related: #9637 (closed) added the source-sha rendering that this PR removes from the menu header. Description follows the enhancement template: **What existing behavior does this improve?** The sidebar account menu popover. Its header shows the user's name, an "Account" or "Local" badge, the email, and a build identifier line ("Paperclip " with branch/commit links for source builds, or "Paperclip v" for release builds). **Current behavior** The popover header mixes identity information with deployment and build metadata. The badge and the version line take space and do not help daily use. **Proposed behavior** The popover header shows only the user's name and email. Build information stays available in the "Server" section at the bottom of the same menu when the server-info debug view is enabled in experimental instance settings. **Reason and benefit** Less visual noise in a menu that users open often. No information is lost: sign-in state is clear from the email line, and the running commit remains visible through the server-info debug view. **Breaking changes** None. The `SidebarAccountMenu` components no longer accept the `serverGit` and `version` props; both call sites in the two `Layout` variants are updated in this PR. ## What Changed - `ui/src/components/SidebarAccountMenu.tsx` and `SidebarAccountMenu.production.tsx`: remove the "Account"/"Local" badge and the full version block (source-build branch/commit links and the release-version fallback); drop the now-unused `serverGit`/`version` props, the sha-parsing helper, and the `Badge` import - `ui/src/components/Layout.tsx` and `Layout.production.tsx`: stop passing the removed props at all four call sites - `ui/src/components/SidebarAccountMenu.test.tsx`: delete the source-build sha test; the sign-out test now pins that the popover contains neither "Account" nor "Paperclip v" - `ui/storybook/stories/navigation-layout.stories.tsx`: stop passing the removed `version` prop in the account-menu story ## Verification - `pnpm vitest run ui/src/components/SidebarAccountMenu.test.tsx ui/src/components/Layout.test.tsx` — 36 tests pass - `tsc --noEmit` for the `ui` package passes - Manual: open the app, click your name in the lower left. The popover header shows only name and email. ## Risks - Low risk. UI-only removal with no data or API changes. - Users who relied on the header sha to identify a source build must enable the experimental server-info debug view to see the running commit in the same menu. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude (Anthropic), Claude Fable 5, model ID `claude-fable-5`, extended thinking enabled, via Claude Code CLI with tool use (file edit, shell, test runner) ## 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 --- ui/src/components/Layout.production.tsx | 4 -- ui/src/components/Layout.tsx | 4 -- .../SidebarAccountMenu.production.tsx | 55 +----------------- ui/src/components/SidebarAccountMenu.test.tsx | 58 ++----------------- ui/src/components/SidebarAccountMenu.tsx | 55 +----------------- .../stories/navigation-layout.stories.tsx | 1 - 6 files changed, 8 insertions(+), 169 deletions(-) diff --git a/ui/src/components/Layout.production.tsx b/ui/src/components/Layout.production.tsx index 2903267e57..12621fca3b 100644 --- a/ui/src/components/Layout.production.tsx +++ b/ui/src/components/Layout.production.tsx @@ -604,8 +604,6 @@ export function Layout() { ) : ( @@ -624,8 +622,6 @@ export function Layout() { )} diff --git a/ui/src/components/Layout.tsx b/ui/src/components/Layout.tsx index b308eb394f..99b7fba771 100644 --- a/ui/src/components/Layout.tsx +++ b/ui/src/components/Layout.tsx @@ -659,8 +659,6 @@ export function Layout() { @@ -684,8 +682,6 @@ export function Layout() { diff --git a/ui/src/components/SidebarAccountMenu.production.tsx b/ui/src/components/SidebarAccountMenu.production.tsx index b592387638..c136d4ea2f 100644 --- a/ui/src/components/SidebarAccountMenu.production.tsx +++ b/ui/src/components/SidebarAccountMenu.production.tsx @@ -8,7 +8,7 @@ import { UserRound, UserRoundPen, } from "lucide-react"; -import type { DeploymentMode, ServerGitInfo } from "@paperclipai/shared"; +import type { DeploymentMode } from "@paperclipai/shared"; import { Link } from "@/lib/router"; import { authApi } from "@/api/auth"; import { queryKeys } from "@/lib/queryKeys"; @@ -20,20 +20,15 @@ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils"; import { ThemeToggle } from "./ThemeToggle"; import { SidebarServerInfo } from "./SidebarServerInfo"; -import { Badge } from "@/components/ui/badge"; const PROFILE_SETTINGS_PATH = "/company/settings/instance/profile"; const DOCS_URL = "https://docs.paperclip.ing/"; const FEEDBACK_URL = "https://paperclip.ing/feedback"; -const SOURCE_REPOSITORY_URL = "https://github.com/paperclipai/paperclip"; -const SOURCE_VERSION_RE = /\+\d+\.git\.([0-9a-f]{7,40})(?:\.dirty)?$/i; interface SidebarAccountMenuProps { deploymentMode?: DeploymentMode; open?: boolean; onOpenChange?: (open: boolean) => void; - serverGit?: ServerGitInfo; - version?: string | null; } interface MenuActionProps { @@ -67,11 +62,6 @@ function deriveUserSlug(name: string | null | undefined, email: string | null | return "me"; } -function sourceVersionSha(version: string): string | null { - const sourceVersion = version.match(SOURCE_VERSION_RE); - return sourceVersion?.[1] ?? null; -} - function MenuAction({ label, description, icon: Icon, onClick, href, external = false }: MenuActionProps) { const className = "flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60"; @@ -115,8 +105,6 @@ export function SidebarAccountMenu({ deploymentMode, open: controlledOpen, onOpenChange, - serverGit, - version, }: SidebarAccountMenuProps) { const [internalOpen, setInternalOpen] = useState(false); const { isMobile, setSidebarOpen, collapsed, peeking } = useSidebar(); @@ -134,15 +122,8 @@ export function SidebarAccountMenu({ const displayName = session?.user.name?.trim() || "Board"; const secondaryLabel = session?.user.email?.trim() || (deploymentMode === "authenticated" ? "Signed in" : "Local workspace board"); - const accountBadge = deploymentMode === "authenticated" ? "Account" : "Local"; const initials = deriveInitials(displayName); const profileHref = `/u/${deriveUserSlug(session?.user.name, session?.user.email, session?.user.id)}`; - const sourceSha = version ? sourceVersionSha(version) : null; - const sourceFullSha = - sourceSha && serverGit?.available && serverGit.fullSha.toLowerCase().startsWith(sourceSha.toLowerCase()) - ? serverGit.fullSha - : sourceSha; - const sourceBranch = sourceSha && serverGit?.available ? serverGit.branchName : null; function closeNavigationChrome() { setOpen(false); @@ -189,40 +170,8 @@ export function SidebarAccountMenu({
-
-

{displayName}

- - {accountBadge} - -
+

{displayName}

{secondaryLabel}

- {sourceSha && sourceFullSha ? ( -
- {sourceBranch ? ( - - {sourceBranch} - - ) : null} -

- Paperclip{" "} - - {sourceSha.slice(0, 7)} - -

-
- ) : version ? ( -

Paperclip v{version}

- ) : null}
diff --git a/ui/src/components/SidebarAccountMenu.test.tsx b/ui/src/components/SidebarAccountMenu.test.tsx index b883af6637..5c4ffe0c02 100644 --- a/ui/src/components/SidebarAccountMenu.test.tsx +++ b/ui/src/components/SidebarAccountMenu.test.tsx @@ -196,10 +196,7 @@ describe("SidebarAccountMenu", () => { root.render( - + , ); @@ -233,7 +230,9 @@ describe("SidebarAccountMenu", () => { const themePos = menuText.indexOf("Switch to"); expect(docsPos).toBeLessThan(themePos); - expect(document.body.textContent).toContain("Paperclip v1.2.3"); + // The popover header stays down to name + email: no "Account" badge, no version line. + expect(popover?.textContent).not.toContain("Account"); + expect(popover?.textContent).not.toContain("Paperclip v"); expect(document.body.textContent).toContain("jane@example.com"); expect(document.body.querySelector('[data-slot="popover-content"]')?.className) .toContain("w-(--sz-277px)"); @@ -331,53 +330,4 @@ describe("SidebarAccountMenu", () => { }); }); - it("shows the short commit sha instead of a version for source builds", async () => { - const root = createRoot(container); - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); - - await act(async () => { - root.render( - - - - - , - ); - }); - await flushReact(); - - expect(document.body.textContent).toContain("feature/source-build-labelPaperclip 518fc71"); - expect(document.body.textContent).not.toContain("2026.626.0+58.git.518fc71ce"); - expect(document.body.querySelector('a[href="https://github.com/paperclipai/paperclip/tree/feature%2Fsource-build-label"]')?.textContent).toBe( - "feature/source-build-label", - ); - expect(document.body.querySelector('a[href="https://github.com/paperclipai/paperclip/commit/518fc71ce1234567890abcdef1234567890abcde"]')?.textContent).toBe( - "518fc71", - ); - - await act(async () => { - root.unmount(); - }); - }); }); diff --git a/ui/src/components/SidebarAccountMenu.tsx b/ui/src/components/SidebarAccountMenu.tsx index caec0bbd30..87c2897d51 100644 --- a/ui/src/components/SidebarAccountMenu.tsx +++ b/ui/src/components/SidebarAccountMenu.tsx @@ -9,7 +9,7 @@ import { UserRound, UserRoundPen, } from "lucide-react"; -import type { DeploymentMode, ServerGitInfo } from "@paperclipai/shared"; +import type { DeploymentMode } from "@paperclipai/shared"; import { Link } from "@/lib/router"; import { authApi } from "@/api/auth"; import { queryKeys } from "@/lib/queryKeys"; @@ -21,20 +21,15 @@ import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { cn, SIDEBAR_RAIL_HIDDEN_LABEL } from "../lib/utils"; import { ThemeToggle } from "./ThemeToggle"; import { SidebarServerInfo } from "./SidebarServerInfo"; -import { Badge } from "@/components/ui/badge"; const PROFILE_SETTINGS_PATH = "/company/settings/instance/profile"; const DOCS_URL = "https://docs.paperclip.ing/"; const FEEDBACK_URL = "https://paperclip.ing/feedback"; -const SOURCE_REPOSITORY_URL = "https://github.com/paperclipai/paperclip"; -const SOURCE_VERSION_RE = /\+\d+\.git\.([0-9a-f]{7,40})(?:\.dirty)?$/i; interface SidebarAccountMenuProps { deploymentMode?: DeploymentMode; open?: boolean; onOpenChange?: (open: boolean) => void; - serverGit?: ServerGitInfo; - version?: string | null; /** Contextual navigation occupies a full sidebar even if the saved global nav mode is collapsed. */ forceExpanded?: boolean; } @@ -70,11 +65,6 @@ function deriveUserSlug(name: string | null | undefined, email: string | null | return "me"; } -function sourceVersionSha(version: string): string | null { - const sourceVersion = version.match(SOURCE_VERSION_RE); - return sourceVersion?.[1] ?? null; -} - function MenuAction({ label, description, icon: Icon, onClick, href, external = false }: MenuActionProps) { const className = "flex w-full items-start gap-3 rounded-xl px-3 py-3 text-left transition-colors hover:bg-accent/60"; @@ -118,8 +108,6 @@ export function SidebarAccountMenu({ deploymentMode, open: controlledOpen, onOpenChange, - serverGit, - version, forceExpanded = false, }: SidebarAccountMenuProps) { const [internalOpen, setInternalOpen] = useState(false); @@ -138,15 +126,8 @@ export function SidebarAccountMenu({ const displayName = session?.user.name?.trim() || "Board"; const secondaryLabel = session?.user.email?.trim() || (deploymentMode === "authenticated" ? "Signed in" : "Local workspace board"); - const accountBadge = deploymentMode === "authenticated" ? "Account" : "Local"; const initials = deriveInitials(displayName); const profileHref = `/u/${deriveUserSlug(session?.user.name, session?.user.email, session?.user.id)}`; - const sourceSha = version ? sourceVersionSha(version) : null; - const sourceFullSha = - sourceSha && serverGit?.available && serverGit.fullSha.toLowerCase().startsWith(sourceSha.toLowerCase()) - ? serverGit.fullSha - : sourceSha; - const sourceBranch = sourceSha && serverGit?.available ? serverGit.branchName : null; function closeNavigationChrome() { setOpen(false); @@ -193,40 +174,8 @@ export function SidebarAccountMenu({
-
-

{displayName}

- - {accountBadge} - -
+

{displayName}

{secondaryLabel}

- {sourceSha && sourceFullSha ? ( -
- {sourceBranch ? ( - - {sourceBranch} - - ) : null} -

- Paperclip{" "} - - {sourceSha.slice(0, 7)} - -

-
- ) : version ? ( -

Paperclip v{version}

- ) : null}
diff --git a/ui/storybook/stories/navigation-layout.stories.tsx b/ui/storybook/stories/navigation-layout.stories.tsx index c78bdfb879..4eca73816f 100644 --- a/ui/storybook/stories/navigation-layout.stories.tsx +++ b/ui/storybook/stories/navigation-layout.stories.tsx @@ -256,7 +256,6 @@ function NavigationLayoutStories() { deploymentMode="authenticated" open onOpenChange={() => undefined} - version="0.3.1" /> From 54dd0f4868f86cb234f0d6dff7cc10f6e9722fd2 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Thu, 3 Sep 2026 23:26:51 -0700 Subject: [PATCH 2/3] feat(agents): grant new agents hire permission by default (#12814) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent permissions control which agents can create or hire other agents (`canCreateAgents`) > - Today only CEO-role agents get this permission by default; every other agent starts without it > - Teams that want agents to delegate and build out their own teams must flip the toggle on each hire, and most operators want delegation to work out of the box > - This pull request makes `canCreateAgents` default to enabled for new standard-trust agents, while low-trust agents keep a disabled default > - The benefit is that agent teams can grow without per-agent permission toggling, while low-trust containment and checkout protection stay intact ## Linked Issues or Issue Description Related (not fixed by this PR): #8064 also decouples an authority from `agents:create`. **Subsystem affected** Server agent permissions (`server/src/services/agent-permissions.ts`), authorization (`server/src/services/authorization.ts`), the shared `agentPermissionsSchema` validator, and the UI trust-preset helper. **Problem or motivation** New agents cannot hire other agents unless an operator enables `canCreateAgents` on each one. Only CEO-role agents get the permission by default. This blocks delegation-by-default workflows. Operators must toggle the permission for every hire. **Proposed solution** Default `canCreateAgents` to `true` for newly created agents. Apply and persist the default at creation only. Stored rows without an explicit value stay fail-closed at read and enforcement time. Keep the default at `false` when the agent's permissions record marks it low-trust (the `low_trust_review` preset or a trust boundary). Explicit values always win. Decouple `tasks:manage_active_checkouts` from `canCreateAgents` so the default-on flag does not let a peer agent write over another agent's checked-out issue. **Alternatives considered** Granting the default only at the route layer would leave stored rows and enforcement out of sync. Keeping the checkout authority coupled to `canCreateAgents` would void the active-checkout write protection once the flag is default-on. A per-company setting adds configuration surface without a clear need; explicit per-agent overrides already exist. **Roadmap alignment** Governance and trust-preset work already separates standard-trust from low-trust agents. This change follows that line: capability by default for standard trust, containment by default for low trust. ## What Changed - `normalizeAgentPermissions` now takes a `create`/`stored` context. Creation writes get the new default: enabled unless `permissionsImplyLowTrust()` detects the low-trust review preset or a trust boundary. Stored rows without an explicit value normalize to disabled (fail-closed). The role parameter is gone. - `agentPermissionsSchema` no longer injects `canCreateAgents: false` when the field is omitted. The server-side default applies instead. - `authorization.ts` normalizes raw agent rows for `agents:create`, so enforcement matches what the API reports for legacy rows. - `tasks:manage_active_checkouts` no longer rides on `canCreateAgents`. CEO role, explicit grants, and the manager chain remain the paths. - `agents:create` is denied outright inside any resolved low-trust execution context (agent, project, issue, or run policy). The default-on flag can never reach the legacy creator allow there. - The UI trust-preset helper sets `canCreateAgents: false` when an agent is switched to the low-trust preset, instead of carrying the old value forward. - `doc/CLI.md` describes the new default for `teams install`. - Tests pin the default matrix (standard, low-trust, explicit overrides) on the server and in the UI helper. ## Verification - `cd server && npx vitest run src/__tests__/agent-permissions-service.test.ts src/__tests__/agent-permissions-routes.test.ts src/__tests__/low-trust-red-team-routes.test.ts src/__tests__/authorization-service.test.ts` — 143 tests pass. - Broader sweep: 18 suites that touch `canCreateAgents` (hire, pending-approval, teams catalog, portability, built-in agents, plugin-managed agents) pass locally. - `cd ui && npx vitest run src/lib/trust-policy-ui.test.ts src/components/TrustPresetSection.test.tsx src/pages/NewAgent.test.tsx src/pages/Agents.test.tsx` — passes. - Typecheck is clean for the changed files in `packages/shared`, `server`, and `ui`. ## Risks - Behavioral shift: agents created after this change persist `canCreateAgents: true` unless low-trust. Pre-existing agents keep their stored value. Legacy or malformed permission records without an explicit value stay fail-closed at read and enforcement time; they never gain the authority retroactively. - Low-trust runs can no longer create agents at all, even when the agent carries an explicit `canCreateAgents: true`. Before this change, that combination could hire. The red-team suite and a new authorization test pin the denial. - Narrowing: a non-CEO agent with `canCreateAgents: true` loses implicit `tasks:manage_active_checkouts`. The manager chain and explicit grants still provide it. This narrowing is deliberate; without it, the default-on flag would let any peer bypass active-checkout write protection. - No migrations. No API shape changes. Low-trust defaults are covered by the red-team regression suite. ## Model Used - Claude Fable 5 (`claude-fable-5`), Anthropic — via Claude Code CLI with extended thinking and tool use (code search, editing, local test 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --- doc/CLI.md | 6 +- packages/shared/src/validators/agent.ts | 4 +- .../agent-permissions-service.test.ts | 100 +++++++++++++++--- .../__tests__/authorization-service.test.ts | 65 ++++++++++++ server/src/services/agent-permissions.ts | 56 ++++++++-- server/src/services/agents.ts | 16 ++- server/src/services/authorization.ts | 30 ++++-- ui/src/lib/trust-policy-ui.test.ts | 14 +++ ui/src/lib/trust-policy-ui.ts | 4 + 9 files changed, 251 insertions(+), 44 deletions(-) diff --git a/doc/CLI.md b/doc/CLI.md index 971648137e..0cdd67107b 100644 --- a/doc/CLI.md +++ b/doc/CLI.md @@ -716,8 +716,10 @@ Preview/install options: `paperclipai company current --json`, or `PAPERCLIP_COMPANY_ID` to select the target company. `company list` falls back to the scoped current company when board-wide listing is forbidden. `teams install` creates agents and therefore - requires board authentication, an `agents:create` grant, or an agent with - explicit `canCreateAgents` permission. + requires board authentication, an `agents:create` grant, or an agent with the + `canCreateAgents` permission (enabled by default for newly created + standard-trust agents; low-trust agents and pre-existing agents without an + explicit value stay disabled). - `--request-approval-on-forbidden` turns a 403 install denial into a linked board approval request instead of a raw failed command; use `--approval-issue-id ` to attach it to a specific issue. During Paperclip diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts index 2be813ca6f..4a9416d14a 100644 --- a/packages/shared/src/validators/agent.ts +++ b/packages/shared/src/validators/agent.ts @@ -12,7 +12,9 @@ import { agentDesiredSkillSelectionSchema } from "./adapter-skills.js"; import { objectWithoutDefaults } from "./partial.js"; export const agentPermissionsSchema = z.object({ - canCreateAgents: z.boolean().optional().default(false), + // No schema default: the server derives the default (enabled unless the + // permissions record marks the agent low-trust) when the field is omitted. + canCreateAgents: z.boolean().optional(), canCreateSkills: z.boolean().optional().default(true), trustPreset: trustPresetSchema.optional(), authorizationPolicy: trustAuthorizationPolicySchema.optional(), diff --git a/server/src/__tests__/agent-permissions-service.test.ts b/server/src/__tests__/agent-permissions-service.test.ts index ddd7dc9b22..6f8e37e300 100644 --- a/server/src/__tests__/agent-permissions-service.test.ts +++ b/server/src/__tests__/agent-permissions-service.test.ts @@ -1,37 +1,103 @@ import { describe, expect, it } from "vitest"; import { + LOW_TRUST_REVIEW_PRESET, agentPermissionsSchema, updateAgentPermissionsSchema, } from "@paperclipai/shared"; import { - defaultPermissionsForRole, + defaultAgentPermissions, normalizeAgentPermissions, + permissionsImplyLowTrust, } from "../services/agent-permissions.js"; describe("agent permissions service", () => { - it("keeps agent-creation authority least-privileged by default", () => { - expect(defaultPermissionsForRole("ceo").canCreateAgents).toBe(true); - expect(defaultPermissionsForRole("CTO").canCreateAgents).toBe(false); - expect(defaultPermissionsForRole("engineering-manager").canCreateAgents).toBe(false); - expect(defaultPermissionsForRole("engineer").canCreateAgents).toBe(false); + it("grants agent-creation authority to new agents by default", () => { + expect(defaultAgentPermissions({ context: "create" }).canCreateAgents).toBe(true); + expect(normalizeAgentPermissions(undefined, { context: "create" }).canCreateAgents).toBe(true); + expect(normalizeAgentPermissions({}, { context: "create" }).canCreateAgents).toBe(true); + expect( + normalizeAgentPermissions({ trustPreset: "standard" }, { context: "create" }).canCreateAgents, + ).toBe(true); }); - it("enables skill creation for every role by default", () => { - expect(defaultPermissionsForRole("ceo").canCreateSkills).toBe(true); - expect(defaultPermissionsForRole("CTO").canCreateSkills).toBe(true); - expect(defaultPermissionsForRole("engineering-manager").canCreateSkills).toBe(true); - expect(defaultPermissionsForRole("engineer").canCreateSkills).toBe(true); + it("keeps stored rows without an explicit value fail-closed", () => { + expect(defaultAgentPermissions().canCreateAgents).toBe(false); + expect(defaultAgentPermissions({ context: "stored" }).canCreateAgents).toBe(false); + expect(normalizeAgentPermissions(undefined).canCreateAgents).toBe(false); + expect(normalizeAgentPermissions({}).canCreateAgents).toBe(false); + expect(normalizeAgentPermissions("malformed").canCreateAgents).toBe(false); + expect(normalizeAgentPermissions([]).canCreateAgents).toBe(false); }); - it("preserves explicit canCreateAgents overrides", () => { - expect(normalizeAgentPermissions({ canCreateAgents: false }, "cto").canCreateAgents).toBe(false); - expect(normalizeAgentPermissions({ canCreateAgents: true }, "engineer").canCreateAgents).toBe(true); + it("withholds agent-creation authority from new low-trust agents", () => { + expect(defaultAgentPermissions({ lowTrust: true, context: "create" }).canCreateAgents).toBe(false); + expect( + normalizeAgentPermissions( + { trustPreset: LOW_TRUST_REVIEW_PRESET }, + { context: "create" }, + ).canCreateAgents, + ).toBe(false); + expect( + normalizeAgentPermissions( + { authorizationPolicy: { trustPreset: LOW_TRUST_REVIEW_PRESET } }, + { context: "create" }, + ).canCreateAgents, + ).toBe(false); + expect( + normalizeAgentPermissions( + { authorizationPolicy: { trustBoundary: { mode: LOW_TRUST_REVIEW_PRESET } } }, + { context: "create" }, + ).canCreateAgents, + ).toBe(false); + }); + + it("detects low-trust markers wherever the trust policy stores them", () => { + expect(permissionsImplyLowTrust(undefined)).toBe(false); + expect(permissionsImplyLowTrust({})).toBe(false); + expect(permissionsImplyLowTrust({ trustPreset: "standard" })).toBe(false); + expect(permissionsImplyLowTrust({ trustPreset: LOW_TRUST_REVIEW_PRESET })).toBe(true); + expect(permissionsImplyLowTrust({ reviewPreset: { id: LOW_TRUST_REVIEW_PRESET } })).toBe(true); + expect( + permissionsImplyLowTrust({ authorizationPolicy: { trustPreset: LOW_TRUST_REVIEW_PRESET } }), + ).toBe(true); + expect( + permissionsImplyLowTrust({ + authorizationPolicy: { reviewPreset: { id: LOW_TRUST_REVIEW_PRESET } }, + }), + ).toBe(true); + expect( + permissionsImplyLowTrust({ + authorizationPolicy: { trustBoundary: { mode: LOW_TRUST_REVIEW_PRESET } }, + }), + ).toBe(true); + }); + + it("enables skill creation by default", () => { + expect(defaultAgentPermissions().canCreateSkills).toBe(true); + expect(defaultAgentPermissions({ lowTrust: true, context: "create" }).canCreateSkills).toBe(true); + }); + + it("preserves explicit canCreateAgents overrides in both contexts", () => { + expect(normalizeAgentPermissions({ canCreateAgents: false }, { context: "create" }).canCreateAgents).toBe(false); + expect(normalizeAgentPermissions({ canCreateAgents: true }).canCreateAgents).toBe(true); + expect( + normalizeAgentPermissions({ + canCreateAgents: true, + trustPreset: LOW_TRUST_REVIEW_PRESET, + }).canCreateAgents, + ).toBe(true); }); it("defaults missing skill creation permission to true and preserves explicit false", () => { - expect(normalizeAgentPermissions({}, "engineer").canCreateSkills).toBe(true); - expect(normalizeAgentPermissions({ canCreateSkills: false }, "ceo").canCreateSkills).toBe(false); - expect(normalizeAgentPermissions({ canCreateSkills: true }, "engineer").canCreateSkills).toBe(true); + expect(normalizeAgentPermissions({}).canCreateSkills).toBe(true); + expect(normalizeAgentPermissions({ canCreateSkills: false }).canCreateSkills).toBe(false); + expect(normalizeAgentPermissions({ canCreateSkills: true }).canCreateSkills).toBe(true); + }); + + it("leaves omitted canCreateAgents undefined at the schema layer", () => { + expect(agentPermissionsSchema.parse({}).canCreateAgents).toBeUndefined(); + expect(agentPermissionsSchema.parse({ canCreateAgents: false }).canCreateAgents).toBe(false); + expect(agentPermissionsSchema.parse({ canCreateAgents: true }).canCreateAgents).toBe(true); }); it("validates skill creation permission with a default-on value", () => { diff --git a/server/src/__tests__/authorization-service.test.ts b/server/src/__tests__/authorization-service.test.ts index 871aabb27e..7a303268f4 100644 --- a/server/src/__tests__/authorization-service.test.ts +++ b/server/src/__tests__/authorization-service.test.ts @@ -1928,6 +1928,71 @@ describeEmbeddedPostgres("authorization service", () => { }); }); + it("grants hire authority through the persisted new-agent default", async () => { + const company = await createCompany(db, "DefaultHire"); + // The service create path persists the create-context default + // (canCreateAgents: true for standard trust); enforcement reads it back. + const actorAgent = await createAgent(db, company.id, { + role: "engineer", + permissions: { canCreateAgents: true, canCreateSkills: true }, + }); + + const decision = await authorizationService(db).decide({ + actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_jwt" }, + action: "agents:create", + resource: { type: "company", companyId: company.id }, + }); + + expect(decision).toMatchObject({ + allowed: true, + reason: "allow_legacy_agent_creator", + }); + }); + + it("keeps legacy rows without an explicit canCreateAgents fail-closed", async () => { + const company = await createCompany(db, "LegacyRowFailClosed"); + const actorAgent = await createAgent(db, company.id, { role: "engineer", permissions: {} }); + + const decision = await authorizationService(db).decide({ + actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_jwt" }, + action: "agents:create", + resource: { type: "company", companyId: company.id }, + }); + + expect(decision).toMatchObject({ + allowed: false, + reason: "deny_missing_grant", + }); + }); + + it("denies agent creation for a low-trust boundary even with explicit canCreateAgents", async () => { + const company = await createCompany(db, "LowTrustHireDenied"); + const project = await createProject(db, company.id, "Contained"); + const actorAgent = await createAgent(db, company.id, { + permissions: { + canCreateAgents: true, + trustPreset: LOW_TRUST_REVIEW_PRESET, + authorizationPolicy: { + trustBoundary: { + mode: LOW_TRUST_REVIEW_PRESET, + projectIds: [project.id], + }, + }, + }, + }); + + const decision = await authorizationService(db).decide({ + actor: { type: "agent", agentId: actorAgent.id, companyId: company.id, source: "agent_jwt" }, + action: "agents:create", + resource: { type: "company", companyId: company.id }, + }); + + expect(decision).toMatchObject({ + allowed: false, + reason: "deny_low_trust_boundary", + }); + }); + it("denies active-checkout management outside the CEO caller company scope", async () => { const sourceCompany = await createCompany(db, "CheckoutSource"); const targetCompany = await createCompany(db, "CheckoutTarget"); diff --git a/server/src/services/agent-permissions.ts b/server/src/services/agent-permissions.ts index 49eba9aa4e..e628a62ec5 100644 --- a/server/src/services/agent-permissions.ts +++ b/server/src/services/agent-permissions.ts @@ -1,28 +1,68 @@ +import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared"; + export type NormalizedAgentPermissions = Record & { canCreateAgents: boolean; canCreateSkills: boolean; }; -export function defaultPermissionsForRole(role: string): NormalizedAgentPermissions { +function asRecord(value: unknown): Record | null { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Record) + : null; +} + +/** + * Mirrors the agent-source low-trust markers consumed by + * resolveCoreTrustPreset: the low-trust review preset (top-level or inside + * authorizationPolicy) or a low-trust boundary. Defaults must never grant + * agent-creation authority to a low-trust agent. + */ +export function permissionsImplyLowTrust(permissions: unknown): boolean { + const record = asRecord(permissions); + if (!record) return false; + const authorizationPolicy = asRecord(record.authorizationPolicy); + return ( + record.trustPreset === LOW_TRUST_REVIEW_PRESET || + authorizationPolicy?.trustPreset === LOW_TRUST_REVIEW_PRESET || + asRecord(record.reviewPreset)?.id === LOW_TRUST_REVIEW_PRESET || + asRecord(authorizationPolicy?.reviewPreset)?.id === LOW_TRUST_REVIEW_PRESET || + asRecord(authorizationPolicy?.trustBoundary) !== null + ); +} + +/** + * "create" is the context for permissions arriving on a new-agent write: the + * hire/create default applies and the resolved value is persisted. "stored" + * is the context for rows read back from the database: a row without an + * explicit value stays fail-closed, so the default is never granted + * retroactively to legacy or malformed records at read or enforcement time. + */ +export type AgentPermissionsContext = "create" | "stored"; + +export function defaultAgentPermissions( + options?: { lowTrust?: boolean; context?: AgentPermissionsContext }, +): NormalizedAgentPermissions { return { - canCreateAgents: role.trim().toLowerCase() === "ceo", + canCreateAgents: options?.context === "create" && options?.lowTrust !== true, canCreateSkills: true, }; } export function normalizeAgentPermissions( permissions: unknown, - role: string, + options?: { context?: AgentPermissionsContext }, ): NormalizedAgentPermissions { - const defaults = defaultPermissionsForRole(role); - if (typeof permissions !== "object" || permissions === null || Array.isArray(permissions)) { + const defaults = defaultAgentPermissions({ + lowTrust: permissionsImplyLowTrust(permissions), + context: options?.context ?? "stored", + }); + const record = asRecord(permissions); + if (!record) { return defaults; } - const record = permissions as Record; - const preserved = { ...record }; return { - ...preserved, + ...record, canCreateAgents: typeof record.canCreateAgents === "boolean" ? record.canCreateAgents diff --git a/server/src/services/agents.ts b/server/src/services/agents.ts index 86dee4a2a2..f785397746 100644 --- a/server/src/services/agents.ts +++ b/server/src/services/agents.ts @@ -344,7 +344,7 @@ export function agentService(db: Db) { function normalizeAgentBaseRow(row: typeof agents.$inferSelect) { return withUrlKey({ ...row, - permissions: normalizeAgentPermissions(row.permissions, row.role), + permissions: normalizeAgentPermissions(row.permissions), }); } @@ -676,8 +676,7 @@ export function agentService(db: Db) { const normalizedPatch = { ...data } as Partial; if (data.permissions !== undefined) { - const role = (data.role ?? existing.role) as string; - normalizedPatch.permissions = normalizeAgentPermissions(data.permissions, role); + normalizedPatch.permissions = normalizeAgentPermissions(data.permissions); } if ( Object.prototype.hasOwnProperty.call(normalizedPatch, "adapterConfig") && @@ -806,7 +805,7 @@ export function agentService(db: Db) { const uniqueName = deduplicateAgentName(data.name, existingAgents); const role = data.role ?? "general"; - const normalizedPermissions = normalizeAgentPermissions(data.permissions, role); + const normalizedPermissions = normalizeAgentPermissions(data.permissions, { context: "create" }); const runtimeConfig = normalizeRuntimeConfigForNewAgent(data.runtimeConfig); const adapterType = data.adapterType ?? "process"; const rawAdapterConfig = isPlainRecord(data.adapterConfig) @@ -1039,10 +1038,9 @@ export function agentService(db: Db) { ); } if (patch.permissions !== undefined) { - patch.permissions = normalizeAgentPermissions( - patch.permissions, - (patch.role ?? existing.role) as string, - ); + // The pending-approval activation replays the original hire + // request, so the new-agent creation default applies. + patch.permissions = normalizeAgentPermissions(patch.permissions, { context: "create" }); } const updated = await tx .update(agents) @@ -1089,7 +1087,7 @@ export function agentService(db: Db) { const updated = await db .update(agents) .set({ - permissions: normalizeAgentPermissions({ ...existing.permissions, ...permissions }, existing.role), + permissions: normalizeAgentPermissions({ ...existing.permissions, ...permissions }), updatedAt: new Date(), }) .where(eq(agents.id, id)) diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts index 6a20e38a3c..c6cad46937 100644 --- a/server/src/services/authorization.ts +++ b/server/src/services/authorization.ts @@ -28,6 +28,7 @@ import { type TrustPresetResolution, } from "./trust-preset-resolver.js"; import { logger } from "../middleware/logger.js"; +import { normalizeAgentPermissions } from "./agent-permissions.js"; import { grantsForHumanRole, normalizeHumanRole } from "./company-member-roles.js"; export type AuthorizationActor = @@ -170,8 +171,10 @@ function permissionForAction(action: AuthorizationAction): PermissionKey | null function canCreateAgentsLegacy(agent: { role: string; permissions: unknown }) { if (agent.role === "ceo") return true; - if (!agent.permissions || typeof agent.permissions !== "object") return false; - return Boolean((agent.permissions as Record).canCreateAgents); + // Raw agent rows may predate permission normalization; apply the same + // defaults the agent service applies on read so enforcement matches what + // the API reports. + return normalizeAgentPermissions(agent.permissions).canCreateAgents; } function scopeValueList(value: unknown): string[] { @@ -984,6 +987,11 @@ export function authorizationService(db: Db | DbTransaction) { if ( input.action === "company_scope:read" || + // Agent creation is a company-wide privileged action. The default-on + // canCreateAgents flag must never reach the legacy creator allow when + // the effective execution context (agent, project, issue, or run + // policy) resolves to low trust. + input.action === "agents:create" || input.action === "decision_queue:manage" || input.action === "decision_queue:read" || input.action === "decision_triage:manage" || @@ -2242,11 +2250,19 @@ export function authorizationService(db: Db | DbTransaction) { if (grantDecision.allowed) return grantDecision; } - if ( - (input.action === "agents:create" || - input.action === "tasks:manage_active_checkouts") && - canCreateAgentsLegacy(actorAgent) - ) { + if (input.action === "agents:create" && canCreateAgentsLegacy(actorAgent)) { + return allow({ + action: input.action, + reason: "allow_legacy_agent_creator", + explanation: "Allowed by legacy agent creator authority.", + }); + } + + // Active-checkout management deliberately does not ride on + // canCreateAgents: that flag is default-on for standard-trust agents, and + // coupling would let any peer write over another agent's checked-out + // issue. CEOs, explicit grants, and the manager chain remain the paths. + if (input.action === "tasks:manage_active_checkouts" && actorAgent.role === "ceo") { return allow({ action: input.action, reason: "allow_legacy_agent_creator", diff --git a/ui/src/lib/trust-policy-ui.test.ts b/ui/src/lib/trust-policy-ui.test.ts index c142c6bb6f..a791c62a15 100644 --- a/ui/src/lib/trust-policy-ui.test.ts +++ b/ui/src/lib/trust-policy-ui.test.ts @@ -1,6 +1,7 @@ // @vitest-environment node import { describe, expect, it } from "vitest"; import { + buildPermissionsForTrustPreset, clearSingleLowTrustBoundaryTarget, getLowTrustBoundary, getSingleLowTrustBoundaryTarget, @@ -10,6 +11,19 @@ import { } from "./trust-policy-ui"; describe("trust-policy-ui low-trust boundary helpers", () => { + it("drops hire authority when switching to the low-trust preset", () => { + const demoted = buildPermissionsForTrustPreset( + { canCreateAgents: true, canCreateSkills: true }, + "low_trust_review", + ); + expect(demoted.canCreateAgents).toBe(false); + expect(demoted.canCreateSkills).toBe(true); + + const restored = buildPermissionsForTrustPreset(demoted, "standard"); + expect(restored.canCreateAgents).toBe(false); + expect(restored.trustPreset).toBe("standard"); + }); + it("writes one project boundary with mode and company id", () => { const permissions = setSingleLowTrustBoundaryTarget(null, "company-1", { type: "project", diff --git a/ui/src/lib/trust-policy-ui.ts b/ui/src/lib/trust-policy-ui.ts index f2442435d8..86ee6d5f47 100644 --- a/ui/src/lib/trust-policy-ui.ts +++ b/ui/src/lib/trust-policy-ui.ts @@ -52,6 +52,10 @@ export function buildPermissionsForTrustPreset( if (preset === LOW_TRUST_REVIEW_PRESET) { return { ...current, + // Hire authority is default-on for standard-trust agents, so demoting + // to low-trust must drop it rather than carry the old value forward. + // Operators can re-enable it explicitly afterwards. + canCreateAgents: false, trustPreset: LOW_TRUST_REVIEW_PRESET, authorizationPolicy: buildLowTrustReviewPolicy(current.authorizationPolicy), }; From 2a5aa5e213f31ebfd3ba3360cff099adfdfe7372 Mon Sep 17 00:00:00 2001 From: Michael Nguyen <13559011+nguyenm7@users.noreply.github.com> Date: Thu, 3 Sep 2026 20:27:25 -1000 Subject: [PATCH 3/3] feat(ui): viewer=full document deep link opens the maximized side pane (#12812) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents ask humans for decisions through approval cards, and a chat gateway plugin can forward those cards to Slack with an "Open task" button > - The button opens the bare task page; to read the document under approval, the reviewer must click four more times (open the side pane, open the Artifacts tab, open the artifact, maximize the pane) > - Approvals are the highest-frequency human touchpoint, so each removed click matters > - This pull request adds a `viewer=full` option to the existing `#document-` deep link; the link now opens the target document and maximizes the side pane > - The benefit is one-click access from an external notification to a full-size reading surface for the document under approval ## Linked Issues or Issue Description **What existing behavior does this improve?** The issue page already supports `#document-` deep links. They open the document in the side pane, but at the pane's default width. **Current behavior** An external link cannot request the maximized (full-size) document view. A reviewer who follows an approval notification must maximize the pane by hand each time. **Proposed behavior** `#document-&viewer=full` opens the document and maximizes the side pane. Plan documents open in the Plan tab, maximized. Mobile keeps the full-screen sheet. Unknown `viewer` values are ignored, so old links and new links stay compatible in both directions. **Reason and benefit** Chat notifications about approvals can now land the reviewer directly on a full-size view of the document they must read. This removes four clicks from every approval review. **Breaking changes** None. The parameter is optional and additive. Links without it keep today's behavior. ## What Changed - `ui/src/lib/document-annotation-hash.ts`: parse and build an optional `viewer=full` parameter in document hashes. - `ui/src/lib/issue-document-deep-link.ts`: thread a `maximize` flag on properties-pane routes; the continuation-summary route is unchanged. - `ui/src/context/PanelContext.tsx`: add a one-shot panel maximize request (`requestPanelMaximize` / `clearPanelMaximizeRequest`). - `ui/src/components/PropertiesPanel.tsx`: the resizable panel host consumes a pending request once it is visible and laid out, then clears it. - `ui/src/pages/IssueDetail.tsx`: request the maximize on the desktop deep-link path only; mobile keeps the sheet. - Tests for all of the above. ## Verification - `cd ui && pnpm typecheck` — clean. - `cd ui && pnpm vitest run src/lib/document-annotation-hash.test.ts src/lib/issue-document-deep-link.test.ts src/components/PropertiesPanel.test.tsx` — 31/31 green. - New cases cover: `viewer` parse/build round trip, unknown values ignored, maximize routing for document and plan tabs, a pending request consumed on mount, and a request held while the panel is hidden. - Manual check: open an issue with `#document-&viewer=full` in the URL; the pane opens on that document, maximized. Remove the parameter; the pane opens at its normal width. ## Risks - Low risk. The parameter is optional; no data, schema, or API changes. - The maximize request lives in React context as a one-shot flag. It is cleared on first consumption, so a stale request cannot re-maximize the pane on later navigations. - If a link carries `viewer=full` on a web build older than this change, the parameter is ignored and the document still opens. ## Model Used - Claude Fable 5 (`claude-fable-5`), Anthropic. Agentic coding session with extended thinking and tool use (file edits, shell, test runs). ## 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) - [ ] 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 - [x] 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 Fable 5 --- ui/src/components/PropertiesPanel.test.tsx | 21 +++++ ui/src/components/PropertiesPanel.tsx | 26 +++++- ui/src/context/PanelContext.tsx | 31 +++++++- ui/src/lib/document-annotation-hash.test.ts | 39 ++++++++- ui/src/lib/document-annotation-hash.ts | 13 ++- ui/src/lib/issue-document-deep-link.test.ts | 17 ++++ ui/src/lib/issue-document-deep-link.ts | 11 ++- ui/src/pages/IssueDetail.test.tsx | 88 ++++++++++++++++++++- ui/src/pages/IssueDetail.tsx | 41 +++++++++- 9 files changed, 276 insertions(+), 11 deletions(-) diff --git a/ui/src/components/PropertiesPanel.test.tsx b/ui/src/components/PropertiesPanel.test.tsx index d30119222b..e478d654f6 100644 --- a/ui/src/components/PropertiesPanel.test.tsx +++ b/ui/src/components/PropertiesPanel.test.tsx @@ -19,8 +19,10 @@ const mockPanelState = vi.hoisted(() => ({ panelContent: null as unknown, panelContentMode: "padded" as const, panelVisible: true, + panelMaximizeRequested: false, })); const mockSetPanelVisible = vi.hoisted(() => vi.fn()); +const mockClearPanelMaximizeRequest = vi.hoisted(() => vi.fn()); vi.mock("../context/PanelContext", () => ({ usePanel: () => ({ @@ -31,6 +33,9 @@ vi.mock("../context/PanelContext", () => ({ closePanel: vi.fn(), setPanelVisible: mockSetPanelVisible, togglePanelVisible: vi.fn(), + panelMaximizeRequested: mockPanelState.panelMaximizeRequested, + requestPanelMaximize: vi.fn(), + clearPanelMaximizeRequest: mockClearPanelMaximizeRequest, }), })); @@ -74,6 +79,8 @@ describe("PropertiesPanel", () => { document.body.appendChild(container); window.localStorage.clear(); mockSetPanelVisible.mockClear(); + mockClearPanelMaximizeRequest.mockClear(); + mockPanelState.panelMaximizeRequested = false; }); afterEach(() => { @@ -151,6 +158,20 @@ describe("PropertiesPanel", () => { expect(container.querySelector("section")?.getAttribute("data-maximized")).toBe("true"); }); + it("consumes a pending deep-link maximize request on mount (LOOA-2181)", async () => { + mockPanelState.panelMaximizeRequested = true; + await renderPanel({ taskDetailLayout: true }); + expect(mockClearPanelMaximizeRequest).toHaveBeenCalled(); + expect(container.querySelector("section")?.getAttribute("data-maximized")).toBe("true"); + }); + + it("holds a deep-link maximize request while the panel is hidden", async () => { + mockPanelState.panelMaximizeRequested = true; + await renderPanel({ panelVisible: false }); + expect(mockClearPanelMaximizeRequest).not.toHaveBeenCalled(); + expect(container.querySelector("section")?.getAttribute("data-maximized")).not.toBe("true"); + }); + it("uses an X to close the Streamlined task-detail sidebar", async () => { await renderPanel({ taskDetailLayout: true }); const close = container.querySelector('[aria-label="Close side panel"]'); diff --git a/ui/src/components/PropertiesPanel.tsx b/ui/src/components/PropertiesPanel.tsx index 26bbd2ca32..783ec1dd39 100644 --- a/ui/src/components/PropertiesPanel.tsx +++ b/ui/src/components/PropertiesPanel.tsx @@ -9,7 +9,14 @@ import { ScrollArea } from "@/components/ui/scroll-area"; import { SidePanelFrame, SidePanelWindowControls } from "@/components/side-panel"; export function PropertiesPanel({ taskDetailLayout = false }: { taskDetailLayout?: boolean }) { - const { panelContent, panelContentMode, panelVisible, setPanelVisible } = usePanel(); + const { + panelContent, + panelContentMode, + panelVisible, + setPanelVisible, + panelMaximizeRequested, + clearPanelMaximizeRequest, + } = usePanel(); const { enabled: classicTaskInterfaceEnabled } = useClassicTaskInterfaceEnabled(); const { enabled: streamlinedUiEnabled } = useStreamlinedUiEnabled(); const streamlinedTaskDetailLayout = streamlinedUiEnabled && taskDetailLayout; @@ -45,6 +52,8 @@ export function PropertiesPanel({ taskDetailLayout = false }: { taskDetailLayout panelVisible={panelVisible} setPanelVisible={setPanelVisible} taskDetailLayout={streamlinedTaskDetailLayout} + maximizeRequested={panelMaximizeRequested} + clearMaximizeRequest={clearPanelMaximizeRequest} /> ); } @@ -144,6 +153,9 @@ interface ResizablePropertiesPanelProps { panelVisible: boolean; setPanelVisible: (visible: boolean) => void; taskDetailLayout: boolean; + /** Pending `viewer=full` deep-link request (LOOA-2181); cleared once consumed. */ + maximizeRequested: boolean; + clearMaximizeRequest: () => void; } function ResizablePropertiesPanel({ @@ -152,6 +164,8 @@ function ResizablePropertiesPanel({ panelVisible, setPanelVisible, taskDetailLayout, + maximizeRequested, + clearMaximizeRequest, }: ResizablePropertiesPanelProps) { const defaultPaneWidth = taskDetailLayout ? TASK_DETAIL_DEFAULT_PANE_WIDTH @@ -301,6 +315,16 @@ function ResizablePropertiesPanel({ restoreTimerRef.current = window.setTimeout(finishRestore, RESTORE_FALLBACK_DELAY); }, [clearRestoreTimer, finishRestore]); + // Deep-link maximize (LOOA-2181): the request may predate this mount (the + // hash routes before the panel content commits), so it lives in context and + // is consumed here once the panel is actually visible and laid out — + // handleMaximize measures live geometry, which needs a committed DOM. + useEffect(() => { + if (!maximizeRequested || !panelVisible) return; + clearMaximizeRequest(); + if (!maximized) handleMaximize(); + }, [maximizeRequested, panelVisible, maximized, handleMaximize, clearMaximizeRequest]); + const handleTransitionEnd = useCallback( (event: React.TransitionEvent) => { if (event.target !== asideRef.current || event.propertyName !== "left") return; diff --git a/ui/src/context/PanelContext.tsx b/ui/src/context/PanelContext.tsx index fcb79e9245..1893c47705 100644 --- a/ui/src/context/PanelContext.tsx +++ b/ui/src/context/PanelContext.tsx @@ -11,6 +11,15 @@ interface PanelContextValue { closePanel: () => void; setPanelVisible: (visible: boolean) => void; togglePanelVisible: () => void; + /** + * One-shot maximize request (LOOA-2181): deep links with `viewer=full` ask + * the resizable panel host to open maximized. The request stays pending + * until the host consumes it (the panel may not be mounted yet when the + * deep link routes), so consumers must clear it after acting. + */ + panelMaximizeRequested: boolean; + requestPanelMaximize: () => void; + clearPanelMaximizeRequest: () => void; } const PanelContext = createContext(null); @@ -36,6 +45,15 @@ export function PanelProvider({ children }: { children: ReactNode }) { const [panelContent, setPanelContent] = useState(null); const [panelContentMode, setPanelContentMode] = useState("padded"); const [panelVisible, setPanelVisibleState] = useState(readPreference); + const [panelMaximizeRequested, setPanelMaximizeRequested] = useState(false); + + const requestPanelMaximize = useCallback(() => { + setPanelMaximizeRequested(true); + }, []); + + const clearPanelMaximizeRequest = useCallback(() => { + setPanelMaximizeRequested(false); + }, []); const openPanel = useCallback((content: ReactNode, options?: { contentMode?: SidePanelContentMode }) => { setPanelContent(content); @@ -62,7 +80,18 @@ export function PanelProvider({ children }: { children: ReactNode }) { return ( {children} diff --git a/ui/src/lib/document-annotation-hash.test.ts b/ui/src/lib/document-annotation-hash.test.ts index c954bcce1e..7899d0e955 100644 --- a/ui/src/lib/document-annotation-hash.test.ts +++ b/ui/src/lib/document-annotation-hash.test.ts @@ -15,6 +15,7 @@ describe("parseDocumentAnnotationHash", () => { documentKey: "plan", threadId: null, commentId: null, + viewer: null, }); }); @@ -25,6 +26,25 @@ describe("parseDocumentAnnotationHash", () => { documentKey: "plan", threadId: "t1", commentId: "c2", + viewer: null, + }); + }); + + it("parses the viewer=full request", () => { + expect(parseDocumentAnnotationHash("#document-direction-package&viewer=full")).toEqual({ + documentKey: "direction-package", + threadId: null, + commentId: null, + viewer: "full", + }); + }); + + it("ignores unknown viewer values", () => { + expect(parseDocumentAnnotationHash("#document-plan&viewer=huge")).toEqual({ + documentKey: "plan", + threadId: null, + commentId: null, + viewer: null, }); }); @@ -33,6 +53,7 @@ describe("parseDocumentAnnotationHash", () => { documentKey: "my notes", threadId: "abc", commentId: null, + viewer: null, }); }); @@ -60,8 +81,24 @@ describe("buildDocumentAnnotationHash", () => { ).toBe("#document-plan&thread=t1&comment=c2"); }); + it("includes the viewer request", () => { + expect( + buildDocumentAnnotationHash({ + documentKey: "direction-package", + threadId: null, + commentId: null, + viewer: "full", + }), + ).toBe("#document-direction-package&viewer=full"); + }); + it("survives a round trip", () => { - const target = { documentKey: "plan-2", threadId: "t-abc", commentId: "c-xyz" }; + const target = { + documentKey: "plan-2", + threadId: "t-abc", + commentId: "c-xyz", + viewer: "full" as const, + }; expect(parseDocumentAnnotationHash(buildDocumentAnnotationHash(target))).toEqual(target); }); }); diff --git a/ui/src/lib/document-annotation-hash.ts b/ui/src/lib/document-annotation-hash.ts index 1b0b859e91..dd58b53c54 100644 --- a/ui/src/lib/document-annotation-hash.ts +++ b/ui/src/lib/document-annotation-hash.ts @@ -2,6 +2,13 @@ export interface DocumentAnnotationHashTarget { documentKey: string; threadId: string | null; commentId: string | null; + /** + * `viewer=full` (LOOA-2181): external deep links — e.g. the Slack gateway's + * "Open task" button on an approval card — request the document opened in + * the maximized (full-size) properties pane, skipping the manual + * open-pane → Artifacts → open → maximize click chain. + */ + viewer: "full" | null; } const DOCUMENT_HASH_PREFIX = "#document-"; @@ -25,13 +32,17 @@ export function parseDocumentAnnotationHash(hash: string): DocumentAnnotationHas documentKey, threadId: threadId && threadId.length > 0 ? threadId : null, commentId: commentId && commentId.length > 0 ? commentId : null, + viewer: params.get("viewer") === "full" ? "full" : null, }; } -export function buildDocumentAnnotationHash(target: DocumentAnnotationHashTarget): string { +export function buildDocumentAnnotationHash( + target: Omit & { viewer?: "full" | null }, +): string { const params = new URLSearchParams(); if (target.threadId) params.set("thread", target.threadId); if (target.commentId) params.set("comment", target.commentId); + if (target.viewer) params.set("viewer", target.viewer); const qs = params.toString(); const encodedKey = encodeURIComponent(target.documentKey); return qs ? `${DOCUMENT_HASH_PREFIX}${encodedKey}&${qs}` : `${DOCUMENT_HASH_PREFIX}${encodedKey}`; diff --git a/ui/src/lib/issue-document-deep-link.test.ts b/ui/src/lib/issue-document-deep-link.test.ts index fca00b3ae1..a5bfb60f98 100644 --- a/ui/src/lib/issue-document-deep-link.test.ts +++ b/ui/src/lib/issue-document-deep-link.test.ts @@ -13,6 +13,7 @@ describe("resolveIssueDocumentDeepLink", () => { kind: "properties-pane", tab: "plans", documentKey: "plan", + maximize: false, }); }); @@ -21,6 +22,22 @@ describe("resolveIssueDocumentDeepLink", () => { kind: "properties-pane", tab: "document", documentKey: "qa evidence", + maximize: false, + }); + }); + + it("requests the maximized pane for viewer=full deep links", () => { + expect(resolveIssueDocumentDeepLink("#document-direction-package&viewer=full")).toEqual({ + kind: "properties-pane", + tab: "document", + documentKey: "direction-package", + maximize: true, + }); + expect(resolveIssueDocumentDeepLink("#document-plan&viewer=full")).toEqual({ + kind: "properties-pane", + tab: "plans", + documentKey: "plan", + maximize: true, }); }); diff --git a/ui/src/lib/issue-document-deep-link.ts b/ui/src/lib/issue-document-deep-link.ts index cfee5e2a01..19132d1f5f 100644 --- a/ui/src/lib/issue-document-deep-link.ts +++ b/ui/src/lib/issue-document-deep-link.ts @@ -3,14 +3,16 @@ import { parseDocumentAnnotationHash } from "./document-annotation-hash"; export type IssueDocumentDeepLinkRoute = | { kind: "continuation-summary" } - | { kind: "properties-pane"; tab: "plans"; documentKey: "plan" } - | { kind: "properties-pane"; tab: "document"; documentKey: string }; + | { kind: "properties-pane"; tab: "plans"; documentKey: "plan"; maximize: boolean } + | { kind: "properties-pane"; tab: "document"; documentKey: string; maximize: boolean }; /** * Maps an issue document hash to the surface that owns that document. * * The continuation summary remains in the activity/handoff surface, the plan * keeps its dedicated pane tab, and every other document opens in its own tab. + * `viewer=full` (LOOA-2181) additionally requests the maximized pane so + * external links (Slack approval cards) land on a full-size reading surface. */ export function resolveIssueDocumentDeepLink(hash: string): IssueDocumentDeepLinkRoute | null { const target = parseDocumentAnnotationHash(hash); @@ -19,8 +21,9 @@ export function resolveIssueDocumentDeepLink(hash: string): IssueDocumentDeepLin if (target.documentKey === ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY) { return { kind: "continuation-summary" }; } + const maximize = target.viewer === "full"; if (target.documentKey === "plan") { - return { kind: "properties-pane", tab: "plans", documentKey: "plan" }; + return { kind: "properties-pane", tab: "plans", documentKey: "plan", maximize }; } - return { kind: "properties-pane", tab: "document", documentKey: target.documentKey }; + return { kind: "properties-pane", tab: "document", documentKey: target.documentKey, maximize }; } diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx index 479cae38b7..9abb6d8d09 100644 --- a/ui/src/pages/IssueDetail.test.tsx +++ b/ui/src/pages/IssueDetail.test.tsx @@ -118,7 +118,10 @@ const mockLocation = vi.hoisted(() => ({ const mockOpenPanel = vi.hoisted(() => vi.fn()); const mockClosePanel = vi.hoisted(() => vi.fn()); const mockSetPanelVisible = vi.hoisted(() => vi.fn()); +const mockRequestPanelMaximize = vi.hoisted(() => vi.fn()); +const mockClearPanelMaximizeRequest = vi.hoisted(() => vi.fn()); const mockPanelState = vi.hoisted(() => ({ panelVisible: true })); +const mockRouteParams = vi.hoisted(() => ({ issueId: "PAP-1" })); const mockSidebarState = vi.hoisted(() => ({ isMobile: false })); const mockIssuePropertiesRender = vi.hoisted(() => vi.fn()); const mockTaskSidePanelRender = vi.hoisted(() => vi.fn()); @@ -216,7 +219,7 @@ vi.mock("@/lib/router", () => ({ useLocation: () => mockLocation, useNavigate: () => mockNavigate, useNavigationType: () => "PUSH", - useParams: () => ({ issueId: "PAP-1" }), + useParams: () => ({ ...mockRouteParams }), })); vi.mock("../context/CompanyContext", () => ({ @@ -266,6 +269,8 @@ vi.mock("../context/PanelContext", () => ({ closePanel: mockClosePanel, panelVisible: mockPanelState.panelVisible, setPanelVisible: mockSetPanelVisible, + requestPanelMaximize: mockRequestPanelMaximize, + clearPanelMaximizeRequest: mockClearPanelMaximizeRequest, }), })); @@ -1347,6 +1352,8 @@ describe("IssueDetail", () => { mockOpenPanel.mockClear(); mockClosePanel.mockClear(); mockSetPanelVisible.mockClear(); + mockRequestPanelMaximize.mockClear(); + mockClearPanelMaximizeRequest.mockClear(); mockSetBreadcrumbPanelControl.mockClear(); mockSetMobileToolbar.mockClear(); mockIssuePropertiesRender.mockClear(); @@ -1364,6 +1371,7 @@ describe("IssueDetail", () => { mockLocation.search = ""; mockLocation.hash = ""; mockLocation.state = null; + mockRouteParams.issueId = "PAP-1"; }); afterEach(async () => { @@ -1802,6 +1810,84 @@ describe("IssueDetail", () => { }); }); + it("maximizes the desktop pane once per viewer=full deep link", async () => { + mockPanelState.panelVisible = false; + mockLocation.hash = "#document-qa-evidence&viewer=full"; + mockIssuesApi.get.mockResolvedValue(createIssue()); + + await act(async () => { + root.render( + + + , + ); + }); + + await waitForAssertion(() => { + expect(mockSetPanelVisible).toHaveBeenCalledWith(true); + expect(mockRequestPanelMaximize).toHaveBeenCalledTimes(1); + }); + + // Replaying the same hash (same-page link click) reopens the document but + // must not re-maximize a pane the user may have deliberately restored. + const link = document.createElement("a"); + link.href = "#document-qa-evidence&viewer=full"; + link.textContent = "QA evidence"; + container.appendChild(link); + await act(async () => link.click()); + expect(mockRequestPanelMaximize).toHaveBeenCalledTimes(1); + + // Ending the deep link drops the pending request and re-arms the guard. + mockLocation.hash = ""; + await act(async () => { + root.render( + + + , + ); + }); + await waitForAssertion(() => { + expect(mockClearPanelMaximizeRequest).toHaveBeenCalled(); + }); + }); + + it("re-maximizes when navigating to another issue with an identical viewer=full hash", async () => { + mockPanelState.panelVisible = false; + mockLocation.hash = "#document-qa-evidence&viewer=full"; + mockIssuesApi.get.mockResolvedValue(createIssue()); + + await act(async () => { + root.render( + + + , + ); + }); + + await waitForAssertion(() => { + expect(mockRequestPanelMaximize).toHaveBeenCalledTimes(1); + }); + + // Navigate to a sibling issue whose URL carries the same document hash. + // IssueDetail stays mounted; the destination pane must still maximize. + mockRouteParams.issueId = "PAP-2"; + mockLocation.pathname = "/issues/PAP-2"; + mockIssuesApi.get.mockResolvedValue( + createIssue({ id: "issue-2", identifier: "PAP-2" }), + ); + await act(async () => { + root.render( + + + , + ); + }); + + await waitForAssertion(() => { + expect(mockRequestPanelMaximize).toHaveBeenCalledTimes(2); + }); + }); + it("opens the mobile properties sheet for a document deep link", async () => { mockSidebarState.isMobile = true; mockLocation.hash = "#document-qa-evidence"; diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index 6a29babbe1..bad72401fd 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -2670,7 +2670,14 @@ export function IssueDetail() { ? "mx-auto w-full max-w-(--tc-shell-max-w)" : undefined; const { openNewIssue } = useDialogActions(); - const { openPanel, closePanel, panelVisible, setPanelVisible } = usePanel(); + const { + openPanel, + closePanel, + panelVisible, + setPanelVisible, + requestPanelMaximize, + clearPanelMaximizeRequest, + } = usePanel(); const { setBreadcrumbs, setBreadcrumbToolbar, @@ -5398,6 +5405,12 @@ export function IssueDetail() { sourceBreadcrumb.href, ]); + // One maximize request per issue + `viewer=full` hash: routing re-runs + // whenever a callback dependency changes identity, and re-requesting then + // would re-maximize a pane the user deliberately restored. The key carries + // the issue param so navigating to another issue with an identical hash + // still maximizes the destination pane. + const lastMaximizeRequestKeyRef = useRef(null); const routeIssueDocumentDeepLink = useCallback( (hash: string) => { const route = resolveIssueDocumentDeepLink(hash); @@ -5421,6 +5434,16 @@ export function IssueDetail() { setPanelBeforePlanOverrideIssueId(issue.id); } setPanelVisible(true); + // `viewer=full` (LOOA-2181): external links (Slack approval cards) + // land with the pane maximized. Mobile uses the sheet, which is + // already full-screen, so the request is desktop-only. + if (route.maximize) { + const requestKey = `${issueId ?? ""}::${hash}`; + if (lastMaximizeRequestKeyRef.current !== requestKey) { + lastMaximizeRequestKeyRef.current = requestKey; + requestPanelMaximize(); + } + } } const targetIssueId = issue?.id ?? issueId ?? ""; setDocumentDeepLink((current) => ({ @@ -5438,6 +5461,7 @@ export function IssueDetail() { issue?.id, issueId, setPanelVisible, + requestPanelMaximize, suppressPanelUntilPlan, taskChatShellEnabled, ], @@ -5446,8 +5470,21 @@ export function IssueDetail() { useEffect(() => { if (!routeIssueDocumentDeepLink(location.hash)) { setDocumentDeepLink(null); + // The deep link ended (hash cleared or issue changed): drop any + // maximize request the panel never consumed so it cannot maximize a + // later, unrelated panel, and re-arm for the next viewer=full hash. + lastMaximizeRequestKeyRef.current = null; + clearPanelMaximizeRequest(); } - }, [issueId, location.hash, routeIssueDocumentDeepLink]); + }, [issueId, location.hash, routeIssueDocumentDeepLink, clearPanelMaximizeRequest]); + + // Leaving the issue page entirely also ends the deep link's lifetime. + useEffect( + () => () => { + clearPanelMaximizeRequest(); + }, + [clearPanelMaximizeRequest], + ); // React Router does not emit a location update when the user clicks a link // whose hash is already current. Capture that repeated intent so a manually