fix(browser): keep unsent page notes across restarts and ask before closing a tab that has them

Unsent browser notes lived only in the renderer store and hydration reset them, so a reload, restart or tab close lost them. Each saved browser page now carries its unsent notes, hydration restores them, and every close path (tab strip, keyboard, CLI, phone) asks before discarding them. A page script's window.close() can't discard them.
This commit is contained in:
Kelvin Amoaba
2026-11-10 19:52:10 +00:00
parent 3a8daa2418
commit 26f4b720e7
24 changed files with 362 additions and 91 deletions
@@ -12,9 +12,15 @@ vi.mock('@/lib/workspace/tabs/workspace-tab-commands', () => ({
import { handleGuestWindowCloseMessage } from './browser-page-window-close'
import { BROWSER_GUEST_WINDOW_CLOSE_CHANNEL } from '../../../../../shared/browser-guest-window-close'
function seedTab(pageId: string, isPinned = false, siblingPageIds: string[] = []): void {
function seedTab(
pageId: string,
isPinned = false,
siblingPageIds: string[] = [],
browserAnnotationsByPageId: Record<string, unknown[]> = {}
): void {
storeState.value = {
closeBrowserPage: closeBrowserPageMock,
browserAnnotationsByPageId,
browserTabsByWorktree: { 'wt-1': [{ id: 'ws-1' }] },
browserPagesByWorkspace: { 'ws-1': [{ id: pageId }, ...siblingPageIds.map((id) => ({ id }))] },
unifiedTabsByWorktree: {
@@ -40,6 +46,13 @@ describe('window.close() from a browser page', () => {
expect(dispatchMock).not.toHaveBeenCalled()
})
it('never discards unsent notes', () => {
seedTab('page-n', false, [], { 'page-n': [{ id: 'note-1' }] })
closeFrom('page-n', { back: false, forward: false })
expect(dispatchMock).not.toHaveBeenCalled()
expect(closeBrowserPageMock).not.toHaveBeenCalled()
})
it('closes only the calling page when its Orca tab holds other pages', () => {
seedTab('page-e', false, ['page-sibling'])
closeFrom('page-e', { back: false, forward: false })
@@ -32,7 +32,8 @@ export function handleGuestWindowCloseMessage(
const tab = (state.unifiedTabsByWorktree[owner.worktreeId] ?? []).find(
(candidate) => candidate.contentType === 'browser' && candidate.entityId === owner.workspaceId
)
if (tab?.isPinned) {
// A script may not discard what the user pinned or left unsent; the page's notes are all it closes.
if (tab?.isPinned || (state.browserAnnotationsByPageId[pageId]?.length ?? 0) > 0) {
return
}
pagesOpenedByPage.delete(pageId)
@@ -25,6 +25,7 @@ export default function PinnedTabCloseDialog(): React.JSX.Element {
const [previousRequest, setPreviousRequest] = useState(request)
const tabLabel = request?.tabLabel.trim()
const unsentNotes = request?.unsentNotes === true
// Reset new requests before paint without reviving a cancelled request’s checkbox state.
if (request !== previousRequest) {
@@ -53,16 +54,26 @@ export default function PinnedTabCloseDialog(): React.JSX.Element {
<DialogContent className="max-w-sm" showCloseButton={false}>
<DialogHeader>
<DialogTitle className="text-sm">
{t(
'auto.components.terminal.pane.PinnedTabCloseDialog.6c190f295a',
'Close pinned tab?'
)}
{unsentNotes
? t(
'auto.components.terminal.pane.PinnedTabCloseDialog.unsent_notes_title',
'Discard unsent notes?'
)
: t(
'auto.components.terminal.pane.PinnedTabCloseDialog.6c190f295a',
'Close pinned tab?'
)}
</DialogTitle>
<DialogDescription className="text-xs">
{t(
'auto.components.terminal.pane.PinnedTabCloseDialog.0d1963f4a6',
'This tab is pinned. Are you sure you want to close it?'
)}
{unsentNotes
? t(
'auto.components.terminal.pane.PinnedTabCloseDialog.unsent_notes_description',
"This tab has notes you haven't sent. Closing it discards them."
)
: t(
'auto.components.terminal.pane.PinnedTabCloseDialog.0d1963f4a6',
'This tab is pinned. Are you sure you want to close it?'
)}
</DialogDescription>
</DialogHeader>
{tabLabel ? (
@@ -70,19 +81,21 @@ export default function PinnedTabCloseDialog(): React.JSX.Element {
{tabLabel}
</p>
) : null}
<div className="flex items-center gap-2">
<Checkbox
id={checkboxId}
checked={dontAskAgain}
onCheckedChange={(checked) => setDontAskAgain(checked === true)}
/>
<Label htmlFor={checkboxId} className="text-xs font-normal text-muted-foreground">
{t(
'auto.components.terminal.pane.PinnedTabCloseDialog.dont_ask_again',
"Don't ask again for pinned tabs"
)}
</Label>
</div>
{unsentNotes ? null : (
<div className="flex items-center gap-2">
<Checkbox
id={checkboxId}
checked={dontAskAgain}
onCheckedChange={(checked) => setDontAskAgain(checked === true)}
/>
<Label htmlFor={checkboxId} className="text-xs font-normal text-muted-foreground">
{t(
'auto.components.terminal.pane.PinnedTabCloseDialog.dont_ask_again',
"Don't ask again for pinned tabs"
)}
</Label>
</div>
)}
<DialogFooter className="gap-2">
<Button type="button" variant="outline" size="sm" onClick={dismissPinnedTabClose}>
{t('auto.components.terminal.pane.PinnedTabCloseDialog.0b38ee2f86', 'Cancel')}
@@ -107,6 +107,7 @@ export async function useIpcEventsForCloseRouting({
activeBrowserTabIdByWorktree: { 'wt-1': 'workspace-1' },
browserTabsByWorktree: { 'wt-1': [{ id: 'workspace-1' }] },
browserPagesByWorkspace: {},
browserAnnotationsByPageId: {},
openFiles: [],
unifiedTabsByWorktree: {},
closeBrowserTab: vi.fn(),
@@ -73,6 +73,7 @@ function storeState(activeWorktreeId: string) {
[LOCAL_WT]: [{ id: 'ws-local' }],
[REMOTE_WT]: [{ id: 'ws-remote' }]
},
browserAnnotationsByPageId: {},
browserPagesByWorkspace: {
'ws-local': [{ id: 'page-local' }],
'ws-remote': [{ id: 'page-remote' }]
@@ -1,10 +1,6 @@
import { destroyPersistentWebview } from '@/components/browser-pane/host-guest/webview-registry'
import {
guardPinnedTabClose,
isUnifiedTabPinned,
resolvePinnedTabLabel
} from '../../store/slices/tabs/closing/pinned-tab-close-guard'
import { translate } from '@/i18n/i18n'
import { closeBrowserTabWithReply } from './browser-tab-close-with-reply'
import { useAppStore } from '../../store'
import { acquireBrowserAutomationBootstrapLease } from './browser-automation-bootstrap-lease'
import {
@@ -209,28 +205,8 @@ export function registerBrowserRequestIpcBridge(unsubs: (() => void)[]): void {
)
})
}
const replyPinnedBrowserCloseCanceled = (tabId: string): void => {
window.api.ui.replyTabClose({
requestId: data.requestId,
error: translate(
'auto.hooks.useIpcEvents.2f6637fe6c',
'Browser tab {{value0}} is pinned',
{ value0: tabId }
)
})
}
const closeBrowserWorkspaceWithReply = (worktreeId: string, workspaceId: string): void => {
const currentStore = useAppStore.getState()
guardPinnedTabClose({
isPinned: isUnifiedTabPinned(currentStore, worktreeId, workspaceId),
tabLabel: resolvePinnedTabLabel(currentStore, worktreeId, workspaceId),
onClose: () => {
useAppStore.getState().closeBrowserTab(workspaceId)
window.api.ui.replyTabClose({ requestId: data.requestId })
},
onCancel: () => replyPinnedBrowserCloseCanceled(workspaceId)
})
}
const closeWithReply = (worktreeId: string, workspaceId: string, pageId?: string): void =>
closeBrowserTabWithReply({ requestId: data.requestId, worktreeId, workspaceId, pageId })
const tabToClose =
explicitTargetId ??
(data.worktreeId
@@ -273,11 +249,15 @@ export function registerBrowserRequestIpcBridge(unsubs: (() => void)[]): void {
replyBrowserTabNotFound(tabToClose)
return
}
if (owningWorktreeId) {
closeWithReply(
owningWorktreeId,
workspaceId,
pages.length > 1 ? tabToClose : undefined
)
return
}
if (pages.length <= 1) {
if (owningWorktreeId) {
closeBrowserWorkspaceWithReply(owningWorktreeId, workspaceId)
return
}
store.closeBrowserTab(workspaceId)
} else {
store.closeBrowserPage(tabToClose)
@@ -295,7 +275,7 @@ export function registerBrowserRequestIpcBridge(unsubs: (() => void)[]): void {
replyBrowserTabNotFound(tabToClose)
return
}
closeBrowserWorkspaceWithReply(owningWorktreeId, tabToClose)
closeWithReply(owningWorktreeId, tabToClose)
return
}
if (explicitTargetId) {
@@ -0,0 +1,52 @@
import { translate } from '@/i18n/i18n'
import { useAppStore } from '../../store'
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
import {
guardPinnedTabClose,
isUnifiedTabPinned,
resolvePinnedTabLabel
} from '../../store/slices/tabs/closing/pinned-tab-close-guard'
/** Closes a browser tab, or one page of it, for a CLI or extension request once the user allows it, then replies to main. */
export function closeBrowserTabWithReply(params: {
requestId: string
worktreeId: string
workspaceId: string
/** Closes only this page, so the tab's pin does not guard it; its notes do. */
pageId?: string
}): void {
const { requestId, worktreeId, workspaceId, pageId } = params
const state = useAppStore.getState()
const unsentNotes = pageId
? (state.browserAnnotationsByPageId[pageId]?.length ?? 0) > 0
: hasUnsentBrowserNotes(state, workspaceId)
const closedId = pageId ?? workspaceId
guardPinnedTabClose({
isPinned: !pageId && isUnifiedTabPinned(state, worktreeId, workspaceId),
tabLabel: resolvePinnedTabLabel(state, worktreeId, workspaceId),
onClose: () => {
const latest = useAppStore.getState()
// Siblings may have closed while the prompt was open; the last page closes its tab.
if (pageId && (latest.browserPagesByWorkspace[workspaceId]?.length ?? 0) > 1) {
latest.closeBrowserPage(pageId)
} else {
latest.closeBrowserTab(workspaceId)
}
window.api.ui.replyTabClose({ requestId })
},
onCancel: () =>
window.api.ui.replyTabClose({
requestId,
error: unsentNotes
? translate(
'auto.hooks.useIpcEvents.unsent_notes_close_canceled',
'Browser tab {{value0}} has unsent notes, and the user kept it open',
{ value0: closedId }
)
: translate('auto.hooks.useIpcEvents.2f6637fe6c', 'Browser tab {{value0}} is pinned', {
value0: closedId
})
}),
unsentNotes
})
}
@@ -1,3 +1,4 @@
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
import { isLocalSessionTabCloseOwned } from '@/runtime/web-session-tabs-sync/closing/local-session-tab-close-owner'
import { closeMobileSessionTabInStore } from '@/runtime/web-session-tabs-sync/closing/mobile-session-tab-close'
import {
@@ -35,7 +36,8 @@ export function registerSessionTabIpcBridge(unsubs: (() => void)[]): void {
guardPinnedTabClose({
isPinned: isUnifiedTabPinned(store, worktreeId, browserTarget.workspaceId),
tabLabel: resolvePinnedTabLabel(store, worktreeId, browserTarget.workspaceId),
onClose: () => useAppStore.getState().closeBrowserTab(browserTarget.workspaceId)
onClose: () => useAppStore.getState().closeBrowserTab(browserTarget.workspaceId),
unsentNotes: hasUnsentBrowserNotes(store, browserTarget.workspaceId)
})
return
}
@@ -111,7 +113,8 @@ export function registerSessionTabIpcBridge(unsubs: (() => void)[]): void {
isPinned: isUnifiedTabPinned(store, worktreeId, visibleId),
tabLabel: resolvePinnedTabLabel(store, worktreeId, visibleId),
onClose: closeAndRespond,
onCancel: () => respond(SESSION_TAB_CLOSE_CANCELED_ERROR)
onCancel: () => respond(SESSION_TAB_CLOSE_CANCELED_ERROR),
unsentNotes: browserTarget ? hasUnsentBrowserNotes(store, browserTarget.workspaceId) : false
})
})
)
+4 -1
View File
@@ -2288,6 +2288,7 @@
"useIpcEvents": {
"0e3cf53060": "Browser tab {{value0}} not found",
"2f6637fe6c": "Browser tab {{value0}} is pinned",
"unsent_notes_close_canceled": "Browser tab {{value0}} has unsent notes, and the user kept it open",
"a8d2bf8e9e": "No active browser tab to close",
"f000b2ff76": "No active worktree",
"7a64b31991": "Local terminal creation is unavailable while a remote runtime is active",
@@ -4511,7 +4512,9 @@
"0d1963f4a6": "This tab is pinned. Are you sure you want to close it?",
"dont_ask_again": "Don't ask again for pinned tabs",
"0b38ee2f86": "Cancel",
"c337c9d75c": "Close"
"c337c9d75c": "Close",
"unsent_notes_title": "Discard unsent notes?",
"unsent_notes_description": "This tab has notes you haven't sent. Closing it discards them."
},
"TerminalSshReconnectOverlay": {
"authFailed": "Authentication failed for {{value0}}. Connect again to continue this terminal session.",
@@ -1,4 +1,5 @@
import type { BrowserPage, BrowserWorkspace } from '../../../../../shared/browser-workspace-types'
import type { BrowserPageAnnotation } from '../../../../../shared/browser/element-grab/browser-grab-types'
import type { WorkspaceSessionState } from '../../../../../shared/workspace-session/workspace-session-state-types'
import type { RemoteBrowserPageHandle } from '../../../store/slices/browser/browser-slice-contract'
@@ -6,7 +7,8 @@ export function buildBrowserSessionData(
browserTabsByWorktree: Record<string, BrowserWorkspace[]>,
browserPagesByWorkspace: Record<string, BrowserPage[]>,
activeBrowserTabIdByWorktree: Record<string, string | null>,
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>,
browserAnnotationsByPageId: Record<string, BrowserPageAnnotation[]>
): Pick<
WorkspaceSessionState,
'browserTabsByWorktree' | 'browserPagesByWorkspace' | 'activeBrowserTabIdByWorktree'
@@ -16,7 +18,8 @@ export function buildBrowserSessionData(
browserTabsByWorktree: buildPersistedBrowserTabsByWorktree(browserTabsByWorktree),
browserPagesByWorkspace: buildPersistedBrowserPagesByWorkspace(
browserPagesByWorkspace,
remoteBrowserPageHandlesByPageId
remoteBrowserPageHandlesByPageId,
browserAnnotationsByPageId
),
activeBrowserTabIdByWorktree
}
@@ -35,16 +38,21 @@ export function buildPersistedBrowserTabsByWorktree(
export function buildPersistedBrowserPagesByWorkspace(
browserPagesByWorkspace: Record<string, BrowserPage[]>,
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>,
browserAnnotationsByPageId: Record<string, BrowserPageAnnotation[]>
): WorkspaceSessionState['browserPagesByWorkspace'] {
return Object.fromEntries(
Object.entries(browserPagesByWorkspace).map(([workspaceId, pages]) => [
workspaceId,
pages.map((page) => ({
...page,
loading: false,
...persistedRemoteBrowserPageIdentity(remoteBrowserPageHandlesByPageId[page.id])
}))
pages.map((page) => {
const annotations = browserAnnotationsByPageId[page.id]
return {
...page,
loading: false,
...persistedRemoteBrowserPageIdentity(remoteBrowserPageHandlesByPageId[page.id]),
...(annotations?.length ? { annotations } : {})
}
})
])
)
}
@@ -155,10 +155,15 @@ export function buildWorkspaceSessionPatch(
snapshot.browserTabsByWorktree
)
}
if (stagedVisibilityChanged || changed.has('browserPagesByWorkspace')) {
if (
stagedVisibilityChanged ||
changed.has('browserPagesByWorkspace') ||
changed.has('browserAnnotationsByPageId')
) {
patch.browserPagesByWorkspace = buildPersistedBrowserPagesByWorkspace(
snapshot.browserPagesByWorkspace,
snapshot.remoteBrowserPageHandlesByPageId
snapshot.remoteBrowserPageHandlesByPageId,
snapshot.browserAnnotationsByPageId
)
}
if (stagedVisibilityChanged || changed.has('activeBrowserTabIdByWorktree')) {
@@ -42,6 +42,7 @@ export type WorkspaceSessionSnapshot = Pick<
| 'activeTabTypeByWorktree'
| 'browserTabsByWorktree'
| 'browserPagesByWorkspace'
| 'browserAnnotationsByPageId'
| 'activeBrowserTabIdByWorktree'
| 'browserUrlHistory'
| 'workspaceDocHistory'
@@ -84,6 +85,7 @@ export const SESSION_RELEVANT_FIELDS = [
'activeTabTypeByWorktree',
'browserTabsByWorktree',
'browserPagesByWorkspace',
'browserAnnotationsByPageId',
'activeBrowserTabIdByWorktree',
'browserUrlHistory',
'workspaceDocHistory',
@@ -310,7 +312,8 @@ export function buildWorkspaceSessionPayload(
snapshot.browserTabsByWorktree,
snapshot.browserPagesByWorkspace,
snapshot.activeBrowserTabIdByWorktree,
snapshot.remoteBrowserPageHandlesByPageId
snapshot.remoteBrowserPageHandlesByPageId,
snapshot.browserAnnotationsByPageId
),
// Why: enforce the history storage cap here so stale renderer state can't make every write stringify an oversized legacy array.
browserUrlHistory: normalizeBrowserHistoryEntries(snapshot.browserUrlHistory),
@@ -6,6 +6,7 @@ import {
resolvePinnedTabLabel
} from '@/store/slices/tabs/closing/pinned-tab-close-guard'
import { createWorkspaceTabCloseCommands } from '@/components/tab-group/workspace-tab-close-commands'
import { hasUnsentBrowserNotes } from '@/store/slices/browser/annotations/browser-page-annotation'
import { captureWorkspaceEmptiedReaction } from '@/components/tab-group/workspace-emptied-reaction'
import {
handleSwitchRecentTab,
@@ -189,7 +190,8 @@ export function dispatchWorkspaceTabCommand(command: WorkspaceTabCommand): boole
guardPinnedTabClose({
isPinned: tab.isPinned === true,
tabLabel: resolvePinnedTabLabel(state, target.worktreeId, tab.id),
onClose: close
onClose: close,
unsentNotes: tab.contentType === 'browser' && hasUnsentBrowserNotes(state, tab.entityId)
})
}
return true
@@ -42,3 +42,16 @@ export function retainBrowserAnnotationMarkerIds(
}
return nextByPageId
}
/** Closing a browser tab discards the notes its pages hold unsent. */
export function hasUnsentBrowserNotes(
state: {
browserPagesByWorkspace: Record<string, readonly { id: string }[]>
browserAnnotationsByPageId: Record<string, readonly BrowserPageAnnotation[]>
},
browserWorkspaceId: string
): boolean {
return (state.browserPagesByWorkspace[browserWorkspaceId] ?? []).some(
(page) => (state.browserAnnotationsByPageId[page.id]?.length ?? 0) > 0
)
}
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest'
import '../../../../../../shared/constants'
import { parseWorkspaceSession } from '../../../../../../shared/workspace-session/workspace-session-schema'
import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types'
import { buildWorkspaceSessionPayload } from '@/lib/workspace/persistence/workspace-session'
import { createTestStore } from '../../../testing/app-store-test-fixture'
import { createStoreSessionMockApi } from '../../../testing/app-store-session-api.test-fixture'
import { makeWorktree } from '../../worktrees/worktree.test-fixture'
import { makeBrowserTab } from '../browser-tab.test-fixture'
import { makeAnnotation } from '../annotations/browser-annotation-test-fixture'
vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } }))
createStoreSessionMockApi()
const WT = 'repo1::/path/wt1'
function createHydratedStore(session: WorkspaceSessionState) {
const store = createTestStore()
store.setState({
repos: [{ id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }],
worktreesByRepo: { repo1: [makeWorktree({ id: WT, repoId: 'repo1', path: '/path/wt1' })] },
activeWorktreeId: WT
})
store.getState().hydrateBrowserSession(session)
return store
}
describe('unsent browser notes across a restart', () => {
it('restores a page’s unsent notes from the saved session', () => {
const before = createHydratedStore({
activeRepoId: 'repo1',
activeWorktreeId: WT,
activeTabId: null,
tabsByWorktree: {},
terminalLayoutsByTabId: {},
browserTabsByWorktree: {
[WT]: [makeBrowserTab({ id: 'workspace-1', worktreeId: WT, url: 'https://example.com/' })]
},
browserPagesByWorkspace: {
'workspace-1': [
{
id: 'page-1',
workspaceId: 'workspace-1',
worktreeId: WT,
url: 'https://example.com/',
title: 'Example',
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 1
}
]
},
activeBrowserTabIdByWorktree: { [WT]: 'workspace-1' }
})
before.getState().addBrowserPageAnnotation(makeAnnotation('page-1'))
const saved = parseWorkspaceSession(
JSON.parse(JSON.stringify(buildWorkspaceSessionPayload(before.getState())))
)
if (!saved.ok) {
throw new Error(saved.error)
}
const after = createHydratedStore(saved.value)
expect(after.getState().browserAnnotationsByPageId).toEqual({
'page-1': [makeAnnotation('page-1')]
})
expect(after.getState().browserPagesByWorkspace['workspace-1']?.[0]).not.toHaveProperty(
'annotations'
)
})
})
@@ -6,7 +6,11 @@ import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../
import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch'
import '../../../../../../shared/constants'
import { ORCA_BROWSER_BLANK_URL } from '../../../../../../shared/browser/browser-blank-page'
import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types'
import type {
PersistedBrowserPage,
WorkspaceSessionState
} from '../../../../../../shared/workspace-session/workspace-session-state-types'
import type { BrowserPageAnnotation } from '../../../../../../shared/browser/element-grab/browser-grab-types'
import { normalizeBrowserHistoryEntries } from '../../../../../../shared/workspace-session/workspace-session-browser-history'
import { normalizeWorkspaceDocHistoryEntries } from '../../../../../../shared/workspace-session/workspace-doc-history'
import type { AppState } from '../../../types'
@@ -37,6 +41,7 @@ export function projectHydratedBrowserSession(
const persistedActiveTabTypeByWorktree = session.activeTabTypeByWorktree ?? {}
const browserTabsByWorktree: Record<string, BrowserWorkspace[]> = {}
const browserPagesByWorkspace: Record<string, BrowserPage[]> = {}
const browserAnnotationsByPageId: Record<string, BrowserPageAnnotation[]> = {}
for (const [worktreeId, tabs] of Object.entries(persistedTabsByWorktree)) {
if (!validWorktreeIds.has(worktreeId)) {
@@ -46,7 +51,7 @@ export function projectHydratedBrowserSession(
for (const tab of tabs) {
// Salvage can leave an empty page array; hydrate it like a missing array.
const storedPages = persistedPagesByWorkspace[tab.id]
const persistedPages = storedPages?.length
const persistedPages: PersistedBrowserPage[] = storedPages?.length
? storedPages
: [
{
@@ -70,10 +75,14 @@ export function projectHydratedBrowserSession(
]
const nextPages = persistedPages.map((page) => {
// Why: in-memory hydration callers can bypass the persistence schema's unknown-key stripping.
const { allowWindowClose: _legacyAllowWindowClose, ...persistedPage } =
page as typeof page & {
allowWindowClose?: boolean
}
const { allowWindowClose: _legacyAllowWindowClose, ...savedPage } = page as typeof page & {
allowWindowClose?: boolean
}
// The store keeps a page's unsent notes beside its record, not on it.
const { annotations, ...persistedPage } = savedPage
if (annotations?.length) {
browserAnnotationsByPageId[page.id] = annotations
}
return {
...persistedPage,
workspaceId: tab.id,
@@ -179,7 +188,7 @@ export function projectHydratedBrowserSession(
remoteBrowserPageHandlesByPageId:
buildRestoredRemoteBrowserPageHandles(browserPagesByWorkspace),
browserCertificateFailuresByPageId: {},
browserAnnotationsByPageId: {},
browserAnnotationsByPageId,
browserAnnotationMarkerIdsByPageId: {},
browserUrlHistory: normalizeBrowserHistoryEntries(session.browserUrlHistory ?? []),
workspaceDocHistory: normalizeWorkspaceDocHistoryEntries(session.workspaceDocHistory ?? []),
@@ -74,6 +74,7 @@ function persistedSession(
state.browserTabsByWorktree,
state.browserPagesByWorkspace,
state.activeBrowserTabIdByWorktree,
{},
{}
)
}
@@ -28,21 +28,18 @@ export function shouldConfirmPinnedTabClose(state: AppState): boolean {
return state.settings?.confirmClosePinnedTab ?? true
}
/** Centralize pin confirmation across keyboard/native/menu paths; unpinned or disabled-confirmation closes proceed immediately. */
/** Centralize close confirmation across keyboard/native/menu/CLI paths: unsent browser notes always ask; pins ask unless turned off. */
export function guardPinnedTabClose(params: {
isPinned: boolean
tabLabel: string
onClose: () => void
onCancel?: () => void
/** The tab holds browser notes the user has not sent; closing discards them. */
unsentNotes?: boolean
}): (() => void) | undefined {
const { isPinned, tabLabel, onClose, onCancel } = params
if (!isPinned) {
onClose()
return undefined
}
const { isPinned, tabLabel, onClose, onCancel, unsentNotes } = params
const state = useAppStore.getState()
if (!shouldConfirmPinnedTabClose(state)) {
if (!unsentNotes && (!isPinned || !shouldConfirmPinnedTabClose(state))) {
onClose()
return undefined
}
@@ -50,7 +47,8 @@ export function guardPinnedTabClose(params: {
const request = {
tabLabel,
onConfirm: onClose,
...(onCancel ? { onCancel } : {})
...(onCancel ? { onCancel } : {}),
...(unsentNotes ? { unsentNotes: true as const } : {})
}
state.requestPinnedTabCloseConfirm(request)
return () => state.cancelPinnedTabCloseRequest(request)
@@ -1,10 +1,12 @@
import type { StateCreator } from 'zustand'
import type { AppState } from '../../types'
/** A pending request to confirm closing a pinned tab. `onConfirm` runs the
* original close once the user accepts; the label is shown in the dialog. */
/** A pending request to confirm closing a pinned tab, or a browser tab holding unsent notes.
* `onConfirm` runs the original close once the user accepts; the label is shown in the dialog. */
export type PinnedTabCloseConfirmRequest = {
tabLabel: string
/** Set when the prompt warns about unsent browser notes instead of a pin. */
unsentNotes?: true
onConfirm: () => void
onCancel?: () => void
}
@@ -128,7 +128,8 @@ export function layoutViewAndFactsOfStore(
localOnlyScrollbackByTabId: terminals.localOnlyScrollbackByTabId,
browserPagesByWorkspace: buildPersistedBrowserPagesByWorkspace(
pickKeys(state.browserPagesByWorkspace, browserTabIds),
state.remoteBrowserPageHandlesByPageId
state.remoteBrowserPageHandlesByPageId,
{}
),
tabLabels: {},
terminalRows: {},
@@ -0,0 +1,77 @@
import { z } from 'zod'
import type { BrowserPageAnnotation } from '../element-grab/browser-grab-types'
const rectSchema = z.object({
x: z.number(),
y: z.number(),
width: z.number(),
height: z.number()
})
const payloadSchema = z.object({
page: z.object({
sanitizedUrl: z.string(),
title: z.string(),
viewportWidth: z.number(),
viewportHeight: z.number(),
scrollX: z.number(),
scrollY: z.number(),
devicePixelRatio: z.number(),
capturedAt: z.string()
}),
target: z.object({
tagName: z.string(),
selector: z.string(),
elementPath: z.string().optional(),
fullPath: z.string().optional(),
cssClasses: z.string().optional(),
nearbyElements: z.array(z.string()).optional(),
selectedText: z.string().nullable().optional(),
isFixed: z.boolean().optional(),
reactComponents: z.string().nullable().optional(),
sourceFile: z.string().nullable().optional(),
textSnippet: z.string(),
htmlSnippet: z.string(),
attributes: z.record(z.string(), z.string()),
accessibility: z.object({
role: z.string().nullable(),
accessibleName: z.string().nullable(),
ariaLabel: z.string().nullable(),
ariaLabelledBy: z.string().nullable()
}),
rectViewport: rectSchema,
rectPage: rectSchema,
computedStyles: z.object({
display: z.string(),
position: z.string(),
width: z.string(),
height: z.string(),
margin: z.string(),
padding: z.string(),
color: z.string(),
backgroundColor: z.string(),
border: z.string(),
borderRadius: z.string(),
fontFamily: z.string(),
fontSize: z.string(),
fontWeight: z.string(),
lineHeight: z.string(),
textAlign: z.string(),
zIndex: z.string()
})
}),
nearbyText: z.array(z.string()),
ancestorPath: z.array(z.string()),
screenshot: z.null().catch(null)
})
export const browserPageAnnotationSchema: z.ZodType<BrowserPageAnnotation> = z.object({
id: z.string(),
browserPageId: z.string(),
comment: z.string(),
intent: z.enum(['fix', 'change', 'question', 'approve']),
priority: z.enum(['blocking', 'important', 'suggestion']),
createdAt: z.string(),
payload: payloadSchema,
imagePaths: z.array(z.string()).optional()
})
@@ -596,6 +596,8 @@
"auto.components.terminal.pane.PinnedTabCloseDialog.6c190f295a",
"auto.components.terminal.pane.PinnedTabCloseDialog.c337c9d75c",
"auto.components.terminal.pane.PinnedTabCloseDialog.dont_ask_again",
"auto.components.terminal.pane.PinnedTabCloseDialog.unsent_notes_description",
"auto.components.terminal.pane.PinnedTabCloseDialog.unsent_notes_title",
"auto.components.workspace.cleanup.WorkspaceCleanupDialog.191f0bc98e",
"auto.components.workspace.cleanup.WorkspaceCleanupDialog.1d3503357d",
"auto.components.workspace.cleanup.WorkspaceCleanupDialog.38ca0b1400",
@@ -4,6 +4,7 @@ import { normalizeBrowserHistoryEntries } from './workspace-session-browser-hist
import { normalizeWorkspaceDocHistoryEntries } from './workspace-doc-history'
import { isDocPreviewUrl } from '../document-preview/doc-preview-scheme'
import { salvagingArray } from '../zod-salvage'
import { browserPageAnnotationSchema } from '../browser/annotations/browser-page-annotation-schema'
const browserLoadErrorSchema = z.object({
code: z.number(),
@@ -88,7 +89,9 @@ export const browserPageSchema = z.object({
docLocation: browserPageDocLocationSchema.nullable().optional(),
// Persist one-level conversion history; reject preview-scheme URLs at this read boundary as at every URL sink.
convertedFrom: browserPageConversionOriginSchema,
convertedTo: browserPageConversionOriginSchema
convertedTo: browserPageConversionOriginSchema,
// Unsent notes ride with their page so a reload or restart keeps them (#39856).
annotations: salvagingArray(browserPageAnnotationSchema).optional()
})
const browserHistoryEntrySchema = z.object({
@@ -4,6 +4,7 @@ import type { WorkspaceKey } from '../workspace-scope'
import type { Tab, TabGroup, TabGroupLayoutNode, WorkspaceVisibleTabType } from '../tab-types'
import type { TerminalLayoutSnapshot, TerminalTab } from '../workspace-layout/terminal-tab-types'
import type { BrowserHistoryEntry, BrowserPage, BrowserWorkspace } from '../browser-workspace-types'
import type { BrowserPageAnnotation } from '../browser/element-grab/browser-grab-types'
import type { WorkspaceDocHistoryEntry } from './workspace-doc-history'
import type { ClientHostedBrowserCloseIntent } from './client-hosted-browser-close-intent'
import type { PairedTerminalTabCloseIntent } from '../workspace-layout/paired-terminal-tab-close-intent'
@@ -32,6 +33,9 @@ export type PersistedOpenFile = {
liveTail?: boolean
}
/** A saved page carries its unsent notes; the store keeps them in browserAnnotationsByPageId. */
export type PersistedBrowserPage = BrowserPage & { annotations?: BrowserPageAnnotation[] }
export type WorkspaceSessionState = {
activeRepoId: string | null
/** Scope-aware active owner for folder workspaces. Legacy worktree UI still reads activeWorktreeId. */
@@ -56,7 +60,7 @@ export type WorkspaceSessionState = {
/** Persisted browser workspaces, keyed by worktree ID. */
browserTabsByWorktree?: Record<string, BrowserWorkspace[]>
/** Persisted browser pages, keyed by workspace ID. */
browserPagesByWorkspace?: Record<string, BrowserPage[]>
browserPagesByWorkspace?: Record<string, PersistedBrowserPage[]>
/** Per-worktree active browser workspace ID at shutdown. */
activeBrowserTabIdByWorktree?: Record<string, string | null>
/** Runtime-authoritative logical client-hosted pages; desktop browserPagesByWorkspace holds the client half. */