Skip to content

The agent that grows with you

fix(desktop): New session "+" is single-flight and honours the default owner

Teknium392c6f7d9ec6
diff --git a/apps/desktop/src/app/chat/new-session-tab.test.tsx b/apps/desktop/src/app/chat/new-session-tab.test.tsx
new file mode 100644
index 00000000000..7e1953e6f92
--- /dev/null
+++ b/apps/desktop/src/app/chat/new-session-tab.test.tsx
@@ -0,0 +1,236 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { paneMirror } from '@/app/chat/pane-mirror'
+import { useSessionActions } from '@/app/session/hooks/use-session-actions'
+import type { ClientSessionState } from '@/app/types'
+import * as model from '@/components/pane-shell/tree/model'
+import * as tree from '@/components/pane-shell/tree/store'
+import { registry } from '@/contrib/registry'
+import type { DesktopProfileRoute } from '@/global'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { clearSessionDraft, freshDraftScope } from '@/store/composer'
+import { $defaultProfileRoute, setDefaultProfile } from '@/store/default-profile'
+import { requestGatewayForAgent } from '@/store/gateway'
+import { $activeGatewayProfile, $newChatConnectionId, $newChatProfile, $newChatRoute } from '@/store/profile'
+import { $projectScope, ALL_PROJECTS } from '@/store/project-scope'
+import * as session from '@/store/session'
+import * as states from '@/store/session-states'
+
+import { $workspaceIsPage } from '../routes'
+
+import { openNewSessionTab } from './new-session-tab'
+
+vi.mock('@/store/profile', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ ensureGatewayAgent: vi.fn(async () => undefined),
+ ensureGatewayProfile: vi.fn(async () => undefined)
+}))
+vi.mock('@/store/gateway', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ activeGatewayConnectionId: vi.fn(() => 'old-host'),
+ requestGatewayForAgent: vi.fn(),
+ retainGatewayForAgent: vi.fn(async () => () => undefined)
+}))
+
+beforeAll(() => {
+ const disposeWorkspace = registry.register({
+ area: 'panes',
+ data: { placement: 'main', uncloseable: true },
+ id: 'workspace',
+ render: () => null,
+ title: 'Chat'
+ })
+
+ tree.watchContributedPanes()
+ paneMirror({
+ source: states.$sessionTiles,
+ key: tile => tile.storedSessionId,
+ prefix: 'session-tile',
+ dir: () => 'center',
+ minWidth: '20rem',
+ title: id => id,
+ render: () => null,
+ close: states.closeSessionTile
+ })()
+
+ return disposeWorkspace
+})
+
+const OLD = { connectionId: 'old-host', profile: 'old-profile' }
+const NEW = { connectionId: 'new-host', profile: 'new-profile' }
+
+/** The real hook, with the window's runtime cache backed by the real store. */
+function mountPlus() {
+ const ref = <T,>(current: T) => ({ current })
+
+ const updateSessionState = (id: string, updater: (state: ClientSessionState) => ClientSessionState) => {
+ const next = updater(states.$sessionStates.get()[id] ?? createClientSessionState())
+ states.$sessionStates.set({ ...states.$sessionStates.get(), [id]: next })
+
+ return next
+ }
+
+ const { result } = renderHook(() =>
+ useSessionActions({
+ activeSessionId: 'existing-runtime',
+ activeSessionIdRef: ref<string | null>('existing-runtime'),
+ busyRef: ref(false),
+ creatingSessionRef: ref(false),
+ ensureSessionState: () => createClientSessionState(),
+ getRouteToken: () => 'route',
+ getRoutedStoredSessionId: () => null,
+ navigate: vi.fn(),
+ requestGateway: vi.fn(async () => ({}) as never),
+ resetViewSync: vi.fn(),
+ routedSessionId: null,
+ runtimeIdByStoredSessionIdRef: ref(new Map()),
+ selectedStoredSessionId: null,
+ selectedStoredSessionIdRef: ref<string | null>(null),
+ sessionStateByRuntimeIdRef: ref(new Map()),
+ syncSessionStateToView: vi.fn(),
+ updateSessionState
+ })
+ )
+
+ return () => openNewSessionTab(result.current.openNewSessionTile)
+}
+
+/** Each session.create answers only when the test releases it. */
+function holdCreates() {
+ const releases: (() => void)[] = []
+ let n = 0
+
+ vi.mocked(requestGatewayForAgent).mockImplementation(() => {
+ const id = ++n
+
+ return new Promise(resolve => {
+ releases.push(() => resolve({ session_id: `rt-${id}`, stored_session_id: `draft-${id}`, info: {} }))
+ })
+ })
+
+ return releases
+}
+
+const creates = () => vi.mocked(requestGatewayForAgent).mock.calls.filter(call => call[2] === 'session.create')
+const flush = () => act(async () => new Promise(resolve => setTimeout(resolve, 0)))
+
+function reset() {
+ states.$sessionTiles.get().forEach(tile => states.discardSessionTile(tile.storedSessionId))
+ states.$sessionStates.set({})
+ tree.$layoutTree.set(null)
+ tree.$activeTreeGroup.set(null)
+ session._resetSessionOwnerHintsForTests()
+ session.$selectedStoredSessionId.set(null)
+ session.setActiveSessionId(null)
+ session.setSessions([])
+ session.setConnection(null)
+ clearSessionDraft(freshDraftScope())
+ $workspaceIsPage.set(false)
+ $defaultProfileRoute.set(null)
+ $newChatRoute.set(null)
+ $newChatProfile.set(null)
+ $newChatConnectionId.set(null)
+ window.localStorage.clear()
+}
+
+beforeEach(async () => {
+ reset()
+ tree.declareDefaultTree(model.group(['workspace'], { active: 'workspace', id: 'main' }))
+ $activeGatewayProfile.set('old-profile')
+ $projectScope.set(ALL_PROJECTS)
+ window.hermesDesktop = { profile: { setDefault: async (route: DesktopProfileRoute) => route } } as never
+ vi.mocked(requestGatewayForAgent).mockReset()
+ await setDefaultProfile(OLD)
+ // Main shows a loaded conversation, so the "+" has no blank main to front.
+ session.$selectedStoredSessionId.set('loaded-chat')
+ session.setActiveSessionId('existing-runtime')
+})
+
+afterEach(() => {
+ cleanup()
+ reset()
+ vi.clearAllMocks()
+})
+
+describe('the registered New session "+" action (#145594)', () => {
+ it('fronts a blank main instead of creating a session', async () => {
+ session.$selectedStoredSessionId.set(null)
+ session.setActiveSessionId(null)
+ const plus = mountPlus()
+
+ plus()
+ plus()
+ plus()
+ await flush()
+
+ expect(creates()).toHaveLength(0)
+ })
+
+ it('keeps a still-pending create single-flight: repeated clicks land on that one draft', async () => {
+ const releases = holdCreates()
+ const plus = mountPlus()
+
+ plus()
+ await flush()
+ plus()
+ plus()
+ await flush()
+ await act(async () => releases.forEach(release => release()))
+ await flush()
+
+ expect(creates()).toHaveLength(1)
+ expect(states.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['draft-1'])
+
+ // Settled: the draft is now a real blank tab, and "+" keeps fronting it.
+ plus()
+ await flush()
+ expect(creates()).toHaveLength(1)
+ })
+
+ it('a failed create does not latch the "+" shut', async () => {
+ vi.mocked(requestGatewayForAgent).mockRejectedValueOnce(new Error('gateway down'))
+ const plus = mountPlus()
+
+ plus()
+ await flush()
+ vi.mocked(requestGatewayForAgent).mockResolvedValue({ session_id: 'rt', stored_session_id: 'draft', info: {} })
+ plus()
+ await flush()
+
+ expect(creates()).toHaveLength(2)
+ expect(states.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['draft'])
+ })
+
+ it('opens under a newly selected default instead of reusing a blank draft of the old owner', async () => {
+ vi.mocked(requestGatewayForAgent).mockResolvedValueOnce({
+ session_id: 'rt-old',
+ stored_session_id: 'old-draft',
+ info: {}
+ })
+ const plus = mountPlus()
+
+ plus()
+ await flush()
+ expect(creates()[0].slice(0, 2)).toEqual([OLD.connectionId, OLD.profile])
+
+ await act(() => setDefaultProfile(NEW))
+ vi.mocked(requestGatewayForAgent).mockResolvedValueOnce({
+ session_id: 'rt-new',
+ stored_session_id: 'new-draft',
+ info: {}
+ })
+ plus()
+ await flush()
+
+ expect(creates()).toHaveLength(2)
+ expect(creates()[1].slice(0, 2)).toEqual([NEW.connectionId, NEW.profile])
+ // The old owner's draft is left intact, not re-homed.
+ expect(states.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['old-draft', 'new-draft'])
+
+ // Same owner as the default again: the blank draft is fronted, not duplicated.
+ plus()
+ await flush()
+ expect(creates()).toHaveLength(2)
+ })
+})
diff --git a/apps/desktop/src/app/chat/new-session-tab.ts b/apps/desktop/src/app/chat/new-session-tab.ts
new file mode 100644
index 00000000000..9eda45bf717
--- /dev/null
+++ b/apps/desktop/src/app/chat/new-session-tab.ts
@@ -0,0 +1,58 @@
+import type { useSessionActions } from '@/app/session/hooks/use-session-actions'
+import { $workspaceMode, $workspaceNewSessionTarget, $workspaceOwnerKey } from '@/components/pane-shell/workspace-scope'
+
+import { frontUntouchedDraftTab } from './reuse-draft-tab'
+
+type OpenNewSessionTile = ReturnType<typeof useSessionActions>['openNewSessionTile']
+
+// The draft tab only exists once session.create answers, so until then the
+// reuse check cannot see it. Clicks meanwhile belong to that pending draft
+// (the create fronts it when it lands) rather than each starting a twin. The
+// latch is per window, like the tab strip, and clears on success or failure.
+let pendingDraftCreate: null | Promise<void> = null
+
+/**
+ * The tab-strip "+" and ⌘T: open a new session as its own tab (stacked into
+ * the workspace zone) WITHOUT polluting the session list. Created
+ * `listed: false`, so each new tab's in-memory session stays out of the
+ * sidebar until its first message persists a turn and a refresh surfaces it —
+ * Cursor-style. Several may be open, but only one blank: an untouched draft
+ * (main or a tab) of the default owner is fronted instead of minting a
+ * twin, and so is a draft still being created (#145594).
+ *
+ * Bot Mode aims the "+" at the selected bot's own profile. Anything short of
+ * an exact route — a group chat's `blocked` target, an orphaned roster row —
+ * falls THROUGH to the ordinary session rather than refusing: the main strip
+ * carries plain session tabs alongside bot chats, so a "+" there must never
+ * be dead just because the sidebar's current selection has nowhere to route.
+ */
+export function openNewSessionTab(openNewSessionTile: OpenNewSessionTile): void {
+ const workspaceOwnerKey = $workspaceOwnerKey.get()
+ const workspaceNewSessionTarget = $workspaceNewSessionTarget.get()
+
+ if ($workspaceMode.get() === 'bots' && workspaceNewSessionTarget?.kind === 'route' && workspaceOwnerKey) {
+ void openNewSessionTile('center', {
+ listed: false,
+ route: workspaceNewSessionTarget.route,
+ workspaceScope: {
+ ownerRoute: workspaceNewSessionTarget.route,
+ workspaceMode: 'bots',
+ workspaceOwnerKey
+ }
+ })
+
+ return
+ }
+
+ if (pendingDraftCreate || frontUntouchedDraftTab()) {
+ return
+ }
+
+ const create = openNewSessionTile('center', { listed: false }).finally(() => {
+ if (pendingDraftCreate === create) {
+ pendingDraftCreate = null
+ }
+ })
+
+ pendingDraftCreate = create
+}
diff --git a/apps/desktop/src/app/chat/reuse-draft-tab.ts b/apps/desktop/src/app/chat/reuse-draft-tab.ts
index 47d744356f4..b445bc38109 100644
--- a/apps/desktop/src/app/chat/reuse-draft-tab.ts
+++ b/apps/desktop/src/app/chat/reuse-draft-tab.ts
@@ -1,7 +1,21 @@
+import { defaultNewSessionTarget } from '@/app/session/new-session-route'
import { noteActiveTreeGroup, revealTreePane } from '@/components/pane-shell/tree/store'
import { freshDraftScope, requestComposerDraftSync, takeSessionDraft } from '@/store/composer'
import { $queuedPromptsBySession } from '@/store/composer-queue'
-import { $activeSessionId, $selectedStoredSessionId, $sessions, sessionMatchesStoredId } from '@/store/session'
+import {
+ $activeGatewayProfile,
+ $newChatProfile,
+ type AgentProfileRoute,
+ normalizeProfileKey,
+ resolveNewChatOwnerRoute
+} from '@/store/profile'
+import {
+ $activeSessionId,
+ $selectedStoredSessionId,
+ $sessions,
+ getSessionOwnerHints,
+ sessionMatchesStoredId
+} from '@/store/session'
import { $sessionStates, $sessionTiles, focusOpenSession, type SessionTile } from '@/store/session-states'
import { mainChatOccupied } from '../open-session'
@@ -22,6 +36,34 @@ const draftIsEmpty = (target: string, scope: string): boolean => {
return !draft.text.trim() && draft.attachments.length === 0
}
+const sameRoute = (a: AgentProfileRoute, b: AgentProfileRoute): boolean =>
+ a.connectionId === b.connectionId && normalizeProfileKey(a.profile) === normalizeProfileKey(b.profile)
+
+/**
+ * A blank draft is only a stand-in for a new session when it already belongs
+ * to the owner a new session would get. Changing the default device/profile
+ * deliberately leaves existing drafts where they are, so a draft of the old
+ * owner must not swallow a "+" meant for the new one: the caller creates
+ * under the default instead. No default means the ambient owner, as before.
+ * `routes` are the draft's exact owners; `legacyProfile` its profile-only
+ * owner when it has none.
+ */
+function ownedByDefault(routes: AgentProfileRoute[], legacyProfile: string): boolean {
+ const target = defaultNewSessionTarget()
+
+ if (!target) {
+ return true
+ }
+
+ if (target.route) {
+ const route = target.route
+
+ return routes.some(owner => sameRoute(owner, route))
+ }
+
+ return routes.length === 0 && normalizeProfileKey(legacyProfile) === normalizeProfileKey(target.profile)
+}
+
/**
* A Sessions tab nobody has used: no listed row, a bound runtime whose state
* reads zero messages and idle, nothing typed, nothing queued. A tab whose
@@ -39,6 +81,7 @@ export function isUntouchedDraftTile(tile: SessionTile): boolean {
Boolean(state) &&
state.messages.length === 0 &&
!state.busy &&
+ ownedByDefault(getSessionOwnerHints(tile.storedSessionId), tile.ownerProfile || 'default') &&
!$sessions.get().some(session => sessionMatchesStoredId(session, tile.storedSessionId)) &&
draftIsEmpty(`tile:${tile.storedSessionId}`, tile.storedSessionId) &&
!hasQueued(tile.storedSessionId, tile.runtimeId)
@@ -47,17 +90,20 @@ export function isUntouchedDraftTile(tile: SessionTile): boolean {
/** Main holds a blank new chat: no session yet, no page over it, nothing typed. */
function mainIsUntouchedDraft(): boolean {
+ const owner = resolveNewChatOwnerRoute()
+
return (
!mainChatOccupied($activeSessionId.get(), $selectedStoredSessionId.get()) &&
!$workspaceIsPage.get() &&
+ ownedByDefault(owner ? [owner] : [], $newChatProfile.get() || $activeGatewayProfile.get()) &&
draftIsEmpty('main', freshDraftScope())
)
}
/**
* The tab-strip "+" / ⌘T opens a new session as a tab. When this window
- * already shows a blank one, front it instead of minting another identical
- * "New session" tab, so repeated clicks land on the one pending draft (#145594).
+ * already shows a blank one owned by the default new-session owner, front it
+ * instead of minting another identical "New session" tab, so repeated clicks land on the one pending draft (#145594).
* Returns true when a draft was fronted and the caller must not create one.
*/
export function frontUntouchedDraftTab(): boolean {
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index da39fdfbdf7..f7c87059651 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -26,12 +26,7 @@ import { DesktopOnboardingOverlay } from '@/components/onboarding'
import { firstRunIntro } from '@/components/onboarding/first-run/kickoff'
import { OnboardingEnd } from '@/components/onboarding/onboarding-end'
import { $newSessionTabAction, registerPaneCloser } from '@/components/pane-shell/tree/store'
-import {
- $workspaceMode,
- $workspaceNewSessionTarget,
- $workspaceOwnerKey,
- setWorkspaceScope
-} from '@/components/pane-shell/workspace-scope'
+import { setWorkspaceScope } from '@/components/pane-shell/workspace-scope'
import { FloatingPet } from '@/components/pet/floating-pet'
import { RemoteDisplayBanner } from '@/components/remote-display-banner'
import { SendDiagnosticsHost } from '@/components/send-diagnostics-dialog'
@@ -104,7 +99,7 @@ import type { SessionInfo } from '@/types/hermes'
import { closeWorkspaceTab } from '../chat/close-tab'
import { requestComposerInsert } from '../chat/composer/focus'
import { useComposerActions } from '../chat/hooks/use-composer-actions'
-import { frontUntouchedDraftTab } from '../chat/reuse-draft-tab'
+import { openNewSessionTab as openNewSessionTabAction } from '../chat/new-session-tab'
import { CommandPalette } from '../command-palette'
import { triggerAndRefreshCronJobs } from '../cron/cron-actions'
import { useGatewayBoot } from '../gateway/hooks/use-gateway-boot'
@@ -992,40 +987,8 @@ export function ContribWiring({ children }: { children: ReactNode }) {
}
}, [])
- // The tab-strip "+" and ⌘T share one action: open a new session as its own
- // tab (stacked into the workspace zone) WITHOUT polluting the session list.
- // Created `listed: false`, so each new tab's in-memory session stays out of
- // the sidebar until its first message persists a turn and a refresh surfaces
- // it — Cursor-style. Several may be open, but only one blank: an untouched
- // draft (main or a tab) is fronted instead of minting a twin (#145594).
- //
- // Bot Mode aims the "+" at the selected bot's own profile. Anything short of
- // an exact route — a group chat's `blocked` target, an orphaned roster row —
- // falls THROUGH to the ordinary session rather than refusing: the main strip
- // carries plain session tabs alongside bot chats, so a "+" there must never
- // be dead just because the sidebar's current selection has nowhere to route.
- const openNewSessionTab = useCallback(() => {
- const workspaceOwnerKey = $workspaceOwnerKey.get()
- const workspaceNewSessionTarget = $workspaceNewSessionTarget.get()
-
- if ($workspaceMode.get() === 'bots' && workspaceNewSessionTarget?.kind === 'route' && workspaceOwnerKey) {
- void openNewSessionTile('center', {
- listed: false,
- route: workspaceNewSessionTarget.route,
- workspaceScope: {
- ownerRoute: workspaceNewSessionTarget.route,
- workspaceMode: 'bots',
- workspaceOwnerKey
- }
- })
-
- return
- }
-
- if (!frontUntouchedDraftTab()) {
- void openNewSessionTile('center', { listed: false })
- }
- }, [openNewSessionTile])
+ // The tab-strip "+" and ⌘T share one action (see `openNewSessionTab`).
+ const openNewSessionTab = useCallback(() => openNewSessionTabAction(openNewSessionTile), [openNewSessionTile])
// Archive the selected session (rebindable `session.archive` hotkey).
const archiveSelectedSession = useCallback(() => {