Skip to content

The agent that grows with you

fix: load the all-profiles Projects view and PR badges over native grants

unsupportedpastels8a773c27a3d3
diff --git a/apps/desktop/e2e/legacy-desktop-history.spec.ts b/apps/desktop/e2e/legacy-desktop-history.spec.ts
index 3ea7f50360b..272f25c0025 100644
--- a/apps/desktop/e2e/legacy-desktop-history.spec.ts
+++ b/apps/desktop/e2e/legacy-desktop-history.spec.ts
@@ -102,6 +102,31 @@ seed(home / 'profiles' / 'developer' / 'state.db', [{'id': sys.argv[2], 'source'
}
}
+ // The all-profiles Projects view and PR badges: which profiles' sessions each read covers.
+ for (const [name, scope] of [['projects:all', {}], ['projects:all:registry', registry]] as const) {
+ try {
+ const r = await api({ path: '/api/profiles/projects/tree?preview_limit=10', ...scope })
+ const profiles = new Set<string>()
+
+ for (const project of r?.projects ?? []) {
+ for (const session of project.previewSessions ?? []) {
+ profiles.add(session.profile)
+ }
+ }
+
+ out[name] = { profiles: [...profiles].sort(), errors: r?.errors ?? [] }
+ } catch (e) {
+ out[name] = 'ERR ' + String((e as Error)?.message ?? e).slice(0, 200)
+ }
+ }
+
+ try {
+ const r = await api({ path: '/api/profiles/sessions/pull-requests', method: 'POST', body: { ids: ['legacy-desktop-anon'] } })
+ out['prs:all'] = { scanned: r?.scanned ?? null }
+ } catch (e) {
+ out['prs:all'] = 'ERR ' + String((e as Error)?.message ?? e).slice(0, 200)
+ }
+
return out
})
console.log('API_PROBES: ' + JSON.stringify(probes))
@@ -203,6 +228,10 @@ for p in alive:
const everyRow = [...ROWS.map(r => `default:${r.id}`), `developer:${NAMED_ROW}`].sort()
expect.soft(probes['sidebar:all'], 'sidebar:all').toEqual({ ids: everyRow, errors: [] })
expect.soft(probes['sidebar:all:registry'], 'sidebar:all:registry').toEqual({ ids: everyRow, errors: [] })
+ const everyProfile = { profiles: ['default', 'developer'], errors: [] }
+ expect.soft(probes['projects:all'], 'projects:all').toEqual(everyProfile)
+ expect.soft(probes['projects:all:registry'], 'projects:all:registry').toEqual(everyProfile)
+ expect.soft(probes['prs:all'], 'prs:all').toEqual({ scanned: ['legacy-desktop-anon'] })
expect.soft(probes['sessions:all'], 'sessions:all').toEqual({ ids: everyRow, errors: [] })
expect.soft(probes['sidebar:default'], 'sidebar:default').toEqual({ ids: ROWS.map(r => `default:${r.id}`).sort(), errors: [] })
expect.soft(probes['sidebar:developer'], 'sidebar:developer').toEqual({ ids: [`developer:${NAMED_ROW}`], errors: [] })
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 3abf73578e5..dca79c5bf03 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -463,12 +463,14 @@ import {
assembleSidebarSessionSlices,
buildSidebarSessionSliceParams,
composeUnifiedSessionResponse,
+ fetchAllProfilesAggregatePerProfile,
fetchAllProfilesSessionsPerProfile,
fetchPrimaryProfileSessions,
fetchRegistrySessionRows,
fetchRemoteProfileSessions,
findRemoteOwnerProfileForSession,
hasPinnedRegistrySessionSource,
+ isAllProfilesAggregateRequest,
isAllProfilesSessionListRequest,
pathWithRemoteOwnerScope,
type RegistrySessionSource,
@@ -15584,22 +15586,30 @@ async function getJsonForBackend(descriptor, path, opts: any = {}) {
async function fetchJsonForBackend(
descriptor,
path,
- opts: { method?: string; body?: unknown; upload?: unknown; timeoutMs?: number } = {}
+ opts: { method?: string; body?: unknown; upload?: unknown; timeoutMs?: number; profileScoped?: boolean } = {}
) {
const url = `${descriptor.baseUrl}${path}`
// A native grant names one profile and the gateway refuses `all`: assemble the unified
- // session lists from one read per profile, each carrying that profile's own grant.
- if (descriptor.gatewayEndpoint && isAllProfilesSessionListRequest(opts.method, path)) {
- const listing = (await fetchJsonForBackend(descriptor, '/api/profiles', { timeoutMs: opts.timeoutMs })) as any
+ // session lists, project tree and PR scan from one read per profile, each carrying that
+ // profile's own grant.
+ if (descriptor.gatewayEndpoint && !opts.profileScoped) {
+ const sessions = isAllProfilesSessionListRequest(opts.method, path)
- const profiles = (Array.isArray(listing?.profiles) ? listing.profiles : [])
- .map(profile => profile?.name)
- .filter(name => typeof name === 'string' && name)
+ if (sessions || isAllProfilesAggregateRequest(opts.method, path)) {
+ const listing = (await fetchJsonForBackend(descriptor, '/api/profiles', { timeoutMs: opts.timeoutMs })) as any
- return fetchAllProfilesSessionsPerProfile(path, profiles, (_profile, scoped) =>
- fetchJsonForBackend(descriptor, scoped, { timeoutMs: opts.timeoutMs })
- )
+ const profiles = (Array.isArray(listing?.profiles) ? listing.profiles : [])
+ .map(profile => profile?.name)
+ .filter(name => typeof name === 'string' && name)
+
+ const readProfile = (_profile, scoped) =>
+ fetchJsonForBackend(descriptor, scoped, { method: opts.method, body: opts.body, timeoutMs: opts.timeoutMs, profileScoped: true })
+
+ return sessions
+ ? fetchAllProfilesSessionsPerProfile(path, profiles, readProfile)
+ : fetchAllProfilesAggregatePerProfile(path, profiles, readProfile)
+ }
}
if (descriptor.authMode === 'oauth') {
diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.ts
index 662f3e95f81..de9883bcfcc 100644
--- a/apps/desktop/electron/profile-session-routing.test.ts
+++ b/apps/desktop/electron/profile-session-routing.test.ts
@@ -5,12 +5,14 @@ import { test } from 'vitest'
import {
assembleSidebarSessionSlices,
buildSidebarSessionSliceParams,
+ fetchAllProfilesAggregatePerProfile,
fetchAllProfilesSessionsPerProfile,
fetchPrimaryProfileSessions,
fetchRegistrySessionRows,
fetchRemoteProfileSessions,
findRemoteOwnerProfileForSession,
hasPinnedRegistrySessionSource,
+ isAllProfilesAggregateRequest,
isAllProfilesSessionListRequest,
mergeProfileSessionWindow,
pathWithRemoteOwnerScope,
@@ -1016,3 +1018,119 @@ test('all-profiles session list pages a deep per-profile read under the backend
assert.equal(result.sessions[0].id, 's400')
assert.equal(result.total, 650)
})
+
+test('the project tree and PR scan are all-profiles reads whatever route scope they carry', () => {
+ assert.equal(isAllProfilesAggregateRequest('GET', '/api/profiles/projects/tree?preview_limit=3'), true)
+ assert.equal(isAllProfilesAggregateRequest('GET', '/api/profiles/projects/tree?preview_limit=3&profile=default'), true)
+ assert.equal(isAllProfilesAggregateRequest('POST', '/api/profiles/sessions/pull-requests'), true)
+ assert.equal(isAllProfilesAggregateRequest('GET', '/api/profiles/sessions/pull-requests'), false)
+ assert.equal(isAllProfilesAggregateRequest('POST', '/api/profiles/projects/tree'), false)
+ assert.equal(isAllProfilesAggregateRequest('GET', '/api/profiles/sessions?profile=all'), false)
+})
+
+test('all-profiles project tree merges one read per profile by folder', async () => {
+ const reads: string[] = []
+ const session = (id: string, profile: string, last: number) => ({ id, profile, last_active: last })
+
+ const pages: Record<string, unknown> = {
+ default: {
+ projects: [
+ {
+ id: 'auto:/repo', mergeKey: '/repo', path: '/repo', label: 'repo', isAuto: true, sessionCount: 2,
+ totalTokens: 10, totalCostUsd: 1, lastActive: 5,
+ previewSessions: [session('d1', 'default', 5), session('d2', 'default', 1)],
+ repos: [{ id: 'r', sessionCount: 2, groups: [{ id: 'main', sessionCount: 2, sessions: [session('d1', 'default', 5)] }] }]
+ },
+ { id: '__no_project__', mergeKey: '__no_project__', isNoProject: true, sessionCount: 1, lastActive: 2, previewSessions: [session('d3', 'default', 2)] }
+ ],
+ active_id: null,
+ scoped_session_ids: ['d1'],
+ errors: []
+ },
+ work: {
+ projects: [
+ {
+ id: 'p_abc', mergeKey: '/repo', path: '/repo', label: 'Declared', isAuto: false, sessionCount: 1,
+ totalTokens: 5, totalCostUsd: 0.5, lastActive: 9,
+ previewSessions: [session('w1', 'work', 9)],
+ repos: [{ id: 'r', sessionCount: 1, groups: [{ id: 'main', sessionCount: 1, sessions: [session('w1', 'work', 9)] }] }]
+ }
+ ],
+ active_id: null,
+ scoped_session_ids: ['w1'],
+ errors: []
+ }
+ }
+
+ const result = (await fetchAllProfilesAggregatePerProfile(
+ '/api/profiles/projects/tree?preview_limit=2&profile=default',
+ ['default', 'work', 'broken'],
+ async (profile, path) => {
+ reads.push(path)
+
+ if (profile === 'broken') {
+ throw new Error('403: denied')
+ }
+
+ return structuredClone(pages[profile])
+ }
+ )) as any
+
+ // Each read names only the profile it reads, replacing the route's own scope.
+ assert.deepEqual(reads.sort(), [
+ '/api/profiles/projects/tree?preview_limit=2&profile=broken',
+ '/api/profiles/projects/tree?preview_limit=2&profile=default',
+ '/api/profiles/projects/tree?preview_limit=2&profile=work'
+ ])
+ assert.deepEqual(result.projects.map((p: any) => p.label ?? p.id), ['Declared', '__no_project__'])
+ const repo = result.projects[0]
+ assert.equal(repo.sessionCount, 3)
+ assert.equal(repo.totalTokens, 15)
+ assert.equal(repo.totalCostUsd, 1.5)
+ assert.equal(repo.lastActive, 9)
+ assert.deepEqual(repo.previewSessions.map((s: any) => s.id), ['w1', 'd1'])
+ assert.equal(repo.repos.length, 1)
+ assert.equal(repo.repos[0].sessionCount, 3)
+ assert.deepEqual(repo.repos[0].groups[0].sessions.map((s: any) => s.id), ['w1', 'd1'])
+ assert.deepEqual(result.scoped_session_ids, ['d1', 'w1'])
+ assert.equal(result.active_id, null)
+ assert.deepEqual(result.errors, [{ profile: 'broken', error: '403: denied' }])
+})
+
+test('all-profiles project tree fails when no profile can be read', async () => {
+ await assert.rejects(
+ fetchAllProfilesAggregatePerProfile('/api/profiles/projects/tree', ['default'], async () => {
+ throw new Error('Gateway ticket bootstrap failed')
+ }),
+ /default: Gateway ticket bootstrap failed/
+ )
+})
+
+test('all-profiles PR scan unions the profiles and settles only what it could read', async () => {
+ const pr = (n: number) => ({ number: n, url: `https://github.com/o/r/pull/${n}` })
+
+ const complete = (await fetchAllProfilesAggregatePerProfile(
+ '/api/profiles/sessions/pull-requests',
+ ['default', 'work'],
+ async profile => ({
+ pull_requests: profile === 'default' ? { a: pr(1) } : { b: pr(2) },
+ scanned: ['a', 'b', 'c']
+ })
+ )) as any
+
+ assert.deepEqual(complete, { pull_requests: { a: pr(1), b: pr(2) }, scanned: ['a', 'b', 'c'] })
+
+ const partial = (await fetchAllProfilesAggregatePerProfile(
+ '/api/profiles/sessions/pull-requests',
+ ['default', 'work'],
+ async profile => {
+ if (profile === 'work') {
+ throw new Error('timeout')
+ }
+
+ return { pull_requests: { a: pr(1) }, scanned: ['a', 'b', 'c'] }
+ }
+ )) as any
+
+ assert.deepEqual(partial, { pull_requests: { a: pr(1) }, scanned: ['a'] })
+})
diff --git a/apps/desktop/electron/profile-session-routing.ts b/apps/desktop/electron/profile-session-routing.ts
index b6ee3203613..ccc27016043 100644
--- a/apps/desktop/electron/profile-session-routing.ts
+++ b/apps/desktop/electron/profile-session-routing.ts
@@ -1145,3 +1145,156 @@ export async function fetchAllProfilesSessionsPerProfile(
? allProfilesSidebar(url, profiles, fetchPage)
: allProfilesSessionList(url, profiles, fetchPage)
}
+
+/** Cross-profile reads the gateway builds by scanning every profile's databases: the
+ * all-profiles project tree and the PR scan. The renderer asks for them only for the
+ * all-profiles view, so a `profile` already on the path is the route's own scope, not a
+ * selector; the per-profile reads carry their own scope and are made with `profileScoped`. */
+export function isAllProfilesAggregateRequest(method: string | undefined, path: string | undefined): boolean {
+ if (!path) {
+ return false
+ }
+
+ let pathname: string
+
+ try {
+ pathname = new URL(path, 'http://desktop.local').pathname.replace(/\/+$/, '')
+ } catch {
+ return false
+ }
+
+ const verb = (method || 'GET').toUpperCase()
+
+ return (
+ (verb === 'GET' && pathname === '/api/profiles/projects/tree') ||
+ (verb === 'POST' && pathname === '/api/profiles/sessions/pull-requests')
+ )
+}
+
+function mergeTreeById(into: Map<string, any>, entries: any[], childKey: string): void {
+ for (const entry of entries) {
+ const existing = into.get(entry.id)
+
+ if (!existing) {
+ into.set(entry.id, entry)
+
+ continue
+ }
+
+ if (childKey === 'sessions') {
+ existing.sessions = [...(existing.sessions ?? []), ...(entry.sessions ?? [])]
+ } else {
+ const children = new Map<string, any>((existing[childKey] ?? []).map((child: any) => [child.id, child]))
+ mergeTreeById(children, entry[childKey] ?? [], 'sessions')
+ existing[childKey] = [...children.values()]
+ }
+
+ if ('sessionCount' in existing) {
+ existing.sessionCount = (existing.sessionCount || 0) + (entry.sessionCount || 0)
+ }
+ }
+}
+
+// The gateway's own cross-profile merge (`_merge_profile_tree`), keyed by the folder key each
+// per-profile read reports: one group per folder, a declared project wins over another
+// profile's auto entry, totals add up, and the previews are the newest across profiles.
+function mergeProfileProjectTrees(reads: ProfileRead[], previewLimit: number) {
+ const merged = new Map<string, any>()
+ const scopedSessionIds: unknown[] = []
+ const errors: SessionScanError[] = []
+
+ for (const read of reads) {
+ if ('error' in read) {
+ errors.push({ profile: read.profile, error: read.error })
+
+ continue
+ }
+
+ scopedSessionIds.push(...(Array.isArray(read.data?.scoped_session_ids) ? read.data.scoped_session_ids : []))
+ errors.push(...(errorsOf(read.data) ?? []))
+
+ for (const incoming of Array.isArray(read.data?.projects) ? read.data.projects : []) {
+ let project = incoming
+ const key = String(project.mergeKey ?? project.path ?? project.id)
+ let existing = merged.get(key)
+
+ if (!existing) {
+ merged.set(key, project)
+
+ continue
+ }
+
+ if (existing.isAuto && !project.isAuto) {
+ ;[existing, project] = [project, existing]
+ merged.set(key, existing)
+ }
+
+ const repos = new Map<string, any>((existing.repos ?? []).map((repo: any) => [repo.id, repo]))
+ mergeTreeById(repos, project.repos ?? [], 'groups')
+ existing.repos = [...repos.values()]
+
+ for (const total of ['sessionCount', 'totalTokens', 'totalCostUsd']) {
+ existing[total] = (existing[total] || 0) + (project[total] || 0)
+ }
+
+ existing.lastActive = Math.max(existing.lastActive || 0, project.lastActive || 0)
+ existing.previewSessions = [...(existing.previewSessions ?? []), ...(project.previewSessions ?? [])]
+ .sort((a, b) => recencyOf(b) - recencyOf(a))
+ .slice(0, previewLimit)
+ }
+ }
+
+ const projects = [...merged.values()].sort((a, b) => (b.lastActive || 0) - (a.lastActive || 0))
+
+ return { projects, active_id: null, scoped_session_ids: scopedSessionIds, errors }
+}
+
+function mergeProfilePullRequests(reads: ProfileRead[]) {
+ const pullRequests: Record<string, unknown> = {}
+ let scanned: unknown[] = []
+
+ // Profile order, like the gateway's scan: a later profile's match wins.
+ for (const read of reads) {
+ if (!('error' in read)) {
+ Object.assign(pullRequests, read.data?.pull_requests)
+ scanned = Array.isArray(read.data?.scanned) ? read.data.scanned : scanned
+ }
+ }
+
+ // `scanned` lets the caller stop asking about an id. An unread profile scanned nothing, so
+ // only the ids that did resolve are settled.
+ return {
+ pull_requests: pullRequests,
+ scanned: reads.some(read => 'error' in read) ? Object.keys(pullRequests) : scanned
+ }
+}
+
+/** The all-profiles project tree or PR scan, assembled from one read per profile.
+ *
+ * A native gateway grant names ONE profile, so each profile is read with its own grant
+ * (`fetchProfile` gets the path scoped to it). A profile that cannot be read is reported in
+ * `errors`; when none can be read the call fails, as the single request would have. */
+export async function fetchAllProfilesAggregatePerProfile(
+ path: string,
+ profiles: readonly string[],
+ fetchProfile: FetchProfilePage
+): Promise<unknown> {
+ const url = new URL(path, 'http://desktop.local')
+
+ const reads = await readEachProfile(profiles, profile => {
+ const params = new URLSearchParams(url.searchParams)
+ params.set('profile', profile)
+
+ return fetchProfile(profile, `${url.pathname}?${params}`)
+ })
+
+ if (!reads.some(read => !('error' in read))) {
+ throw new Error(reads.map(read => ('error' in read ? `${read.profile}: ${read.error}` : '')).join('; ') || 'No profiles to read')
+ }
+
+ if (url.pathname.replace(/\/+$/, '') === '/api/profiles/projects/tree') {
+ return mergeProfileProjectTrees(reads, Math.max(0, Number(url.searchParams.get('preview_limit') ?? 3) || 0))
+ }
+
+ return mergeProfilePullRequests(reads)
+}
diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.py
index eec9fc130c3..25bd3cb07ce 100644
--- a/hermes_cli/dashboard_auth/native_http.py
+++ b/hermes_cli/dashboard_auth/native_http.py
@@ -84,6 +84,7 @@ async def _check_profile_scope(request, profile_id):
suffix = path.removeprefix('/api/profiles/')
aggregate_selector = {
'sessions': 'profile', 'sessions/sidebar': 'recents_profile',
+ 'projects/tree': 'profile', 'sessions/pull-requests': 'profile',
}.get(suffix)
if aggregate_selector:
values = request.query_params.getlist(aggregate_selector)
@@ -94,7 +95,7 @@ async def _check_profile_scope(request, profile_id):
_own_profile(value, profile_id, current=False)
elif suffix == 'active' and request.method == 'GET':
return # Discovery of sticky defaults does not switch this daemon.
- elif suffix in {'active', 'import', 'projects/tree', 'sessions/pull-requests'}:
+ elif suffix in {'active', 'import'}:
raise PermissionError('profile_scope_mismatch')
else:
_own_profile(suffix.split('/', 1)[0], profile_id, current=False)
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index 783ec2376fc..718c82982c1 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -228,6 +228,14 @@ def _profile_targets(log_label: str) -> list[tuple[str, Path]]:
return targets
+def _scoped_profile_targets(log_label: str, profile: Optional[str]) -> list[tuple[str, Path]]:
+ """Every profile, or only ``profile``: a native grant may read just the profile it names,
+ so the Desktop assembles the all-profiles view from one scoped read per profile."""
+ scope = (profile or "all").strip() or "all"
+ targets = _profile_targets(log_label)
+ return targets if scope == "all" else [(name, home) for name, home in targets if name == scope]
+
+
def _tag_rows(rows: list[dict[str, Any]], name: str, now: float) -> list[dict[str, Any]]:
"""Stamp session rows with their owning profile and the 300s active heuristic; SQLite
stores flags as 0/1 and the sidebar needs booleans."""
@@ -670,6 +678,8 @@ def _merge_profile_tree(
# so the cross-profile merge agrees by construction with the trees it merges.
from tui_gateway.project_tree import _path_key
key = _path_key(project.get("path") or project["id"])
+ # A per-profile read is merged again by its caller, which cannot compute this key.
+ project["mergeKey"] = key
existing = merged.get(key)
if existing is None:
merged[key] = project
@@ -694,7 +704,7 @@ def _merge_profile_tree(
@sessions_router.get("/api/profiles/projects/tree")
@_sidebar_singleflight_cache
-def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000):
+def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000, profile: Optional[str] = None):
"""Project tree for every profile at once, for the all-profiles sidebar.
``projects.tree`` over JSON-RPC answers for the backend's own profile only; this runs the
@@ -703,13 +713,16 @@ def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000
off: a repo with zero sessions is the same repo in every profile (the disk scan would
multiply empty lanes by the profile count), and discovery is the one part of the builder
that writes (policy reconciliation), which a read-only fan-out must not do.
+
+ ``profile`` limits the scan to that one profile: a native grant may read only its own, so
+ the Desktop merges one such read per profile by each project's ``mergeKey``.
"""
from tui_gateway import server as gateway_server
merged: dict[str, dict[str, Any]] = {}
scoped_session_ids: list[str] = []
errors: list[dict[str, str]] = []
- for name, home in _profile_targets("GET /api/profiles/projects/tree"):
+ for name, home in _scoped_profile_targets("GET /api/profiles/projects/tree", profile):
def _read(db, name=name, home=home):
with _hermes_home_scope(home):
tree, _active_id = gateway_server._build_project_tree(
@@ -743,7 +756,7 @@ def _pr_url_from_tool_output(content: str) -> Optional[tuple[int, str]]:
@sessions_router.post("/api/profiles/sessions/pull-requests")
-def post_profiles_sessions_pull_requests(body: SessionPrScanBody):
+def post_profiles_sessions_pull_requests(body: SessionPrScanBody, profile: Optional[str] = None):
"""The PR each of these sessions opened, recovered from its own transcript: a session
that starts in the main checkout and works in a worktree has no branch of its own, so
its PR is invisible to the branch join — but ``gh pr create`` ran in the conversation
@@ -761,7 +774,7 @@ def post_profiles_sessions_pull_requests(body: SessionPrScanBody):
# Oldest-first, so a later `gh pr create` (the replacement PR) wins.
found[pr["session_id"]] = {"number": parsed[0], "url": parsed[1]}
- for name, home in _profile_targets("POST /api/profiles/sessions/pull-requests"):
+ for name, home in _scoped_profile_targets("POST /api/profiles/sessions/pull-requests", profile):
_read_profile_db(name, home, None, _read)
# ``scanned``: every id looked at, so the caller can remember "nothing there".
diff --git a/tests/gateway/test_native_http_auth.py b/tests/gateway/test_native_http_auth.py
index 571ed413a77..8ba94e22e4b 100644
--- a/tests/gateway/test_native_http_auth.py
+++ b/tests/gateway/test_native_http_auth.py
@@ -129,6 +129,16 @@ def test_native_http_grants_are_single_use_and_bound_to_daemon(tmp_path):
headers=headers(ticket(home, descriptor))).status_code == 200
assert client.get('/api/profiles/sessions/sidebar?recents_profile=default',
headers=headers(ticket(home, descriptor))).status_code == 200
+ # The cross-profile project tree and PR scan answer one grant for its own profile only.
+ assert client.get('/api/profiles/projects/tree?profile=default',
+ headers=headers(ticket(home, descriptor))).status_code == 200
+ assert client.post('/api/profiles/sessions/pull-requests?profile=default', json={'ids': ['x']},
+ headers=headers(ticket(home, descriptor))).status_code == 200
+ for scope in ('', '?profile=all', '?profile=other', '?profile=default&profile=other'):
+ assert client.get('/api/profiles/projects/tree' + scope,
+ headers=headers(ticket(home, descriptor))).status_code == 403, scope
+ assert client.post('/api/profiles/sessions/pull-requests' + scope, json={'ids': ['x']},
+ headers=headers(ticket(home, descriptor))).status_code == 403, scope
assert client.get('/api/config?profile=current',
headers=headers(ticket(home, descriptor))).status_code == 200
assert client.get('/api/profiles', headers=headers(ticket(home, descriptor))).status_code == 200
diff --git a/tests/hermes_cli/test_profiles_sidebar_scope.py b/tests/hermes_cli/test_profiles_sidebar_scope.py
index 2c059257bd4..c9aaa090b4f 100644
--- a/tests/hermes_cli/test_profiles_sidebar_scope.py
+++ b/tests/hermes_cli/test_profiles_sidebar_scope.py
@@ -229,6 +229,21 @@ class TestCrossProfileProjectTree:
assert labels == {"Only default", "Only worker"}
+ def test_a_named_profile_reads_only_its_own_tree(self, client, profiles_on_disk, tmp_path):
+ # The per-profile read a native grant makes; its caller merges the profiles by mergeKey.
+ for name in profiles_on_disk:
+ (tmp_path / "repos" / f"only-{name}").mkdir(parents=True)
+ _seed_session(profiles_on_disk[name], f"{name}-chat", source="cli")
+ _seed_project(profiles_on_disk[name], f"Only {name}", tmp_path / "repos" / f"only-{name}")
+
+ payload = client.get("/api/profiles/projects/tree", params={"profile": "worker"}).json()
+
+ assert payload["errors"] == []
+ assert {project["label"] for project in payload["projects"] if not project["isNoProject"]} == {"Only worker"}
+ assert all(project["mergeKey"] for project in payload["projects"])
+ sessions = [s for project in payload["projects"] for s in project.get("previewSessions") or []]
+ assert {s["profile"] for s in sessions} == {"worker"}
+
def test_a_profile_that_cannot_be_read_does_not_sink_the_rest(
self, client, profiles_on_disk, tmp_path, monkeypatch
):