The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): New session tab reuses the blank draft instead of opening another
Teknium9473c214e2ca
diff --git a/apps/desktop/src/app/chat/reuse-draft-tab.test.ts b/apps/desktop/src/app/chat/reuse-draft-tab.test.tsnew file mode 100644index 00000000000..d04ebe35982--- /dev/null+++ b/apps/desktop/src/app/chat/reuse-draft-tab.test.ts@@ -0,0 +1,145 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'++import { paneMirror } from '@/app/chat/pane-mirror'+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 { clearSessionDraft, freshDraftScope, onComposerDraftSyncRequest, stashSessionDraft } from '@/store/composer'+import * as session from '@/store/session'+import * as states from '@/store/session-states'+import type { SessionInfo } from '@/types/hermes'++import { $workspaceIsPage } from '../routes'++import { frontUntouchedDraftTab } from './reuse-draft-tab'++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 TILE_IDS = ['draft-a', 'used-b', 'bot-c']++function idleState(messages = 0): ClientSessionState {+ return { busy: false, messages: Array.from({ length: messages }, (_, i) => ({ id: `m${i}` })) } as ClientSessionState+}++function openTile(id: string, runtimeId: string, messages = 0, workspaceMode: 'bots' | 'sessions' = 'sessions') {+ states.openSessionTile(id, 'center', 'workspace', undefined, { workspaceMode })+ states.patchSessionTile(id, { runtimeId })+ states.$sessionStates.set({ ...states.$sessionStates.get(), [runtimeId]: idleState(messages) })+ // The create path fronts what it opened; the user is now looking at this tab.+ states.focusOpenSession(id, { workspaceMode })+}++const activePane = () => model.findGroupOfPane(tree.$layoutTree.get()!, 'workspace')?.active++function reset() {+ TILE_IDS.forEach(id => states.discardSessionTile(id))+ TILE_IDS.forEach(id => clearSessionDraft(id))+ states.$sessionStates.set({})+ tree.$layoutTree.set(null)+ tree.$activeTreeGroup.set(null)+ session.$selectedStoredSessionId.set(null)+ session.$activeSessionId.set(null)+ session.setSessions([])+ clearSessionDraft(freshDraftScope())+ $workspaceIsPage.set(false)+ window.localStorage.clear()+}++describe('the tab-strip "+" reuses an untouched New session draft (#145594)', () => {+ beforeEach(() => {+ reset()+ tree.declareDefaultTree(model.group(['workspace'], { active: 'workspace', id: 'main' }))+ })++ afterEach(reset)++ it('fronts the blank draft tab instead of asking for another one', () => {+ session.$selectedStoredSessionId.set('loaded-chat')+ openTile('draft-a', 'rt-a')+ openTile('used-b', 'rt-b', 2)+ expect(activePane()).toBe('session-tile:used-b')++ expect(frontUntouchedDraftTab()).toBe(true)+ expect(activePane()).toBe('session-tile:draft-a')+ expect(states.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['draft-a', 'used-b'])+ })++ it('fronts main when main is the blank new chat', () => {+ openTile('used-b', 'rt-b', 2)+ expect(activePane()).toBe('session-tile:used-b')++ expect(frontUntouchedDraftTab()).toBe(true)+ expect(activePane()).toBe('workspace')+ })++ it('still opens a new tab once every draft has been used', () => {+ session.$selectedStoredSessionId.set('loaded-chat')+ openTile('draft-a', 'rt-a')+ stashSessionDraft('draft-a', 'half-typed question', [])+ openTile('used-b', 'rt-b', 1)+ openTile('bot-c', 'rt-c', 0, 'bots')++ expect(frontUntouchedDraftTab()).toBe(false)++ clearSessionDraft('draft-a')+ session.setSessions([{ id: 'draft-a' } as SessionInfo])+ expect(frontUntouchedDraftTab()).toBe(false)+ })++ it('counts text still in the editor, not yet stashed by the debounce', () => {+ session.$selectedStoredSessionId.set('loaded-chat')+ openTile('draft-a', 'rt-a')+ openTile('used-b', 'rt-b', 1)++ const stop = onComposerDraftSyncRequest(({ mode, target }) => {+ if (mode === 'flush' && target === 'tile:draft-a') {+ stashSessionDraft('draft-a', 'just typed', [])+ }+ })++ try {+ expect(frontUntouchedDraftTab()).toBe(false)+ } finally {+ stop()+ }+ })++ it('does not treat a typed main draft or a page as blank', () => {+ stashSessionDraft(freshDraftScope(), 'draft text', [])+ expect(frontUntouchedDraftTab()).toBe(false)++ clearSessionDraft(freshDraftScope())+ $workspaceIsPage.set(true)+ expect(frontUntouchedDraftTab()).toBe(false)+ })++ it('does not reuse a tab whose session state is not known yet', () => {+ session.$selectedStoredSessionId.set('loaded-chat')+ states.openSessionTile('draft-a', 'center', 'workspace', undefined, { workspaceMode: 'sessions' })++ expect(frontUntouchedDraftTab()).toBe(false)+ })+})diff --git a/apps/desktop/src/app/chat/reuse-draft-tab.ts b/apps/desktop/src/app/chat/reuse-draft-tab.tsnew file mode 100644index 00000000000..47d744356f4--- /dev/null+++ b/apps/desktop/src/app/chat/reuse-draft-tab.ts@@ -0,0 +1,74 @@+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 { $sessionStates, $sessionTiles, focusOpenSession, type SessionTile } from '@/store/session-states'++import { mainChatOccupied } from '../open-session'+import { $workspaceIsPage } from '../routes'++const hasQueued = (...keys: (string | undefined)[]): boolean => {+ const queues = $queuedPromptsBySession.get()++ return keys.some(key => Boolean(key && queues[key]?.length))+}++// A composer stashes its text on a debounce, so flush the live editor before+// reading: a word typed a moment ago still counts as touched.+const draftIsEmpty = (target: string, scope: string): boolean => {+ requestComposerDraftSync('flush', target)+ const draft = takeSessionDraft(scope)++ return !draft.text.trim() && draft.attachments.length === 0+}++/**+ * 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+ * state is not known yet (restored, still resuming, failed) is NOT untouched:+ * unknown never reads as empty.+ */+export function isUntouchedDraftTile(tile: SessionTile): boolean {+ if ((tile.workspaceMode ?? 'sessions') !== 'sessions' || tile.error || !tile.runtimeId) {+ return false+ }++ const state = $sessionStates.get()[tile.runtimeId]++ return (+ Boolean(state) &&+ state.messages.length === 0 &&+ !state.busy &&+ !$sessions.get().some(session => sessionMatchesStoredId(session, tile.storedSessionId)) &&+ draftIsEmpty(`tile:${tile.storedSessionId}`, tile.storedSessionId) &&+ !hasQueued(tile.storedSessionId, tile.runtimeId)+ )+}++/** Main holds a blank new chat: no session yet, no page over it, nothing typed. */+function mainIsUntouchedDraft(): boolean {+ return (+ !mainChatOccupied($activeSessionId.get(), $selectedStoredSessionId.get()) &&+ !$workspaceIsPage.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).+ * Returns true when a draft was fronted and the caller must not create one.+ */+export function frontUntouchedDraftTab(): boolean {+ if (mainIsUntouchedDraft()) {+ revealTreePane('workspace')+ noteActiveTreeGroup(null)++ return true+ }++ const tile = $sessionTiles.get().find(isUntouchedDraftTile)++ return Boolean(tile && focusOpenSession(tile.storedSessionId) === 'tile')+}diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 302a9cf0e24..da39fdfbdf7 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -104,6 +104,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 { CommandPalette } from '../command-palette'import { triggerAndRefreshCronJobs } from '../cron/cron-actions'import { useGatewayBoot } from '../gateway/hooks/use-gateway-boot'@@ -995,8 +996,8 @@ export function ContribWiring({ children }: { children: ReactNode }) {// 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. Every click opens a fresh "New session" tab (multiple- // empty tabs are fine since none touch the session list).+ // 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 —@@ -1021,7 +1022,9 @@ export function ContribWiring({ children }: { children: ReactNode }) {return}- void openNewSessionTile('center', { listed: false })+ if (!frontUntouchedDraftTab()) {+ void openNewSessionTile('center', { listed: false })+ }}, [openNewSessionTile])// Archive the selected session (rebindable `session.archive` hotkey).