The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): agent preview tools see only their own profile's pins and runtime's tabs
teknium1d481030dff18
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.tsindex b72ca1bd025..41367d7eadc 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts@@ -1,11 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { registerPreviewNav } from '@/app/chat/right-rail/preview-nav'+import { registerPreviewPageReader } from '@/app/chat/right-rail/preview-reader'import { group } from '@/components/pane-shell/tree/model'import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'import { createClientSessionState } from '@/lib/chat-runtime'import { runTour } from '@/lib/tour'-import { $previewTabs, closeRightRail, openPreview } from '@/store/preview'+import { $previewTabs, closeRightRail, openPreview, setPreviewTabPinned } from '@/store/preview'import { hasOpenServerRequest, resetServerRequestsForTests } from '@/store/server-requests'import { setActiveSessionId, setSelectedStoredSessionId, setSessions } from '@/store/session'import { $sessionStates, $sessionTiles, dropSessionState, publishSessionState } from '@/store/session-states'@@ -344,7 +345,8 @@ describe('window.read claim tolerance (#121609)', () => {describe('preview pop-out forwarding', () => {// The requester reaches the pop-out: it answers only for that session's tabs.- const sessionAOwner = { runtimeId: 'session-a', sessionId: 'stored-a' }+ // It also names its profile: only that profile's pins may answer it.+ const sessionAOwner = { profile: 'default', runtimeId: 'session-a', sessionId: 'stored-a' }beforeEach(() => {hasLivePreviewSurface.mockReturnValue(false)@@ -455,7 +457,11 @@ describe('preview requests act for the session that asked (#73890)', () => {const { respond } = deliver('tour', { action: 'discover', session_id: 'rt-a', surface: 'preview' }, 'rt-a')await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1), { timeout: 30_000 })- expect(runTour).toHaveBeenCalledWith(expect.anything(), 'preview', { runtimeId: 'rt-a', sessionId: 'stored-a' })+ expect(runTour).toHaveBeenCalledWith(expect.anything(), 'preview', {+ profile: 'default',+ runtimeId: 'rt-a',+ sessionId: 'stored-a'+ })})it('drives the tab its runtime opened before the selection named its stored id', async () => {@@ -480,6 +486,40 @@ describe('preview requests act for the session that asked (#73890)', () => {}})+ it("never answers a tile of another profile with the viewed profile's pinned page", async () => {+ // Profile X's runtime stays open as a tile while the primary's profile+ // (the bucket in view) has a pinned Browser.+ $sessionTiles.set([+ { dir: 'right', ownerProfile: 'prof-p1-x', runtimeId: 'rt-x', storedSessionId: 'stored-x' } as never+ ])+ publishSessionState('rt-x', createClientSessionState('stored-x'))+ openPreview({ kind: 'url', label: 'y', source: 'https://y.example', url: 'https://y.example' }, 'stored-a')+ const pin = $previewTabs.get()[0]!.id+ setPreviewTabPinned(pin, true)++ const unbind = registerPreviewPageReader(pin, async () => ({+ text: 'PROFILE_Y_PRIVATE_TEXT',+ title: 'y',+ url: 'https://y.example'+ }))++ try {+ const fromX = deliver('preview.read', { session_id: 'rt-x' }, 'rt-a')++ await vi.waitFor(() => expect(fromX.respond).toHaveBeenCalledTimes(1), { timeout: 30_000 })+ expect(fromX.respond.mock.calls[0][0].value).toBe('')++ // Control: the pin's own profile still reads it.+ const fromA = deliver('preview.read', { session_id: 'rt-a' }, 'rt-a')++ await vi.waitFor(() => expect(fromA.respond).toHaveBeenCalledTimes(1), { timeout: 30_000 })+ expect(JSON.parse(fromA.respond.mock.calls[0][0].value)).toMatchObject({ text: 'PROFILE_Y_PRIVATE_TEXT' })+ } finally {+ unbind()+ dropSessionState('rt-x')+ }+ })+it('reads no tab for a requester whose stored id is not bound yet, never the focused one', async () => {// A fresh primary runtime whose stored id has not arrived; tile B focused.setActiveSessionId('rt-new')diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.tsindex abac07d5be4..65e74bb1828 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts@@ -31,7 +31,12 @@ import {} from '@/store/prompts'import { rememberServerRequest } from '@/store/server-requests'import { $selectedStoredSessionId, $sessions, lineageAliases, sessionMatchesStoredId } from '@/store/session'-import { $sessionStates, $sessionTiles, storedSessionIdForRuntimeId } from '@/store/session-states'+import {+ $sessionStates,+ $sessionTiles,+ previewScopeForRuntime,+ storedSessionIdForRuntimeId+} from '@/store/session-states'import { requestScrollToBottom } from '@/store/thread-scroll'import { $toursEnabled } from '@/store/tours'@@ -55,12 +60,20 @@ const loadPreviewEngine = () => {const str = (v: unknown): string => (typeof v === 'string' ? v : '')/** Whose preview tabs a scoped agent request may see: the requesting- * runtime's stored id plus the tabs that runtime opened before the id bound.- * An id that does not resolve yet is null — the ownerless view — never the- * focused session's tabs. Only an unscoped request (no id) falls through to- * the focused session (undefined). */+ * runtime's stored id plus the tabs that runtime opened before the id bound,+ * and the pins of the profile that runtime belongs to — never the viewed+ * profile's pins on another profile's behalf. An id that does not resolve+ * yet has no stored id — the runtime's own pending tabs — never the focused+ * session's tabs. Only an unscoped request (no id) falls through to the+ * focused session (undefined). */const previewOwnerFor = (sessionId: string): PreviewOwner | undefined =>- sessionId ? { runtimeId: sessionId, sessionId: storedSessionIdForRuntimeId(sessionId) } : undefined+ sessionId+ ? {+ profile: previewScopeForRuntime(sessionId),+ runtimeId: sessionId,+ sessionId: storedSessionIdForRuntimeId(sessionId)+ }+ : undefinedconst num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined)diff --git a/apps/desktop/src/app/session/hooks/use-preview-routing.ts b/apps/desktop/src/app/session/hooks/use-preview-routing.tsindex 3d2858eafdc..61e44cee3bb 100644--- a/apps/desktop/src/app/session/hooks/use-preview-routing.ts+++ b/apps/desktop/src/app/session/hooks/use-preview-routing.ts@@ -10,13 +10,19 @@ import {closeAgentPreview,completePreviewServerRestart,openPreview,+ type PreviewOwner,progressPreviewServerRestart,renderedHtmlTarget,requestPreviewReload} from '@/store/preview'import { $activeSessionId, $currentCwd } from '@/store/session'import { $focusedStoredSessionId } from '@/store/session-focus'-import { $focusedRuntimeId, $sessionTiles, storedSessionIdForRuntimeId } from '@/store/session-states'+import {+ $focusedRuntimeId,+ $sessionTiles,+ previewScopeForRuntime,+ storedSessionIdForRuntimeId+} from '@/store/session-states'type EventHandler = (event: GatewayEvent) => void@@ -45,6 +51,14 @@ function previewOwnerForEvent(sessionId: string | undefined): null | string {return sessionId ? storedSessionIdForRuntimeId(sessionId) : $focusedStoredSessionId.get()}+/** The full identity an agent's close acts for: its stored id, the runtime+ * (its pending tabs) and its profile (the only pins it may close). */+function previewCloserForEvent(sessionId: string | undefined): PreviewOwner {+ return sessionId+ ? { profile: previewScopeForRuntime(sessionId), runtimeId: sessionId, sessionId: previewOwnerForEvent(sessionId) }+ : previewOwnerForEvent(sessionId)+}+export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestGateway }: PreviewRoutingOptions) {const restartPreviewServer = useCallback(async (url: string, context?: string) => {@@ -112,7 +126,9 @@ export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestGrenderedHtmlTarget(trimmedLabel ? { ...reached, label: trimmedLabel } : reached),previewOwnerForEvent(event.session_id),// The runtime that ran the tool, should its stored id lag.- event.session_id || undefined+ event.session_id || undefined,+ // Its profile: another profile's pinned Browser is not its to navigate.+ event.session_id ? previewScopeForRuntime(event.session_id) : undefined)})@@ -132,7 +148,7 @@ export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestGreturn}- const owner = previewOwnerForEvent(event.session_id)+ const owner = previewCloserForEvent(event.session_id)if (!target) {closeAgentPreview(owner, [])diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.tsindex 9b88dc9e2ba..820cc18b12b 100644--- a/apps/desktop/src/store/preview.test.ts+++ b/apps/desktop/src/store/preview.test.ts@@ -30,6 +30,7 @@ import {openPreview,previewTabId,previewTabIdsVisibleTo,+ previewTabsFor,type PreviewTarget,progressPreviewServerRestart,prunePreviewTabsForSession,@@ -618,6 +619,60 @@ describe('preview session scoping (#73890)', () => {}})+ it("authorizes only the requester's own profile pins for a pop-out, never the viewed profile's", () => {+ try {+ setPreviewScope('prof-p1-x')+ openPreview(urlTarget('https://x-pin.example'), 'stored-p1-x')+ const xPin = $previewTabs.get()[0]!.id+ setPreviewTabPinned(xPin, true)+ setPreviewScope('prof-p1-y')+ openPreview(urlTarget('https://y-private.example'), 'stored-p1-y')+ const yPin = $previewTabs.get()[0]!.id+ setPreviewTabPinned(yPin, true)+ openPreview(fileTarget('/work/x-in-y.html'), 'stored-p1-x')+ const xOwnInView = $previewTabs.get().find(tab => tab.target.path === '/work/x-in-y.html')!.id++ const fromX = { profile: 'prof-p1-x', runtimeId: 'rt-p1-x', sessionId: 'stored-p1-x' }+ const fromY = { profile: 'prof-p1-y', runtimeId: 'rt-p1-y', sessionId: 'stored-p1-y' }++ expect(previewTabsFor(fromX).map(tab => tab.id)).toEqual([xOwnInView])+ expect(previewTabIdsVisibleTo(fromX).sort()).toEqual([xOwnInView, xPin].sort())+ expect(previewTabsFor(fromY).map(tab => tab.id)).toEqual([yPin])+ expect(previewTabIdsVisibleTo(fromY)).toEqual([yPin])+ } finally {+ setPreviewScope('default')+ dropPreviewTabsForProfile('prof-p1-x')+ dropPreviewTabsForProfile('prof-p1-y')+ }+ })++ it("keeps one pending runtime's Browser out of another pending runtime's reads, opens and closes", () => {+ openPreview(urlTarget('https://runtime-a.example'), null, 'rt-pend-a')+ const aTab = $previewTabs.get()[0]!.id+ const fromB = { runtimeId: 'rt-pend-b', sessionId: null }++ expect(previewTabsFor(fromB)).toEqual([])+ expect(previewTabIdsVisibleTo(fromB)).toEqual([])++ openPreview(urlTarget('https://runtime-b.example'), null, 'rt-pend-b')+ const bTab = $previewTabs.get().find(tab => tab.id !== aTab)?.id++ expect($previewTabs.get().find(tab => tab.id === aTab)?.target.url).toBe('https://runtime-a.example')+ expect(bTab).toBeDefined()++ closeAgentPreview(fromB, [])+ expect($previewTabs.get().map(tab => tab.id)).toEqual([aTab])++ // A's own stored id binding still adopts the tab B left alone.+ publishSessionState('rt-pend-a', createClientSessionState('stored-pend-a'))++ try {+ expect($previewTabs.get()[0]?.sessionId).toBe('stored-pend-a')+ } finally {+ dropSessionState('rt-pend-a')+ }+ })+it("records the agent event's runtime, not whichever runtime is active", () => {$activeSessionId.set('runtime-w')diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.tsindex 1b94f70d0d4..4af73e81aec 100644--- a/apps/desktop/src/store/preview.ts+++ b/apps/desktop/src/store/preview.ts@@ -397,35 +397,74 @@ function tabVisibleTo(tab: PreviewTab, sessionId: null | string, rotated: Readonreturn Boolean(tab.pinned) || latestSessionId(tab.sessionId, rotated) === latestSessionId(sessionId, rotated)}-function tabsVisibleTo(tabs: readonly PreviewTab[], sessionId: null | string): PreviewTab[] {- const rotated = $rotatedSessionIds.get()+/** Who an agent tool acts for: a stored id (null = none bound yet), or the+ * full identity of the runtime asking — its stored id, the runtime itself+ * (the tabs it opened before that id bound are its own) and the profile it+ * belongs to, whose bucket is the only one whose pins it may use. A bare id+ * (no profile) is a request from the chat on screen: the viewed bucket's+ * pins. */+export type PreviewOwner =+ null | string | { profile?: null | string; runtimeId: null | string; sessionId: null | string }- return tabs.filter(tab => tabVisibleTo(tab, sessionId, rotated))+interface OwnerIdentity {+ /** Normalized profile whose pins the owner shares; null = the view's. */+ profile: null | string+ runtimeId: null | string+ sessionId: null | string}-/** Who an agent tool acts for: a stored id (null = none bound yet), or that- * plus the runtime asking. A runtime's tabs opened before its stored id bound- * are its own too, even once the selection names that id. */-export type PreviewOwner = null | string | { runtimeId: string; sessionId: null | string }+function ownerIdentity(owner: PreviewOwner): OwnerIdentity {+ if (owner === null || typeof owner !== 'object') {+ return { profile: null, runtimeId: null, sessionId: owner }+ }-function tabsOwnedBy(tabs: readonly PreviewTab[], owner: PreviewOwner): PreviewTab[] {- const { runtimeId, sessionId } =- owner !== null && typeof owner === 'object' ? owner : { runtimeId: null, sessionId: owner }+ return {+ profile: owner.profile ? normalizeProfileKey(owner.profile) || 'default' : null,+ runtimeId: owner.runtimeId,+ sessionId: owner.sessionId+ }+}- const pending = $pendingRuntimeByTab.get()- const rotated = $rotatedSessionIds.get()+/** True when `tab` is `who`'s own — pins aside. A stored owner matches by id+ * through every compression rotation. An ownerless tab is one of two things,+ * never a shared pool: a RUNTIME's pending tab (opened before its stored id+ * bound), which only that runtime owns; or a true DRAFT tab (opened in a+ * fresh draft before any runtime existed), which only the draft on screen+ * owns — the primary's runtime while it has no stored id, or a request with+ * no runtime at all. `inView`: a draft tab outside the viewed bucket belongs+ * to no draft on screen. */+function ownsTab(tab: PreviewTab, who: OwnerIdentity, inView: boolean): boolean {+ if (tab.sessionId != null) {+ const rotated = $rotatedSessionIds.get()- return tabs.filter(- tab =>- tabVisibleTo(tab, sessionId, rotated) ||- (runtimeId !== null && tab.sessionId == null && pending.get(tab.id) === runtimeId)- )+ return who.sessionId != null && latestSessionId(tab.sessionId, rotated) === latestSessionId(who.sessionId, rotated)+ }++ const draftRuntime = $activeSessionId.get()+ // A request naming no runtime and no session speaks for the draft on screen.+ const runtime = who.runtimeId ?? (who.sessionId == null ? draftRuntime : null)+ const pendingRuntime = $pendingRuntimeByTab.get().get(tab.id)++ if (pendingRuntime !== undefined) {+ return runtime === pendingRuntime+ }++ return inView && who.sessionId == null && runtime === draftRuntime+}++/** `who`'s tabs in one bucket: its own, plus the bucket's pins when it is+ * `who`'s profile. */+function bucketTabsFor(tabs: readonly PreviewTab[], who: OwnerIdentity, key: string): PreviewTab[] {+ const sharesPins = key === (who.profile ?? viewKey)++ return tabs.filter(tab => (tab.pinned && sharesPins) || ownsTab(tab, who, key === viewKey))}/** The tabs an agent tool acting for `owner` (default: the focused session)- * may read or drive: never another session's hidden tab. A popped-out- * Browser renderer answers only for the one tab it shows (the chat window- * decided the requester may see it — `previewTabIdsVisibleTo`). */+ * may read or drive: never another session's hidden tab, and never another+ * profile's pin. A popped-out Browser renderer answers only for the one tab+ * it shows (the chat window decided the requester may see it —+ * `previewTabIdsVisibleTo`). */export function previewTabsFor(owner: PreviewOwner = $focusedStoredSessionId.get()): PreviewTab[] {if (isBrowserWindow()) {const own = windowBrowserTabId()@@ -433,24 +472,22 @@ export function previewTabsFor(owner: PreviewOwner = $focusedStoredSessionId.getreturn $previewTabs.get().filter(tab => tab.id === own)}- return tabsOwnedBy($previewTabs.get(), owner)+ return bucketTabsFor($previewTabs.get(), ownerIdentity(owner), viewKey)}/** Ids of the tabs `owner` may see in ANY profile's rail, for scoping a* request to a popped-out Browser window: a background session's Browser- * can be popped out while another profile is in view. A background bucket- * counts only when the requester has a tab of its own there, so one- * profile's pins never answer for another profile's session. */+ * can be popped out while another profile is in view. Its own tabs count in+ * every bucket; pins only in its own profile's. */export function previewTabIdsVisibleTo(owner: PreviewOwner): string[] {- const view = tabsOwnedBy($previewTabs.get(), owner)+ const who = ownerIdentity(owner)- const background = Object.entries(tabsByProfile).flatMap(([key, tabs]) => {- const visible = key === viewKey ? [] : tabsOwnedBy(tabs, owner)+ const buckets: [string, readonly PreviewTab[]][] = [+ [viewKey, $previewTabs.get()],+ ...Object.entries(tabsByProfile).filter(([key]) => key !== viewKey)+ ]- return visible.some(tab => !tab.pinned) ? visible : []- })-- return [...view, ...background].map(tab => tab.id)+ return buckets.flatMap(([key, tabs]) => bucketTabsFor(tabs, who, key)).map(tab => tab.id)}/** The primary's selection names a session the list already holds — one being@@ -1018,13 +1055,24 @@ export function openPreview(/** The runtime asking: an ownerless tab is handed to it once its stored id* binds. An agent event passes its own session id; anything else is the* primary's runtime. */- runtimeId: null | string = $activeSessionId.get()+ runtimeId: null | string = $activeSessionId.get(),+ /** The asking agent's profile, when it is not the chat on screen: only that+ * profile's pins may be reused. Omitted = the viewed profile. */+ profile?: null | string) {// Stamp the tip, not an alias: the alias map is memory-only, so a tab// stamped with a rotated-away id would be orphaned by the next relaunch.const owner = currentSessionId(requestedOwner)const current = $previewTabs.get()- const visible = tabsVisibleTo(current, owner)++ // Reuse never crosses runtimes: with no stored id yet, the runtime decides+ // which ownerless tabs are this opener's (its own pending ones, or the+ // draft's when it is the draft on screen).+ const visible = bucketTabsFor(+ current,+ ownerIdentity({ profile, runtimeId: owner === null ? runtimeId : null, sessionId: owner }),+ viewKey+ )const existing =target.kind === 'url'@@ -1312,13 +1360,14 @@ function dockedTabs(tabs: readonly PreviewTab[]): PreviewTab[] {return tabs.filter(tab => !popped.has(tab.id))}-/** An agent's `close_preview` for the session that ran it (`owner`, a stored- * id). With candidates it closes the first matching tab that session can- * see (live Browser page first, then source/url/label); without, it closes- * every tab that session owns. Never another session's tabs, never a pin- * the agent did not name. */-export function closeAgentPreview(owner: null | string, candidates: string[]): void {- const visible = tabsVisibleTo($previewTabs.get(), owner)+/** An agent's `close_preview` for the session that ran it (`owner`). With+ * candidates it closes the first matching tab that session can see (live+ * Browser page first, then source/url/label); without, it closes every tab+ * that session owns. Never another session's tabs (another runtime's pending+ * ones included), never another profile's pin, never a pin the agent did not+ * name. */+export function closeAgentPreview(owner: PreviewOwner, candidates: string[]): void {+ const visible = bucketTabsFor($previewTabs.get(), ownerIdentity(owner), viewKey)if (candidates.length > 0) {if (!closeBrowserMatchingLiveUrlIn(visible, candidates)) {diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex b3d656c9812..5cd0b63bda8 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -1925,7 +1925,14 @@ setSessionOwnerResolver(knownOwnerForSession)* showed one agent's previews in every agent's chat. `bot-row.tsx` documents* the same trap for the roster highlight and resolves it the same way. */function railScopeForActiveSession(): string {- const owner = knownOwnerForSession($activeSessionId.get() ?? undefined)+ return previewScopeForRuntime($activeSessionId.get() ?? undefined)+}++/** The preview-rail profile a runtime's chat belongs to — the bucket whose+ * pins its agent may use. Same resolution as the rail's own scope, so the+ * primary's runtime always lands on the bucket in view. */+export function previewScopeForRuntime(runtimeId: string | undefined): string {+ const owner = knownOwnerForSession(runtimeId)const profile = typeof owner === 'string' ? owner : owner?.profilereturn normalizeProfileKey(profile || $activeGatewayProfile.get())