The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope every agent preview tool to the requesting session
teknium1bc636d37a3d8
diff --git a/apps/desktop/src/app/chat/right-rail/preview-act.ts b/apps/desktop/src/app/chat/right-rail/preview-act.tsindex d4b84bd9028..6574e478bfb 100644--- a/apps/desktop/src/app/chat/right-rail/preview-act.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-act.ts@@ -750,17 +750,19 @@ async function driveScroll(return { ...after.result, acted: 'scrolled the page', success: true }}-/** Run one action against the ACTIVE preview tab's page. `kind` is a bare- * string: the verb arrives off the wire, and the history ones never reach- * the in-page engine. */+/** Run one action against the page of the ACTIVE tab among those `owner`+ * (the requesting session's stored id; omitted = the focused session) may+ * see. `kind` is a bare string: the verb arrives off the wire, and the+ * history ones never reach the in-page engine. */export async function actOnActivePreview(action: Omit<PreviewActAction, 'kind'> & { kind: string },- signal?: AbortSignal+ signal?: AbortSignal,+ owner?: null | string): Promise<PreviewActResult> {const nav = NAV_ACTIONS.find(verb => verb === action.kind)if (nav) {- const handle = activePreviewNav()+ const handle = activePreviewNav(owner)if (!handle) {return { error: NOTHING_OPEN, success: false }@@ -773,7 +775,7 @@ export async function actOnActivePreview(return { acted: nav, note: 'Page is loading — call elements to see what is on it.', success: true }}- const run = activePreviewScriptRunner()+ const run = activePreviewScriptRunner(owner)if (!run) {return { error: NOTHING_OPEN, success: false }@@ -802,7 +804,7 @@ export async function actOnActivePreview(return trip.kind === 'answered' ? trip.result : { acted: typed.kind, note: NAVIGATED, success: true }}- const input = activePreviewInput()+ const input = activePreviewInput(owner)if (input && DRIVEN.indexOf(typed.kind) !== -1) {return driveAction(run, input, typed, signal)diff --git a/apps/desktop/src/app/chat/right-rail/preview-active-tab.ts b/apps/desktop/src/app/chat/right-rail/preview-active-tab.tsnew file mode 100644index 00000000000..f6d38068c46--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-active-tab.ts@@ -0,0 +1,75 @@+/**+ * THE PREVIEW AN AGENT TOOL ACTS ON — one resolution shared by read_preview+ * (preview-reader.ts), drive_preview (the nav / input / script-runner+ * registries) and the preview tour, so a read and the action after it can+ * never land on different tabs.+ *+ * Callers pass the tabs the requesting session may see+ * (`previewTabsFor(owner)`): a background session's agent stays inside its own+ * tabs even while another session holds focus (#73890).+ */++import { findGroup } from '@/components/pane-shell/tree/model'+import { $activeTreeGroup, $hoveredTreeGroup, $layoutTree } from '@/components/pane-shell/tree/store'+import { $rightRailActiveTabId } from '@/store/layout'+import { type PreviewTab, previewTabsFor } from '@/store/preview'+import { explicitOpenBlocksZone, PREVIEW_TILE_PREFIX } from '@/store/preview-explicit'++function tabIdFromPreviewPane(paneId: string | undefined): null | string {+ if (!paneId?.startsWith(`${PREVIEW_TILE_PREFIX}:`)) {+ return null+ }++ return paneId.slice(PREVIEW_TILE_PREFIX.length + 1)+}++/** Active preview tab in a layout zone, if that tab is still open. */+function openTabInGroup(groupId: null | string, tabs: readonly PreviewTab[]): null | PreviewTab {+ const tree = $layoutTree.get()++ if (!tree || !groupId) {+ return null+ }++ const tabId = tabIdFromPreviewPane(findGroup(tree, groupId)?.active)++ if (!tabId) {+ return null+ }++ return tabs.find(tab => tab.id === tabId) ?? null+}++/**+ * The preview the user is looking at: hovered zone, else focused zone, else+ * the store. A focused zone that is still the pre-open zone does not override+ * an explicit open living in a different group — that is follow()'s clobber,+ * not a look.+ */+export function resolveActivePreviewTab(tabs: readonly PreviewTab[] = previewTabsFor()): null | PreviewTab {+ if (tabs.length === 0) {+ return null+ }++ const hovered = openTabInGroup($hoveredTreeGroup.get(), tabs)++ if (hovered) {+ return hovered+ }++ const focusedId = $activeTreeGroup.get()+ const focused = openTabInGroup(focusedId, tabs)+ const openIds = tabs.map(tab => tab.id)++ if (focused && !explicitOpenBlocksZone(focusedId, openIds)) {+ return focused+ }++ return tabs.find(tab => tab.id === $rightRailActiveTabId.get()) ?? tabs[0] ?? null+}++/** The active preview among the tabs `owner` (a stored id; null = a session+ * with none yet; omitted = the focused session) may see. */+export function activePreviewTabFor(owner?: null | string): null | PreviewTab {+ return resolveActivePreviewTab(previewTabsFor(owner))+}diff --git a/apps/desktop/src/app/chat/right-rail/preview-input.ts b/apps/desktop/src/app/chat/right-rail/preview-input.tsindex f7c023b7c98..d487b9fc59d 100644--- a/apps/desktop/src/app/chat/right-rail/preview-input.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-input.ts@@ -19,8 +19,7 @@* must be scaled by the guest's zoom factor on the way back out (#116281).*/-import { $rightRailActiveTabId } from '@/store/layout'-import { previewTabsFor } from '@/store/preview'+import { activePreviewTabFor } from './preview-active-tab'/** The subset of Electron's input events the agent needs to drive a page. */export type PreviewInputEvent =@@ -58,11 +57,11 @@ export function registerPreviewInput(tabId: string, handle: PreviewInputHandle):}}-/** The ACTIVE preview tab's input channel. Null = nothing real to drive, and- * the caller falls back to synthesizing events inside the page. */-export function activePreviewInput(): PreviewInputHandle | null {- const tabs = previewTabsFor()- const tab = tabs.find(t => t.id === $rightRailActiveTabId.get()) ?? tabs[0]+/** The ACTIVE preview tab's input channel among those `owner` (omitted = the+ * focused session) may see. Null = nothing real to drive, and the caller+ * falls back to synthesizing events inside the page. */+export function activePreviewInput(owner?: null | string): PreviewInputHandle | null {+ const tab = activePreviewTabFor(owner)return (tab && handles.get(tab.id)) || null}diff --git a/apps/desktop/src/app/chat/right-rail/preview-mind.ts b/apps/desktop/src/app/chat/right-rail/preview-mind.tsindex 3f7a1856c47..9573d605557 100644--- a/apps/desktop/src/app/chat/right-rail/preview-mind.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-mind.ts@@ -11,7 +11,7 @@* to poke the overlay the last action left behind. See preview-nudge.ts.*/-import { $busy } from '@/store/session'+import { $busy, $selectedStoredSessionId } from '@/store/session'import { nudgeOverlay } from './preview-nudge'@@ -25,5 +25,7 @@ $busy.subscribe(busy => {}running = busy- nudgeOverlay(busy ? 'think' : 'rest')+ // $busy is the primary's turn, so the pulse goes to the primary's page,+ // not whichever session's tab holds focus.+ nudgeOverlay(busy ? 'think' : 'rest', $selectedStoredSessionId.get())})diff --git a/apps/desktop/src/app/chat/right-rail/preview-nav.ts b/apps/desktop/src/app/chat/right-rail/preview-nav.tsindex 6e455fded0c..6960b58d465 100644--- a/apps/desktop/src/app/chat/right-rail/preview-nav.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-nav.ts@@ -10,8 +10,8 @@*/import { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'-import { $rightRailActiveTabId } from '@/store/layout'-import { previewTabsFor } from '@/store/preview'++import { activePreviewTabFor } from './preview-active-tab'/** Marks a live browser pane so a gesture can find the one holding focus. */export const PREVIEW_BROWSER_ATTR = 'data-preview-browser'@@ -35,11 +35,12 @@ export function registerPreviewNav(tabId: string, handle: PreviewNavHandle): ()}}-/** The ACTIVE preview tab's commands, for callers with no focus to key off —- * the agent's drive_preview, which runs while focus is in the composer. */-export function activePreviewNav(): PreviewNavHandle | null {- const tabs = previewTabsFor()- const tab = tabs.find(t => t.id === $rightRailActiveTabId.get()) ?? tabs[0]+/** The ACTIVE preview tab's commands among those `owner` (the requesting+ * session's stored id; omitted = the focused session) may see, for callers+ * with no focus to key off — the agent's drive_preview, which runs while+ * focus is in the composer. */+export function activePreviewNav(owner?: null | string): PreviewNavHandle | null {+ const tab = activePreviewTabFor(owner)return (tab && handles.get(tab.id)) || null}diff --git a/apps/desktop/src/app/chat/right-rail/preview-nudge.ts b/apps/desktop/src/app/chat/right-rail/preview-nudge.tsindex 8a8f4199878..20786fa3de4 100644--- a/apps/desktop/src/app/chat/right-rail/preview-nudge.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-nudge.ts@@ -18,9 +18,10 @@ import type { WatchStage } from '@/lib/preview-act/watch-in-page'import { activePreviewScriptRunner } from './preview-script-runner'-/** Run one stage against the active pane's overlay, if it has one. */-export function nudgeOverlay(stage: WatchStage): void {- const run = activePreviewScriptRunner()+/** Run one stage against the overlay of the active pane `owner` (omitted =+ * the focused session) sees, if it has one. */+export function nudgeOverlay(stage: WatchStage, owner?: null | string): void {+ const run = activePreviewScriptRunner(owner)if (!run) {returndiff --git a/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.test.ts b/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.test.tsindex a81b6e1faf7..9a9fbf75a4c 100644--- a/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.test.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.test.ts@@ -171,6 +171,43 @@ describe('preview pop-out bridge', () => {}})+ it('answers only for the session whose tab the pop-out shows (#73890)', async () => {+ isBrowserWindow.mockReturnValue(true)+ actOnActivePreview.mockResolvedValue({ acted: 'click', success: true })+ window.history.replaceState(null, '', '/?win=browser&tab=url:browser-a')+ const { $previewTabs } = await import('@/store/preview')+ const url = (u: string) => ({ kind: 'url' as const, label: u, source: u, url: u })++ $previewTabs.set([+ { id: 'url:browser-a', pinned: false, sessionId: 'sess-a', target: url('https://a.example') },+ { id: 'url:browser-b', pinned: false, sessionId: 'sess-b', target: url('https://b.example') }+ ])++ const { installPopoutPreviewResponder, requestPopoutPreviewAct } = await import('./preview-popout-bridge')+ const stop = installPopoutPreviewResponder()+ vi.useFakeTimers()++ try {+ // sess-b's agent: the pop-out shows sess-a's tab, so it stays silent.+ const refused = requestPopoutPreviewAct({ kind: 'click', ref: 'btn-1' }, 'sess-b')+ await vi.advanceTimersByTimeAsync(20_100)++ expect(await refused).toBeNull()+ expect(actOnActivePreview).not.toHaveBeenCalled()++ // sess-a's agent is answered.+ expect(await requestPopoutPreviewAct({ kind: 'click', ref: 'btn-1' }, 'sess-a')).toEqual({+ acted: 'click',+ success: true+ })+ } finally {+ vi.useRealTimers()+ stop()+ $previewTabs.set([])+ window.history.replaceState(null, '', '/')+ }+ })+it('installs no responder outside the browser pop-out window', async () => {isBrowserWindow.mockReturnValue(false)diff --git a/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.ts b/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.tsindex 2d426c2105b..22e81f3e9d9 100644--- a/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-popout-bridge.ts@@ -16,7 +16,8 @@*/import type { PreviewActAction, PreviewActResult } from '@/lib/preview-act/act-in-page'-import { isBrowserWindow } from '@/store/windows'+import { previewTabIdsVisibleTo } from '@/store/preview'+import { isBrowserWindow, windowBrowserTabId } from '@/store/windows'import { actOnActivePreview } from './preview-act'import { activePreviewNav } from './preview-nav'@@ -30,8 +31,12 @@ const READ_TIMEOUT_MS = 8_000type ActPayload = Omit<PreviewActAction, 'kind'> & { kind: string }-type BridgeRequest =- { id: string; kind: 'act'; payload: ActPayload } | { id: string; kind: 'read'; payload: PreviewReadOptions }+/** `tabIds`: the tabs the requesting session may see, resolved in the chat+ * window (it alone knows compression rotations and session tiles). A pop-out+ * answers only when the tab it shows is among them; absent = unscoped. */+type BridgeRequest = { id: string; tabIds?: string[] } & (+ { kind: 'act'; payload: ActPayload } | { kind: 'read'; payload: PreviewReadOptions }+)type BridgeResponse =| { id: string; kind: 'act'; result: PreviewActResult }@@ -82,11 +87,16 @@ function getBus(): RelayBus | null {return cachedBus}-/** True when this renderer has a live webview (or nav handle) for the active tab. */-export function hasLivePreviewSurface(): boolean {- return Boolean(activePreviewScriptRunner() || activePreviewNav())+/** True when this renderer has a live webview (or nav handle) for the active+ * tab among those `owner` (omitted = the focused session) may see. */+export function hasLivePreviewSurface(owner?: null | string): boolean {+ return Boolean(activePreviewScriptRunner(owner) || activePreviewNav(owner))}+/** Scope a request to `owner`'s tabs (undefined = an unscoped request). */+const scopeFor = (owner: null | string | undefined): { tabIds?: string[] } =>+ owner === undefined ? {} : { tabIds: previewTabIdsVisibleTo(owner) }+function nextId(prefix: string): string {seq += 1@@ -145,16 +155,21 @@ function askPopout<T>(})}-/** Ask the browser pop-out to run drive_preview. Null when no pop-out answers. */-export function requestPopoutPreviewAct(payload: ActPayload): Promise<PreviewActResult | null> {- return askPopout({ id: nextId('act'), kind: 'act', payload }, ACT_TIMEOUT_MS, response =>+/** Ask the browser pop-out to run drive_preview for `owner` (the requesting+ * session's stored id). Null when no pop-out showing one of its tabs answers. */+export function requestPopoutPreviewAct(payload: ActPayload, owner?: null | string): Promise<PreviewActResult | null> {+ return askPopout({ id: nextId('act'), kind: 'act', payload, ...scopeFor(owner) }, ACT_TIMEOUT_MS, response =>response.kind === 'act' ? response.result : undefined)}-/** Ask the browser pop-out to run read_preview. Null when no pop-out answers. */-export function requestPopoutPreviewRead(payload: PreviewReadOptions = {}): Promise<PreviewReadResult | null> {- return askPopout({ id: nextId('read'), kind: 'read', payload }, READ_TIMEOUT_MS, response =>+/** Ask the browser pop-out to run read_preview for `owner`. Null when no+ * pop-out showing one of its tabs answers. */+export function requestPopoutPreviewRead(+ payload: PreviewReadOptions = {},+ owner?: null | string+): Promise<PreviewReadResult | null> {+ return askPopout({ id: nextId('read'), kind: 'read', payload, ...scopeFor(owner) }, READ_TIMEOUT_MS, response =>response.kind === 'read' ? response.result : undefined)}@@ -189,6 +204,12 @@ export function installPopoutPreviewResponder(): () => void {return}+ // Another session's request: stay silent (an answer — even an error —+ // would win the race against a pop-out that does show that session's tab).+ if (Array.isArray(request.tabIds) && !request.tabIds.includes(windowBrowserTabId() ?? '')) {+ return+ }+const id = request.idvoid (async () => {diff --git a/apps/desktop/src/app/chat/right-rail/preview-reader.test.ts b/apps/desktop/src/app/chat/right-rail/preview-reader.test.tsindex 042541fcc58..4dc2ddd6ce9 100644--- a/apps/desktop/src/app/chat/right-rail/preview-reader.test.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-reader.test.ts@@ -8,14 +8,11 @@ import { $selectedStoredSessionId } from '@/store/session'import { watchPreviewTiles } from '../preview-tile'+import { resolveActivePreviewTab } from './preview-active-tab'import { activePreviewInput, registerPreviewInput } from './preview-input'import { activePreviewNav, registerPreviewNav } from './preview-nav'-import {- PREVIEW_READ_MAX_CHARS,- readActivePreview,- registerPreviewPageReader,- resolveActivePreviewTab-} from './preview-reader'+import { PREVIEW_READ_MAX_CHARS, readActivePreview, registerPreviewPageReader } from './preview-reader'+import { activePreviewScriptRunner, registerPreviewScriptRunner } from './preview-script-runner'function urlTarget(url: string): PreviewTarget {return { kind: 'url', label: 'Browser', source: url, url }@@ -221,8 +218,12 @@ describe('agent preview reads stay inside the session (#73890)', () => {$selectedStoredSessionId.set('sess-a')openPreview(fileTarget('/work/secret-a.txt'))const hidden = $previewTabs.get()[0]!.id- const unbindNav = registerPreviewNav(hidden, { back: () => {}, forward: () => {}, reload: () => {} })- const unbindInput = registerPreviewInput(hidden, { focus: () => {}, send: () => {} })+ const navA = { back: () => {}, forward: () => {}, reload: () => {} }+ const inputA = { focus: () => {}, send: () => {} }+ const runA = async () => 'a'+ const unbindNav = registerPreviewNav(hidden, navA)+ const unbindInput = registerPreviewInput(hidden, inputA)+ const unbindRun = registerPreviewScriptRunner(hidden, runA)try {$selectedStoredSessionId.set('sess-b')@@ -234,14 +235,23 @@ describe('agent preview reads stay inside the session (#73890)', () => {expect(resolveActivePreviewTab()?.target.path).toMatch(/^\/work\/b/)expect(activePreviewNav()).toBeNull()expect(activePreviewInput()).toBeNull()+ expect(activePreviewScriptRunner()).toBeNull()const read = await readActivePreview()expect(read?.path).toMatch(/^\/work\/b/)expect(JSON.stringify(read)).not.toContain('secret-a')++ // sess-a's own agent, while sess-b holds focus, drives sess-a's page.+ expect(activePreviewNav('sess-a')).toBe(navA)+ expect(activePreviewInput('sess-a')).toBe(inputA)+ expect(activePreviewScriptRunner('sess-a')).toBe(runA)+ // A requester with no resolved session sees no session's tabs.+ expect(activePreviewScriptRunner(null)).toBeNull()} finally {unbindNav()unbindInput()+ unbindRun()}})})diff --git a/apps/desktop/src/app/chat/right-rail/preview-reader.ts b/apps/desktop/src/app/chat/right-rail/preview-reader.tsindex f47ff0aedfe..76c12b7bdc2 100644--- a/apps/desktop/src/app/chat/right-rail/preview-reader.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-reader.ts@@ -13,12 +13,9 @@* directly (read_file / the conversation's artifact).*/-import { findGroup } from '@/components/pane-shell/tree/model'-import { $activeTreeGroup, $hoveredTreeGroup, $layoutTree } from '@/components/pane-shell/tree/store'-import { $rightRailActiveTabId } from '@/store/layout'import { type PreviewTab, previewTabsFor } from '@/store/preview'-import { explicitOpenBlocksZone, PREVIEW_TILE_PREFIX } from '@/store/preview-explicit'+import { resolveActivePreviewTab } from './preview-active-tab'import { nudgeOverlay } from './preview-nudge'export interface PreviewReadOptions {@@ -90,59 +87,6 @@ function windowText(return { ...base, end: to, start: from, text: text.slice(from, to), total_chars: total }}-function tabIdFromPreviewPane(paneId: string | undefined): null | string {- if (!paneId?.startsWith(`${PREVIEW_TILE_PREFIX}:`)) {- return null- }-- return paneId.slice(PREVIEW_TILE_PREFIX.length + 1)-}--/** Active preview tab in a layout zone, if that tab is still open. */-function openTabInGroup(groupId: null | string, tabs: PreviewTab[]): null | PreviewTab {- const tree = $layoutTree.get()-- if (!tree || !groupId) {- return null- }-- const tabId = tabIdFromPreviewPane(findGroup(tree, groupId)?.active)-- if (!tabId) {- return null- }-- return tabs.find(tab => tab.id === tabId) ?? null-}--/**- * The preview the user is looking at: hovered zone, else focused zone, else- * the store. A focused zone that is still the pre-open zone does not override- * an explicit open living in a different group — that is follow()'s clobber,- * not a look.- */-export function resolveActivePreviewTab(tabs: PreviewTab[] = previewTabsFor()): null | PreviewTab {- if (tabs.length === 0) {- return null- }-- const hovered = openTabInGroup($hoveredTreeGroup.get(), tabs)-- if (hovered) {- return hovered- }-- const focusedId = $activeTreeGroup.get()- const focused = openTabInGroup(focusedId, tabs)- const openIds = tabs.map(tab => tab.id)-- if (focused && !explicitOpenBlocksZone(focusedId, openIds)) {- return focused- }-- return tabs.find(tab => tab.id === $rightRailActiveTabId.get()) ?? tabs[0] ?? null-}-function tabSummary(tab: PreviewTab): PreviewReadTabSummary {return { id: tab.id, kind: tab.target.kind, label: tab.target.label, url: tab.target.url }}@@ -193,7 +137,7 @@ export async function readActivePreview(// side of it — so a run of reads used to leave the pane dark for the// twenty seconds it took to page through a document, immediately after// the one moment that showed anything.- nudgeOverlay('read')+ nudgeOverlay('read', sessionId)return windowText({diff --git a/apps/desktop/src/app/chat/right-rail/preview-script-runner.ts b/apps/desktop/src/app/chat/right-rail/preview-script-runner.tsindex 69a0efa2a4e..503f57fecb8 100644--- a/apps/desktop/src/app/chat/right-rail/preview-script-runner.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-script-runner.ts@@ -4,14 +4,13 @@* registry.** A live browser pane registers its webview's `executeJavaScript` here, keyed- * by tab id; `activePreviewScriptRunner` resolves the ACTIVE tab from the- * store. Both guest-page features ride it — the tour tool (preview-tour.ts)+ * by tab id; `activePreviewScriptRunner` resolves the ACTIVE tab among the+ * requesting session's tabs. Both guest-page features ride it — the tour tool (preview-tour.ts)* and the interaction tool (preview-act.ts) — so their heavy payloads stay out* of the pane component's static import graph and only load when used.*/-import { $rightRailActiveTabId } from '@/store/layout'-import { $previewTabs } from '@/store/preview'+import { activePreviewTabFor } from './preview-active-tab'/** Runs JS source in the pane's guest page, resolving its completion value. */export type PreviewScriptRunner = (code: string) => Promise<unknown>@@ -29,10 +28,11 @@ export function registerPreviewScriptRunner(tabId: string, runner: PreviewScript}}-/** The ACTIVE preview tab's script runner. Null = no live page behind it. */-export function activePreviewScriptRunner(): PreviewScriptRunner | null {- const tabs = $previewTabs.get()- const tab = tabs.find(t => t.id === $rightRailActiveTabId.get()) ?? tabs[0]+/** The script runner of the ACTIVE tab among those `owner` (the requesting+ * session's stored id; omitted = the focused session) may see. Null = no live+ * page behind it. */+export function activePreviewScriptRunner(owner?: null | string): PreviewScriptRunner | null {+ const tab = activePreviewTabFor(owner)return (tab && runners.get(tab.id)) || null}diff --git a/apps/desktop/src/app/chat/right-rail/preview-tour.ts b/apps/desktop/src/app/chat/right-rail/preview-tour.tsindex a033a7c1f85..d7961e28aaa 100644--- a/apps/desktop/src/app/chat/right-rail/preview-tour.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-tour.ts@@ -49,9 +49,10 @@ function buildTourScript(action: TourAction): string {})()`}-/** Run one tour action in the ACTIVE preview tab's page. */-export async function runPreviewTour(action: TourAction): Promise<TourResult> {- const run = activePreviewScriptRunner()+/** Run one tour action in the page of the ACTIVE tab among those `owner`+ * (the requesting session's stored id; omitted = the focused session) sees. */+export async function runPreviewTour(action: TourAction, owner?: null | string): Promise<TourResult> {+ const run = activePreviewScriptRunner(owner)if (!run) {return { error: 'No live page is open in the preview pane — open one first.', success: false }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 f4b03917fb6..74157eb48c9 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,6 +1,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { registerPreviewNav } from '@/app/chat/right-rail/preview-nav'+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 { hasOpenServerRequest, resetServerRequestsForTests } from '@/store/server-requests'import { setActiveSessionId, setSelectedStoredSessionId, setSessions } from '@/store/session'import { $sessionStates, $sessionTiles } from '@/store/session-states'@@ -378,6 +383,90 @@ describe('preview pop-out forwarding', () => {})})+describe('preview requests act for the session that asked (#73890)', () => {+ beforeEach(() => {+ hasLivePreviewSurface.mockReturnValue(true)+ closeRightRail()+ setActiveSessionId('rt-a')+ setSelectedStoredSessionId('stored-a')+ $sessionTiles.set([{ dir: 'right', runtimeId: 'rt-b', storedSessionId: 'stored-b' } as never])+ })++ afterEach(() => {+ noteActiveTreeGroup(null)+ $layoutTree.set(null)+ $sessionTiles.set([])+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ closeRightRail()+ hasLivePreviewSurface.mockReturnValue(false)+ })++ // Tile B holds focus while the primary session A's agent is the one asking.+ const focusTileB = () => {+ $layoutTree.set(group(['session-tile:stored-b'], { active: 'session-tile:stored-b', id: 'grp-b' }))+ noteActiveTreeGroup('grp-b')+ }++ it("drives the requesting session's page, not the focused tile's", async () => {+ openPreview({ kind: 'url', label: 'a', source: 'https://a.example', url: 'https://a.example' }, 'stored-a')+ openPreview({ kind: 'url', label: 'b', source: 'https://b.example', url: 'https://b.example' }, 'stored-b')+ const [a, b] = $previewTabs.get()+ const backA = vi.fn()+ const backB = vi.fn()++ const unbind = [+ registerPreviewNav(a!.id, { back: backA, forward: () => {}, reload: () => {} }),+ registerPreviewNav(b!.id, { back: backB, forward: () => {}, reload: () => {} })+ ]++ focusTileB()++ try {+ const { respond } = deliver('preview.act', { action: 'back', session_id: 'rt-a' }, 'rt-a')++ await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1), { timeout: 30_000 })+ expect(JSON.parse(respond.mock.calls[0][0].value)).toMatchObject({ acted: 'back', success: true })+ expect(backA).toHaveBeenCalledTimes(1)+ expect(backB).not.toHaveBeenCalled()+ } finally {+ unbind.forEach(stop => stop())+ }+ })++ it("runs a preview tour against the requesting session's tabs", async () => {+ focusTileB()+ vi.mocked(runTour).mockClear()++ 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', 'stored-a')+ })++ 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')+ setSelectedStoredSessionId(null)+ openPreview(+ {+ kind: 'file',+ label: 'b',+ path: '/work/b-secret.txt',+ source: '/work/b-secret.txt',+ url: 'file:///work/b-secret.txt'+ },+ 'stored-b'+ )+ focusTileB()++ const { respond } = deliver('preview.read', { session_id: 'rt-new' }, 'rt-new')++ await vi.waitFor(() => expect(respond).toHaveBeenCalledTimes(1), { timeout: 30_000 })+ expect(respond.mock.calls[0][0].value).toBe('')+ })+})+describe('tour request routing', () => {afterEach(() => {$toursEnabled.set(true)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 5e5656907a1..d1568550f0a 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@@ -52,6 +52,14 @@ const loadPreviewEngine = () => {}const str = (v: unknown): string => (typeof v === 'string' ? v : '')++/** The stored id whose preview tabs a scoped agent request may see. An id that+ * does not resolve yet (a runtime before its stored id binds) is null — the+ * ownerless view — never the focused session's tabs. Only an unscoped+ * request (no id) falls through to the focused session (undefined). */+const previewOwnerFor = (sessionId: string): null | string | undefined =>+ sessionId ? storedSessionIdForRuntimeId(sessionId) : undefined+const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : undefined)/** Answer a string-valued request with a JSON-encoded result ('' = nothing / unavailable). */@@ -489,12 +497,12 @@ const previewRead: Handler = ({ request, sessionId }) => {// first; a null (no pop-out answered) falls back to the legacy local read.// A local read sees only the tabs the requesting session can see.const opts = { count: num(request.params.count), start: num(request.params.start) }- const owner = (sessionId && storedSessionIdForRuntimeId(sessionId)) || undefined+ const owner = previewOwnerFor(sessionId)void (async () => {- const result = hasLivePreviewSurface()+ const result = hasLivePreviewSurface(owner)? await readActivePreview(opts, owner)- : ((await requestPopoutPreviewRead(opts)) ?? (await readActivePreview(opts, owner)))+ : ((await requestPopoutPreviewRead(opts, owner)) ?? (await readActivePreview(opts, owner)))answerValue(request, result)})()@@ -517,6 +525,10 @@ const previewAct: Handler = ({ deps, isActiveSession, request, sessionId }) => {return}+ // The agent drives ITS session's page: with a tile focused, the primary's+ // agent must not reach into the tile's tabs (#73890).+ const owner = previewOwnerFor(sessionId)+// The keystroke loop has to be able to stop when this request is withdrawn// (tool timeout or turn interrupt). The local interrupted flag can flip// before request.cancel arrives; poll it so Stop cuts the loop off too.@@ -550,8 +562,8 @@ const previewAct: Handler = ({ deps, isActiveSession, request, sessionId }) => {// answer with the pop-out's result. No pop-out answering (null) falls// through to the local engine, which keeps the legacy NOTHING_OPEN// error for a genuinely closed pane.- if (!hasLivePreviewSurface()) {- const remote = await requestPopoutPreviewAct(action)+ if (!hasLivePreviewSurface(owner)) {+ const remote = await requestPopoutPreviewAct(action, owner)if (remote) {answerValue(request, remote)@@ -561,7 +573,7 @@ const previewAct: Handler = ({ deps, isActiveSession, request, sessionId }) => {}const run = await loadPreviewEngine()- const result = await run(action, signal)+ const result = await run(action, signal, owner)answerValue(request, result)} catch (error) {@@ -588,7 +600,7 @@ const windowRead: Handler = ({ request }) => {)}-const tour: Handler = ({ isActiveSession, request }) => {+const tour: Handler = ({ isActiveSession, request, sessionId }) => {// tour tool: one guided-tour action via driver.js, app DOM or preview guest// page. Active session only, same window-ownership rule as preview.act// (WINDOW_OWNED_REQUESTS).@@ -620,7 +632,8 @@ const tour: Handler = ({ isActiveSession, request }) => {text: p.text as never,title: p.title as never},- p.surface === 'preview' ? 'preview' : 'app'+ p.surface === 'preview' ? 'preview' : 'app',+ previewOwnerFor(sessionId))).then(diff --git a/apps/desktop/src/app/session/hooks/use-preview-routing.ts b/apps/desktop/src/app/session/hooks/use-preview-routing.tsindex 22ef477e532..3d2858eafdc 100644--- a/apps/desktop/src/app/session/hooks/use-preview-routing.ts+++ b/apps/desktop/src/app/session/hooks/use-preview-routing.ts@@ -110,7 +110,9 @@ export function usePreviewRouting({ baseHandleGatewayEvent, currentCwd, requestGopenPreview(renderedHtmlTarget(trimmedLabel ? { ...reached, label: trimmedLabel } : reached),- previewOwnerForEvent(event.session_id)+ previewOwnerForEvent(event.session_id),+ // The runtime that ran the tool, should its stored id lag.+ event.session_id || undefined)})diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsxindex 93f5b847ded..cd64411c153 100644--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx@@ -260,6 +260,31 @@ describe('useSessionStateCache — stored-id rotation provenance', () => {}})+ it("hands a runtime's pre-stored-id preview tabs over when its stored id binds, even on a no-op update (#73890)", async () => {+ const { $previewTabs, closeRightRail, openPreview } = await import('@/store/preview')+ let cache!: Cache++ setActiveSessionId('runtime-B')+ setSelectedStoredSessionId(null)+ render(<Harness activeSessionId="runtime-B" onReady={value => (cache = value)} selectedStoredSessionId={null} />)++ try {+ act(() => {+ cache.updateSessionState('runtime-B', state => state, null)+ })+ openPreview({ kind: 'url', label: 'Docs', source: 'https://docs.example', url: 'https://docs.example' }, null)+ expect($previewTabs.get().map(tab => tab.sessionId)).toEqual([undefined])++ act(() => {+ cache.updateSessionState('runtime-B', state => state, 'stored-B')+ })++ expect($previewTabs.get().map(tab => tab.sessionId)).toEqual(['stored-B'])+ } finally {+ closeRightRail()+ }+ })+it('rekeys the persisted owner profile when its runtime rotates while another profile is visible', () => {let cache!: Cacheconst profileA = 'rotation-profile-a-98622'diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts b/apps/desktop/src/app/session/hooks/use-session-state-cache.tsindex 60e47c59198..6565f84bad8 100644--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts@@ -7,7 +7,7 @@ import { preserveLocalAssistantErrors } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { migrateInFlightTurnJournal, persistInFlightTurnState } from '@/lib/inflight-turn-journal'import { setMutableRef } from '@/lib/mutable-ref'-import { rekeyPreviewTabsSession } from '@/store/preview'+import { adoptPendingRuntimeTabs, rekeyPreviewTabsSession } from '@/store/preview'import {$activeSessionId,$messages,@@ -229,6 +229,12 @@ export function useSessionStateCache({if (storedSessionId) {runtimeIdByStoredSessionIdRef.current.set(storedSessionId, sessionId)++ // The runtime's stored id binding (null → id). Mirrors+ // handleTransition's hand-over, which a no-op updater skips.+ if (!existing.storedSessionId) {+ adoptPendingRuntimeTabs(sessionId, storedSessionId)+ }}sessionStateCache.set(sessionId, updated)diff --git a/apps/desktop/src/lib/tour/run-tour.ts b/apps/desktop/src/lib/tour/run-tour.tsindex 88df01d9ab4..d436c3ad557 100644--- a/apps/desktop/src/lib/tour/run-tour.ts+++ b/apps/desktop/src/lib/tour/run-tour.ts@@ -67,10 +67,16 @@ const appHolder: TourHolder = {}/** Run one tour action on `surface`. Never throws — failures come back as* `{success: false, error}` so a caller (or the agent) can recover. */-export async function runTour(action: TourAction, surface: TourSurface = 'app'): Promise<TourResult> {+export async function runTour(+ action: TourAction,+ surface: TourSurface = 'app',+ /** The requesting session's stored id, for surface='preview': the tour runs+ * in that session's page (omitted = the focused session's). */+ owner?: null | string+): Promise<TourResult> {try {if (surface === 'preview') {- return await runPreviewTour(action)+ return await runPreviewTour(action, owner)}const result = runTourEngine(driverFactory, appHolder, action, collectTourTargets, document, TOUR_STYLE, APP_HOST)diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.tsindex b786f7436d7..c52d864adb6 100644--- a/apps/desktop/src/store/preview.test.ts+++ b/apps/desktop/src/store/preview.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { group } from '@/components/pane-shell/tree/model'import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'+import { createClientSessionState } from '@/lib/chat-runtime'import { $rightRailActiveTabId, selectRightRailTab } from './layout'import {@@ -35,6 +36,7 @@ import {setPreviewTabPinned} from './preview'import { $activeSessionId, $selectedStoredSessionId } from './session'+import { publishSessionState } from './session-states'function fileTarget(source: string): PreviewTarget {return { kind: 'file', label: source, path: source, previewKind: 'html', source, url: `file://${source}` }@@ -514,25 +516,43 @@ describe('preview session scoping (#73890)', () => {it('hands an agent tab opened before the stored id to that runtime only', () => {// A live chat whose stored id lags: the agent opens a preview right away.$activeSessionId.set('runtime-r')+ publishSessionState('runtime-r', createClientSessionState(null))openPreview(fileTarget('/work/agent.html'), null)expect($previewTabs.get()[0]?.sessionId).toBeUndefined()try {- // Another session taking the screen (its own runtime) does not take it.- $activeSessionId.set('runtime-x')+ // Resuming another session selects it while runtime-r is still the+ // active runtime: that selection is not runtime-r's stored id arriving.$selectedStoredSessionId.set('stored-x')+ $activeSessionId.set('runtime-x')+ expect($previewTabs.get()[0]?.sessionId).toBeUndefined()+ // Nor does the next draft's first send take a tab another runtime opened.+ adoptDraftPreviewTabs('stored-draft')expect($previewTabs.get()[0]?.sessionId).toBeUndefined()- $selectedStoredSessionId.set(null)- $activeSessionId.set('runtime-r')- // The opening runtime's stored id arriving does.- $selectedStoredSessionId.set('stored-r')+ // runtime-r's own stored id binding does.+ publishSessionState('runtime-r', createClientSessionState('stored-r'))expect($previewTabs.get()[0]?.sessionId).toBe('stored-r')} finally {$activeSessionId.set(null)}})+ it("records the agent event's runtime, not whichever runtime is active", () => {+ $activeSessionId.set('runtime-w')++ try {+ openPreview(fileTarget('/work/from-r.html'), null, 'runtime-q')+ publishSessionState('runtime-w', createClientSessionState('stored-w'))+ expect($previewTabs.get()[0]?.sessionId).toBeUndefined()++ publishSessionState('runtime-q', createClientSessionState('stored-q'))+ expect($previewTabs.get()[0]?.sessionId).toBe('stored-q')+ } finally {+ $activeSessionId.set(null)+ }+ })+it('owns a strip "+" Browser by the focused session, never adopting it elsewhere', () => {$selectedStoredSessionId.set('sess-x')newBrowserTab()@@ -659,7 +679,7 @@ describe('preview session scoping (#73890)', () => {expect($previewTabs.get()).toHaveLength(0)})- it('agent close without a url writes the tab list once and fronts what the session still sees', () => {+ it('agent close without a url fronts what the session still sees', () => {$selectedStoredSessionId.set('sess-a')openPreview(fileTarget('/work/pinned.html'))const pinned = $previewTabs.get()[0]!.id@@ -669,16 +689,8 @@ describe('preview session scoping (#73890)', () => {openPreview(fileTarget(`/work/a${i}.html`))}- let writes = 0- const unbind = $previewTabs.listen(() => writes++)-- try {- closeAgentPreview('sess-a', [])- } finally {- unbind()- }+ closeAgentPreview('sess-a', [])- expect(writes).toBe(1)expect(paths($previewTabs.get())).toEqual(['/work/pinned.html'])expect($rightRailActiveTabId.get()).toBe(pinned)})diff --git a/apps/desktop/src/store/preview.ts b/apps/desktop/src/store/preview.tsindex 8a7ac71a680..7750912b9aa 100644--- a/apps/desktop/src/store/preview.ts+++ b/apps/desktop/src/store/preview.ts@@ -13,9 +13,9 @@ import { recordFeatureUse } from './desktop-metrics'import { $rightRailActiveTabId, type RightRailTabId, selectRightRailTab } from './layout'import { clearExplicitPreviewOpen, noteExplicitPreviewOpen, PREVIEW_TILE_PREFIX } from './preview-explicit'import { normalizeProfileKey } from './profile'-import { $activeSessionId, $selectedStoredSessionId } from './session'-import { $focusedStoredSessionId } from './session-focus'-import { canOpenBrowserWindow, isBrowserWindow, openBrowserInNewWindow } from './windows'+import { $activeSessionId } from './session'+import { $focusedSessionIsTile, $focusedStoredSessionId } from './session-focus'+import { canOpenBrowserWindow, isBrowserWindow, openBrowserInNewWindow, windowBrowserTabId } from './windows'/*** PREVIEW RAIL — one list of tabs, one way in.@@ -256,6 +256,13 @@ export const $previewTabs = atom<PreviewTab[]>([])// its `default` bucket the same way.let adoptingStoredTabs = true+// An ownerless tab opened while a live chat was on screen whose stored id had+// not arrived yet (the agent's open_preview right after the first send): the+// runtime it was opened under. Memory-only — runtime ids do not survive a+// relaunch. A draft opened before any send has no runtime, so its tabs carry+// no stamp and only adoptDraftPreviewTabs can take them.+const $pendingRuntimeByTab = atom<ReadonlyMap<string, string>>(new Map())+$previewTabs.subscribe(tabs => {if (adoptingStoredTabs) {return@@ -264,6 +271,7 @@ $previewTabs.subscribe(tabs => {// `subscribe` hands a readonly view; the bucket is a mutable store of its own.tabsByProfile[viewKey] = [...tabs]persistTabs()+ forgetGonePendingTabs()})// Seed the view with this renderer's own bucket. Without it the primary@@ -313,6 +321,8 @@ export function dropPreviewTabsForProfile(profile: string) {if (key === viewKey) {$previewTabs.set([])+ } else {+ forgetGonePendingTabs()}}@@ -367,9 +377,9 @@ const $rotatedSessionIds = atom<ReadonlyMap<string, string>>(new Map())function latestSessionId(sessionId: null | string | undefined, rotated: ReadonlyMap<string, string>): null | string {let id = sessionId ?? null- // Acyclic by construction: `rekeyPreviewTabsSession` only links one tip to- // a different tip.- while (id && rotated.has(id)) {+ // Acyclic by construction (`rekeyPreviewTabsSession` only links one tip to+ // a different tip), so no chain is longer than the map.+ for (let hops = 0; id && rotated.has(id) && hops < rotated.size; hops++) {id = rotated.get(id)!}@@ -395,17 +405,44 @@ function tabsVisibleTo(tabs: readonly PreviewTab[], sessionId: null | string): P/** The tabs an agent tool acting for `sessionId` (default: the focused* session) may read or drive: never another session's hidden tab. A- * popped-out Browser renderer holds only the tab it shows, so there every- * tab is its own. */+ * 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(sessionId: null | string = $focusedStoredSessionId.get()): PreviewTab[] {- return isBrowserWindow() ? $previewTabs.get() : tabsVisibleTo($previewTabs.get(), sessionId)+ if (isBrowserWindow()) {+ const own = windowBrowserTabId()++ return $previewTabs.get().filter(tab => tab.id === own)+ }++ return tabsVisibleTo($previewTabs.get(), sessionId)+}++/** Ids of the tabs `sessionId`'s drawer holds, for scoping a request to a+ * popped-out Browser window. */+export function previewTabIdsVisibleTo(sessionId: null | string): string[] {+ return tabsVisibleTo($previewTabs.get(), sessionId).map(tab => tab.id)}/** Tabs the FOCUSED session sees. The layout-tree mirror renders only these,- * so a session switch swaps the drawer; hidden tabs stay in `$previewTabs`. */+ * so a session switch swaps the drawer; hidden tabs stay in `$previewTabs`.+ * The primary also shows the tabs its runtime opened before its stored id+ * arrived: the selection can name that id a beat before the runtime binds it,+ * and a Browser hidden in that gap would lose its page. */export const $visiblePreviewTabs = computed(- [$previewTabs, $focusedStoredSessionId, $rotatedSessionIds],- (tabs, sessionId, rotated) => tabs.filter(tab => tabVisibleTo(tab, sessionId, rotated))+ [+ $previewTabs,+ $focusedStoredSessionId,+ $rotatedSessionIds,+ $pendingRuntimeByTab,+ $activeSessionId,+ $focusedSessionIsTile+ ],+ (tabs, sessionId, rotated, pending, activeRuntime, focusedIsTile) =>+ tabs.filter(+ tab =>+ tabVisibleTo(tab, sessionId, rotated) ||+ (!focusedIsTile && tab.sessionId == null && activeRuntime !== null && pending.get(tab.id) === activeRuntime)+ ))// The tab each session last had in front, so switching back to a session@@ -501,47 +538,93 @@ export function preferredVisibleTabId(): RightRailTabId | null {* tabs follow it into the conversation. Never on a focus change: clicking an* existing session or a side tile must leave the draft's tabs in the draft. */export function adoptDraftPreviewTabs(storedSessionId: string): void {+ const pending = $pendingRuntimeByTab.get()+ // A tab a live runtime opened before its stored id is that runtime's, not+ // the draft's.+ const draftOwned = (tab: PreviewTab) => tab.sessionId == null && !tab.pinned && !pending.has(tab.id)const tabs = $previewTabs.get()- if (tabs.some(tab => tab.sessionId == null && !tab.pinned)) {- $previewTabs.set(- tabs.map(tab => (tab.sessionId == null && !tab.pinned ? { ...tab, sessionId: storedSessionId } : tab))- )+ if (tabs.some(draftOwned)) {+ $previewTabs.set(tabs.map(tab => (draftOwned(tab) ? { ...tab, sessionId: storedSessionId } : tab)))}}-// An ownerless tab opened while a live chat was on screen whose stored id had-// not arrived yet (the agent's open_preview right after the first send): the-// runtime it was opened under. Memory-only — runtime ids do not survive a-// relaunch. A draft opened before any send has no runtime, so its tabs carry-// no stamp and only adoptDraftPreviewTabs can take them.-const pendingRuntimeByTab = new Map<string, string>()+function setPendingRuntime(tabId: string, runtimeId: null | string): void {+ const current = $pendingRuntimeByTab.get()-function adoptPendingRuntimeTabs(runtimeId: null | string, storedSessionId: null | string): void {- if (!runtimeId || !storedSessionId || pendingRuntimeByTab.size === 0) {+ if ((current.get(tabId) ?? null) === runtimeId) {return}- const ids = new Set([...pendingRuntimeByTab].filter(([, runtime]) => runtime === runtimeId).map(([id]) => id))+ const next = new Map(current)- if (ids.size === 0) {+ if (runtimeId) {+ next.set(tabId, runtimeId)+ } else {+ next.delete(tabId)+ }++ $pendingRuntimeByTab.set(next)+}++/** Drop the runtime notes of tabs no profile bucket holds any more (closed,+ * pruned, or their profile dropped). */+function forgetGonePendingTabs(): void {+ const pending = $pendingRuntimeByTab.get()++ if (pending.size === 0) {return}- ids.forEach(id => pendingRuntimeByTab.delete(id))- const tabs = $previewTabs.get()+ const alive = new Set<string>(Object.values(tabsByProfile).flatMap(tabs => tabs.map(tab => tab.id)))- if (tabs.some(tab => ids.has(tab.id) && tab.sessionId == null)) {- $previewTabs.set(- tabs.map(tab => (ids.has(tab.id) && tab.sessionId == null ? { ...tab, sessionId: storedSessionId } : tab))- )+ if ([...pending.keys()].some(id => !alive.has(id))) {+ $pendingRuntimeByTab.set(new Map([...pending].filter(([id]) => alive.has(id))))}}-// The stored id arriving for the SAME runtime that opened the tab — not any-// focus change — is what hands it over.-$selectedStoredSessionId.listen(storedSessionId => adoptPendingRuntimeTabs($activeSessionId.get(), storedSessionId))-$activeSessionId.listen(runtimeId => adoptPendingRuntimeTabs(runtimeId, $selectedStoredSessionId.get()))+/** `runtimeId`'s stored id was just bound (its session state went from no+ * stored id to `storedSessionId`): the tabs it opened before then are that+ * session's. Called by the session-state layer at that transition — never on+ * a selection change, which is also what resuming another session looks+ * like. Every profile bucket: the runtime may not be the one in view. */+export function adoptPendingRuntimeTabs(runtimeId: string, storedSessionId: string): void {+ const ids = new Set([...$pendingRuntimeByTab.get()].filter(([, runtime]) => runtime === runtimeId).map(([id]) => id))++ if (ids.size === 0) {+ return+ }++ const adopt = (tabs: PreviewTab[]) =>+ tabs.some(tab => ids.has(tab.id) && tab.sessionId == null)+ ? tabs.map(tab => (ids.has(tab.id) && tab.sessionId == null ? { ...tab, sessionId: storedSessionId } : tab))+ : null++ let backgroundChanged = false++ for (const [key, tabs] of Object.entries(tabsByProfile)) {+ const next = key === viewKey ? null : adopt(tabs)++ if (next) {+ tabsByProfile[key] = next+ backgroundChanged = true+ }+ }++ if (backgroundChanged) {+ persistTabs()+ }++ const view = adopt($previewTabs.get())++ // Owner first, then the note: the other order leaves a beat where the tab+ // is neither owned nor pending and drops out of the drawer.+ if (view) {+ $previewTabs.set(view)+ }++ $pendingRuntimeByTab.set(new Map([...$pendingRuntimeByTab.get()].filter(([id]) => !ids.has(id))))+}/** The tab the rail actually shows. A stale or missing selection falls back to* the first tab, so the strip, `⌘W`, and the pane never disagree about which@@ -873,7 +956,14 @@ export function setPreviewRenderMode(tabId: string, renderMode: PreviewRenderMod* session's tab; a reused tab keeps its owner and pin. Opening for a session* that is not focused does not touch the focused drawer's selection — the* tab is fronted when that session's drawer shows. */-export function openPreview(target: PreviewTarget, requestedOwner: null | string = $focusedStoredSessionId.get()) {+export function openPreview(+ target: PreviewTarget,+ requestedOwner: null | string = $focusedStoredSessionId.get(),+ /** 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()+) {// 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)@@ -901,15 +991,9 @@ export function openPreview(target: PreviewTarget, requestedOwner: null | string$previewTabs.set(existing ? current.map(item => (item === existing ? tab : item)) : [...current, tab])- const pendingRuntime = tab.sessionId == null && !tab.pinned ? $activeSessionId.get() : null-- if (pendingRuntime) {- pendingRuntimeByTab.set(id, pendingRuntime)- } else {- pendingRuntimeByTab.delete(id)- }+ setPendingRuntime(id, tab.sessionId == null && !tab.pinned ? runtimeId : null)- if (!tabVisibleTo(tab, $focusedStoredSessionId.get(), $rotatedSessionIds.get())) {+ if (!$visiblePreviewTabs.get().some(item => item.id === id)) {rememberActiveTab(owner, id)returndiff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 8139f8cb333..dfd2e43d1c0 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -45,6 +45,7 @@ import { registryConnectionKind } from './connection-registry-state'import { recordDislike } from './desktop-metrics'import { dialedGatewayModeFor } from './gateway'import {+ adoptPendingRuntimeTabs,dropPreviewTabsForProfile,migratePreviewTabsForProfile,rekeyPreviewTabsSession,@@ -828,6 +829,12 @@ function handleTransition(previous: ClientSessionState | null, next: ClientSessisetSessionStalled(previous.storedSessionId, false)}+ // THIS runtime's stored id binding: the preview tabs it opened before then+ // are now its session's (#73890).+ if (!previous?.storedSessionId && next.storedSessionId) {+ adoptPendingRuntimeTabs(runtimeId, next.storedSessionId)+ }+// Every busy publish is stream activity: clear the quiet hint and restart// the silence window. A real terminal transition clears both the timer and// any hint, but only that authoritative transition clears working/busy.