Skip to content

The agent that grows with you

73.7 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import type { ClientSessionState } from '@/app/types'
import { findGroupOfPane, group, split } from '@/components/pane-shell/tree/model'
import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'
import {
  $workspaceMode,
  forgetActivePane,
  rememberActivePane,
  setWorkspaceScope,
  workspaceScopeKey
} from '@/components/pane-shell/workspace-scope'
import { $connectionsRegistry } from '@/store/connection-registry-state'
import { setPrimaryGateway, setPrimaryGatewayConnection } from '@/store/gateway'
import { $activeGatewayProfile } from '@/store/profile'
import { $projectTree } from '@/store/projects'
import {
  $activeSessionId,
  $connection,
  $selectedStoredSessionId,
  $workspaceCwdOwner,
  setCurrentCwd,
  setSessionOwnerHint,
  setSessions,
  setUnlistedSessionOwnerRows
} from '@/store/session'
import { $focusedStoredSessionId } from '@/store/session-focus'
import type { SessionProfileRoute } from '@/store/session-request-router'
import type { SessionTile } from '@/store/session-states'
import type * as SessionStatesModule from '@/store/session-states'
import {
  $focusedWorkspaceCwd,
  $sessionStates,
  $sessionTiles,
  blankDraftTile,
  clearAllSessionStates,
  closeAllOpenSessionTiles,
  focusedSessionNeedsRoute,
  focusedSessionWorkspaceScope,
  focusOpenSession,
  focusWorkspaceOwnerSessionTile,
  foregroundSessionScopes,
  frontMainIfSelected,
  isSessionRemote,
  knownOwnerForSession,
  markSelectionRestore,
  nextSessionTileForWorkspace,
  openSessionTile,
  patchSessionTile,
  recordSessionEventScope,
  rekeySessionTile,
  releaseSessionTranscript,
  requestForOwnedSession,
  resetRouteOwnedTileRuntimeBindings,
  resetTileRuntimeBindings,
  selectionHomesToWorkspace,
  type SessionTileDelegate,
  sessionTileOwnerRoute,
  setSessionTileDelegate,
  setSessionTileWorkspaceScope
} from '@/store/session-states'
import { orderTilesByTree } from '@/store/session-tile-order'

const tile = (storedSessionId: string): SessionTile => ({ storedSessionId })
const tilePane = (id: string) => `session-tile:${id}`

describe('foregroundSessionScopes', () => {
  beforeEach(() => {
    clearAllSessionStates()
    $activeSessionId.set(null)
    $sessionTiles.set([])
  })

  afterEach(() => {
    clearAllSessionStates()
    $activeSessionId.set(null)
    $sessionTiles.set([])
  })

  it('keeps the exact registry owner of an idle foreground runtime', () => {
    recordSessionEventScope({ connectionId: 'cloud', profile: 'default', session_id: 'runtime-1' })
    $activeSessionId.set('runtime-1')

    expect(foregroundSessionScopes()).toEqual(new Set(['conn:cloud::default']))
  })

  it('fails closed when the foreground runtime has no registered source', () => {
    $activeSessionId.set('legacy-runtime')

    expect(foregroundSessionScopes()).toEqual(new Set())
  })

  it('keeps every open pane owner, not only the focused runtime', () => {
    recordSessionEventScope({ connectionId: 'cloud-a', profile: 'default', session_id: 'runtime-a' })
    recordSessionEventScope({ connectionId: 'cloud-b', profile: 'default', session_id: 'runtime-b' })
    $sessionTiles.set([
      { runtimeId: 'runtime-a', storedSessionId: 'stored-a' },
      {
        ownerRoute: { connectionId: 'cloud-b', profile: 'default' },
        storedSessionId: 'stored-b'
      }
    ])

    expect(foregroundSessionScopes()).toEqual(new Set(['conn:cloud-a::default', 'conn:cloud-b::default']))
  })

  it('releases an idle pane owner when the pane closes', () => {
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'cloud', profile: 'default' },
        storedSessionId: 'stored-cloud'
      }
    ])

    expect(foregroundSessionScopes()).toEqual(new Set(['conn:cloud::default']))

    $sessionTiles.set([])

    expect(foregroundSessionScopes()).toEqual(new Set())
  })
})

describe('resetTileRuntimeBindings', () => {
  afterEach(() => {
    $sessionTiles.set([])
  })

  it('invalidates the delegate wiring cache AND drops tile runtime ids (sleep/wake reconnect)', () => {
    // The reconnect path must bust BOTH layers: the tile atoms' runtimeId and
    // the delegate's stored→runtime warm cache. Clearing only the atoms let
    // resumeTile's warm path re-bind the same dead runtime id after wake.
    const invalidateRuntimeBindings = vi.fn()
    setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)

    $sessionTiles.set([{ runtimeId: 'runtime-dead', storedSessionId: 'stored-a' }])
    resetTileRuntimeBindings()

    expect(invalidateRuntimeBindings).toHaveBeenCalledTimes(1)
    expect($sessionTiles.get()).toEqual([
      { anchor: undefined, before: undefined, dir: undefined, storedSessionId: 'stored-a' }
    ])
  })

  it('keeps Bot runtimes owned by a different connection', () => {
    const invalidateRuntimeBindings = vi.fn()
    setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
    $sessionTiles.set([
      {
        ownerRoute: {
          connectionId: 'barry',
          mode: 'remote',
          profile: 'oxcoder',
          targetProfile: 'oxcoder'
        },
        runtimeId: 'runtime-bot',
        storedSessionId: 'stored-bot',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:barry::oxcoder'
      }
    ])

    resetTileRuntimeBindings('work-vps')

    expect($sessionTiles.get()[0]?.runtimeId).toBe('runtime-bot')
    expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-bot']))
  })

  it('rebinds only the restarted connection while preserving other Bot gateways', () => {
    const invalidateRuntimeBindings = vi.fn()
    setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'barry', mode: 'remote', profile: 'oxcoder', targetProfile: 'oxcoder' },
        runtimeId: 'runtime-barry-dead',
        storedSessionId: 'stored-barry-bot',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:barry::oxcoder'
      },
      {
        ownerRoute: { connectionId: 'barry', mode: 'remote', profile: 't2oracle', targetProfile: 't2oracle' },
        runtimeId: 'runtime-barry-sibling-live',
        storedSessionId: 'stored-barry-sibling-bot',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:barry::t2oracle'
      },
      {
        ownerRoute: { connectionId: 'work-vps', mode: 'remote', profile: 'ceo', targetProfile: 'ceo' },
        runtimeId: 'runtime-work-live',
        storedSessionId: 'stored-work-bot',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:work-vps::ceo'
      },
      { runtimeId: 'runtime-session-dead', storedSessionId: 'stored-session' }
    ])

    resetTileRuntimeBindings({ connectionId: 'barry', profile: 'oxcoder' })

    const [barryBot, barrySibling, workBot, ordinarySession] = $sessionTiles.get()

    expect(barryBot).toMatchObject({ storedSessionId: 'stored-barry-bot' })
    expect(barryBot).not.toHaveProperty('runtimeId')
    expect(barrySibling).toMatchObject({
      runtimeId: 'runtime-barry-sibling-live',
      storedSessionId: 'stored-barry-sibling-bot'
    })
    expect(workBot).toMatchObject({ runtimeId: 'runtime-work-live', storedSessionId: 'stored-work-bot' })
    expect(ordinarySession).toMatchObject({ storedSessionId: 'stored-session' })
    expect(ordinarySession).not.toHaveProperty('runtimeId')
    expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-barry-sibling-bot', 'stored-work-bot']))
  })

  it('keeps an owner-routed SESSIONS tile (branch child) bound across an unrelated reconnect', () => {
    const invalidateRuntimeBindings = vi.fn()
    setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: '100-125-133-71-9119', mode: 'remote', profile: 'default' },
        runtimeId: 'runtime-branch-live',
        storedSessionId: 'stored-branch-child',
        workspaceMode: 'sessions'
      }
    ])

    // A flapping sibling connection reconnects; the branch child's runtime
    // lives on its parent's backend and must keep its binding — dropping it
    // re-arms the tile's resume, and repeated sibling flaps latch the
    // resume-storm error card over a healthy session.
    resetTileRuntimeBindings({ connectionId: 'other-ssh-source', profile: 'default' })

    expect($sessionTiles.get()[0]?.runtimeId).toBe('runtime-branch-live')
    expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-branch-child']))

    // Its OWN connection reconnecting still drops the binding for re-resume.
    resetTileRuntimeBindings({ connectionId: '100-125-133-71-9119', profile: 'default' })
    expect($sessionTiles.get()[0]?.runtimeId).toBeUndefined()
  })

  it('unknown restarted identity preserves only Bot runtimes owned by provably-live connections', () => {
    // Legacy remote primary: no registry connectionId to scope by. The dead
    // owner can't be named, so keep only owners we know are alive elsewhere —
    // the restarted backend's own Bot tile must still drop its binding.
    const invalidateRuntimeBindings = vi.fn()
    setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'legacy-remote', mode: 'remote', profile: 'writer', targetProfile: 'writer' },
        runtimeId: 'runtime-legacy-dead',
        storedSessionId: 'stored-legacy-bot',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:legacy-remote::writer'
      },
      {
        ownerRoute: { connectionId: 'work-vps', mode: 'remote', profile: 'ceo', targetProfile: 'ceo' },
        runtimeId: 'runtime-work-live',
        storedSessionId: 'stored-work-bot',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:work-vps::ceo'
      },
      { runtimeId: 'runtime-session-dead', storedSessionId: 'stored-session' }
    ])

    resetTileRuntimeBindings({ liveConnectionIds: new Set(['work-vps']) })

    const [legacyBot, workBot, ordinarySession] = $sessionTiles.get()

    expect(legacyBot).toMatchObject({ storedSessionId: 'stored-legacy-bot' })
    expect(legacyBot).not.toHaveProperty('runtimeId')
    expect(workBot).toMatchObject({ runtimeId: 'runtime-work-live', storedSessionId: 'stored-work-bot' })
    expect(ordinarySession).not.toHaveProperty('runtimeId')
    expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-work-bot']))
  })
})

function runtimeBindingDelegate(
  dropRuntimeBindings: (storedSessionIds: ReadonlySet<string>) => void,
  invalidateRuntimeBindings: (preserveStoredSessionIds?: ReadonlySet<string>) => void
): SessionTileDelegate {
  return {
    archiveSession: vi.fn(),
    branchSession: vi.fn(),
    branchSessionAtMessage: vi.fn(async () => true),
    deleteSession: vi.fn(),
    executeSlash: vi.fn(),
    interruptSession: vi.fn(),
    resumeTile: vi.fn(),
    submitToSession: vi.fn(),
    updateSession: vi.fn(),
    dropRuntimeBindings,
    invalidateRuntimeBindings
  }
}

describe('resetRouteOwnedTileRuntimeBindings', () => {
  afterEach(() => {
    $sessionTiles.set([])
  })

  it('drops only tiles owned by the reopened route and leaves ambient tiles bound', () => {
    const invalidateRuntimeBindings = vi.fn()
    const dropRuntimeBindings = vi.fn()
    setSessionTileDelegate(runtimeBindingDelegate(dropRuntimeBindings, invalidateRuntimeBindings))
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'local', mode: 'local', profile: 'writer', targetProfile: 'writer' },
        runtimeId: 'runtime-writer-bot',
        storedSessionId: 'stored-writer-bot',
        workspaceMode: 'bots'
      },
      {
        ownerRoute: { connectionId: 'local', mode: 'local', profile: 'coder', targetProfile: 'coder' },
        runtimeId: 'runtime-coder-bot',
        storedSessionId: 'stored-coder-bot',
        workspaceMode: 'bots'
      },
      { runtimeId: 'runtime-ambient', storedSessionId: 'stored-ambient' }
    ])

    resetRouteOwnedTileRuntimeBindings({ connectionId: 'local', profile: 'writer' })

    const [writerBot, coderBot, ambient] = $sessionTiles.get()

    expect(writerBot).toMatchObject({ storedSessionId: 'stored-writer-bot' })
    expect(writerBot).not.toHaveProperty('runtimeId')
    expect(coderBot).toMatchObject({ runtimeId: 'runtime-coder-bot' })
    expect(ambient).toMatchObject({ runtimeId: 'runtime-ambient' })
    expect(dropRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-writer-bot']))
    expect(invalidateRuntimeBindings).not.toHaveBeenCalled()
  })

  it('is a no-op when no open tile belongs to the reopened route', () => {
    const invalidateRuntimeBindings = vi.fn()
    const dropRuntimeBindings = vi.fn()
    setSessionTileDelegate(runtimeBindingDelegate(dropRuntimeBindings, invalidateRuntimeBindings))
    const tiles = [{ runtimeId: 'runtime-ambient', storedSessionId: 'stored-ambient' }]
    $sessionTiles.set(tiles)

    resetRouteOwnedTileRuntimeBindings({ connectionId: 'local', profile: 'writer' })

    expect($sessionTiles.get()).toBe(tiles)
    expect(dropRuntimeBindings).not.toHaveBeenCalled()
    expect(invalidateRuntimeBindings).not.toHaveBeenCalled()
  })
})

describe('SessionTile workspace scope', () => {
  afterEach(() => {
    $activeGatewayProfile.set('default')
    $layoutTree.set(null)
    $selectedStoredSessionId.set(null)
    $sessionTiles.set([])
  })

  it('persists a sessions-mode owner route so a branch child tile pins its owning socket', () => {
    const ownerRoute = { connectionId: '100-125-133-71-9119', mode: 'remote' as const, profile: 'default' }

    openSessionTile('branch-child', 'center', undefined, null, { ownerRoute, workspaceMode: 'sessions' })

    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({ ownerRoute, storedSessionId: 'branch-child', workspaceMode: 'sessions' })
    ])
  })

  it('keeps an existing sessions-mode owner route on a route-less re-scope', () => {
    const ownerRoute = { connectionId: '100-125-133-71-9119', mode: 'remote' as const, profile: 'default' }

    openSessionTile('branch-child', 'center', undefined, null, { ownerRoute, workspaceMode: 'sessions' })
    // A plain sidebar re-open routes through setSessionTileWorkspaceScope with
    // no route — absence of information, not a revocation.
    setSessionTileWorkspaceScope('branch-child', { workspaceMode: 'sessions' })

    expect($sessionTiles.get()).toEqual([expect.objectContaining({ ownerRoute, storedSessionId: 'branch-child' })])
  })

  it('stores an exact Bot owner and keeps it through placement patches', () => {
    const ownerRoute = {
      connectionId: 'connection-a',
      mode: 'remote' as const,
      profile: 'default',
      targetProfile: 'backend-default'
    }

    const scope = { ownerRoute, workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::default' }

    openSessionTile('bot-chat', 'right', undefined, undefined, scope)
    patchSessionTile('bot-chat', { dir: 'left' })

    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({
        dir: 'left',
        ownerRoute,
        storedSessionId: 'bot-chat',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'connection-a::default'
      })
    ])
  })

  it('allows a Bot-scoped tab when the same stored session is hidden in Sessions main', () => {
    const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::default' }

    $selectedStoredSessionId.set('bot-chat')
    openSessionTile('bot-chat', 'center', undefined, undefined, scope)
    $layoutTree.set(group(['workspace', tilePane('bot-chat')], { active: 'workspace', id: 'main' }))

    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({
        storedSessionId: 'bot-chat',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'connection-a::default'
      })
    ])
    expect(focusOpenSession('bot-chat', scope)).toBe('tile')
  })

  it('splits a Bot chat loaded in MAIN instead of silently no-oping the drop', () => {
    const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'bot:connection-a::alpha' }

    $selectedStoredSessionId.set('bot-chat')
    // A real open records the bot scope on the MAIN chat (which has no tile
    // to carry it). The drag handler then commits the drop with NO explicit
    // scope — the tab it drags is the workspace pane itself.
    setSessionTileWorkspaceScope('bot-chat', scope)
    openSessionTile('bot-chat', 'right', 'workspace', undefined)

    // The minted tile registers its pane (watchSessionTiles) and the drop
    // hint's reveal adopts it — here, the tree that adoption produces.
    $layoutTree.set(group(['workspace', tilePane('bot-chat')], { id: 'workspace-group' }))

    expect(focusOpenSession('bot-chat', scope)).toBe('tile')
    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({
        storedSessionId: 'bot-chat',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'bot:connection-a::alpha'
      })
    ])
  })

  it('fronts the existing tab when compaction rotated the tip id — never a duplicate', () => {
    // The tile was opened when seg-2 was the tip; the conversation has since
    // rotated to seg-3 (projected row carries the full chain). Opening the
    // new tip must front that tile, not open the same chat twice.
    setSessions([{ _lineage_ids: ['seg-1', 'seg-2', 'seg-3'], _lineage_root_id: 'seg-1', id: 'seg-3' } as never])
    openSessionTile('seg-2')
    $layoutTree.set(group(['workspace', tilePane('seg-2')], { active: 'workspace', id: 'main' }))

    expect(focusOpenSession('seg-3')).toBe('tile')
    expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['seg-2'])

    // The open path dedupes through the same lineage test.
    openSessionTile('seg-3')
    expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['seg-2'])
    setSessions([])
  })

  it('reports the workspace scope of the focused Bot session tab', () => {
    const scope = {
      ownerRoute: { connectionId: 'connection-a', profile: 'default' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'connection-a::default',
      workspaceTabTitle: 'Bot Chat'
    }

    openSessionTile('bot-chat', 'center', undefined, undefined, scope)
    $layoutTree.set(group(['workspace', tilePane('bot-chat')], { active: tilePane('bot-chat'), id: 'main' }))

    expect(focusedSessionWorkspaceScope()).toEqual(scope)
  })

  it('keeps Bot tabs while a profile publication swaps the Sessions bucket', () => {
    const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::writer' }

    openSessionTile('sessions-chat')
    openSessionTile('bot-chat', 'center', undefined, undefined, scope)
    $activeGatewayProfile.set('other-profile')

    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({
        storedSessionId: 'bot-chat',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'connection-a::writer'
      })
    ])
  })

  it('re-scopes an existing tile without changing its placement', () => {
    openSessionTile('chat', 'bottom', 'workspace')

    expect(
      setSessionTileWorkspaceScope('chat', {
        workspaceMode: 'bots',
        workspaceOwnerKey: 'connection-b::default'
      })
    ).toBe(true)
    expect($sessionTiles.get()[0]).toMatchObject({
      anchor: 'workspace',
      dir: 'bottom',
      workspaceMode: 'bots',
      workspaceOwnerKey: 'connection-b::default'
    })
  })

  it('preserves an existing Bot tile scope when moving it without an explicit scope', () => {
    const scope = {
      ownerRoute: {
        connectionId: 'connection-a',
        mode: 'remote' as const,
        profile: 'default',
        targetProfile: 'default'
      },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'bot:connection-a::default',
      workspaceTabTitle: 'Bot chat'
    }

    openSessionTile('bot-chat', 'right', undefined, undefined, scope)
    $layoutTree.set(group(['workspace', 'session-tile:bot-chat'], { id: 'workspace-group' }))
    // A split drag re-docks the tab with no scope (session-drag onCommit).
    openSessionTile('bot-chat', 'left', 'workspace')

    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({
        anchor: 'workspace',
        dir: 'left',
        ownerRoute: scope.ownerRoute,
        storedSessionId: 'bot-chat',
        workspaceMode: 'bots',
        workspaceOwnerKey: scope.workspaceOwnerKey,
        workspaceTabTitle: 'Bot chat'
      })
    ])

    // An explicit scope from the caller still wins over the tile's current one.
    openSessionTile('bot-chat', 'right', 'workspace', undefined, { workspaceMode: 'sessions' })

    expect($sessionTiles.get()).toEqual([
      expect.objectContaining({ dir: 'right', storedSessionId: 'bot-chat', workspaceMode: 'sessions' })
    ])
    expect($sessionTiles.get()[0]).not.toHaveProperty('workspaceOwnerKey', scope.workspaceOwnerKey)
  })

  it('preserves workspace scope while dropping a stale runtime binding', () => {
    $sessionTiles.set([
      {
        runtimeId: 'runtime-dead',
        storedSessionId: 'bot-chat',
        workspaceMode: 'bots',
        workspaceOwnerKey: 'connection-a::default'
      }
    ])

    resetTileRuntimeBindings()

    expect($sessionTiles.get()[0]).toEqual({
      anchor: undefined,
      before: undefined,
      dir: undefined,
      storedSessionId: 'bot-chat',
      workspaceMode: 'bots',
      workspaceOwnerKey: 'connection-a::default'
    })
  })
})

describe('frontMainIfSelected (#125899 — Bot row click while its chat sits in main)', () => {
  const activePane = () => {
    const tree = $layoutTree.get()

    return tree?.type === 'group' ? tree.active : null
  }

  afterEach(() => {
    $layoutTree.set(null)
    $selectedStoredSessionId.set(null)
    $sessionTiles.set([])
  })

  it('fronts the workspace pane over another bot tile when main holds the chat', () => {
    // The promoted-into-main state: closing main dropped the bot tile and
    // loaded its chat as the primary; the zone sits on another bot tile.
    $selectedStoredSessionId.set('bot-chat')
    $layoutTree.set(group(['workspace', tilePane('other-bot')], { active: tilePane('other-bot'), id: 'main' }))

    expect(frontMainIfSelected('bot-chat')).toBe(true)
    expect(activePane()).toBe('workspace')
  })

  it('matches a compression-lineage alias of the chat main holds', () => {
    setSessions([{ _lineage_ids: ['seg-1', 'seg-2'], _lineage_root_id: 'seg-1', id: 'seg-2' } as never])
    $selectedStoredSessionId.set('seg-2')
    $layoutTree.set(group(['workspace'], { id: 'main' }))

    expect(frontMainIfSelected('seg-1')).toBe(true)
    setSessions([])
  })

  it('reports false and fronts nothing when main holds another chat', () => {
    $selectedStoredSessionId.set('other-chat')
    $layoutTree.set(group(['workspace', tilePane('other-bot')], { active: tilePane('other-bot'), id: 'main' }))

    expect(frontMainIfSelected('bot-chat')).toBe(false)
    expect(activePane()).toBe(tilePane('other-bot'))
  })

  it('reports false when main holds nothing', () => {
    expect(frontMainIfSelected('bot-chat')).toBe(false)
  })
})

describe('focusWorkspaceOwnerSessionTile', () => {
  const botA = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'bot:a' }
  const botB = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'bot:b' }

  afterEach(() => {
    forgetActivePane(workspaceScopeKey('bots', 'bot:a'))
    $layoutTree.set(null)
    $sessionTiles.set([])
  })

  it('reports null for an owner with no open tile — the caller opens something', () => {
    openSessionTile('other-bot-chat', 'center', 'workspace', undefined, botB)
    openSessionTile('sessions-chat')

    expect(focusWorkspaceOwnerSessionTile('bot:a')).toBeNull()
  })

  it('fronts the tab the owner last had active and reports its stored id', () => {
    openSessionTile('older-thread', 'center', 'workspace', undefined, botA)
    openSessionTile('newer-thread', 'center', 'workspace', undefined, botA)
    $layoutTree.set(
      group(['workspace', tilePane('older-thread'), tilePane('newer-thread')], { active: 'workspace', id: 'main' })
    )
    rememberActivePane(workspaceScopeKey('bots', 'bot:a'), tilePane('older-thread'))

    expect(focusWorkspaceOwnerSessionTile('bot:a')).toBe('older-thread')
    expect(findGroupOfPane($layoutTree.get()!, tilePane('older-thread'))?.active).toBe(tilePane('older-thread'))
  })

  it('falls back to the most recently opened tab when nothing is remembered', () => {
    openSessionTile('older-thread', 'center', 'workspace', undefined, botA)
    openSessionTile('newer-thread', 'center', 'workspace', undefined, botA)
    $layoutTree.set(
      group(['workspace', tilePane('older-thread'), tilePane('newer-thread')], { active: 'workspace', id: 'main' })
    )

    expect(focusWorkspaceOwnerSessionTile('bot:a')).toBe('newer-thread')
    expect(findGroupOfPane($layoutTree.get()!, tilePane('newer-thread'))?.active).toBe(tilePane('newer-thread'))
  })

  it('ignores a remembered tab that has since been closed', () => {
    openSessionTile('closed-bot-chat', 'center', 'workspace', undefined, botA)
    openSessionTile('thread', 'center', 'workspace', undefined, botA)
    rememberActivePane(workspaceScopeKey('bots', 'bot:a'), tilePane('closed-bot-chat'))
    $sessionTiles.set($sessionTiles.get().filter(t => t.storedSessionId !== 'closed-bot-chat'))
    $layoutTree.set(group(['workspace', tilePane('thread')], { active: 'workspace', id: 'main' }))

    expect(focusWorkspaceOwnerSessionTile('bot:a')).toBe('thread')
  })

  it("never crosses owners: another bot's open tabs do not count", () => {
    openSessionTile('other-bot-chat', 'center', 'workspace', undefined, botB)

    expect(focusWorkspaceOwnerSessionTile('bot:a')).toBeNull()
    expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['other-bot-chat'])
  })

  describe('staleness probe (#90102): the tile bucket reconciles with backend truth before it wins', () => {
    it('discards a stale tile and reports null so the caller runs its authoritative open', () => {
      openSessionTile('stale-bot-chat', 'center', 'workspace', undefined, botA)

      expect(focusWorkspaceOwnerSessionTile('bot:a', tile => tile.storedSessionId === 'stale-bot-chat')).toBeNull()
      // Discard, not close: resurrecting the tile would just front the stale
      // session again on the next click.
      expect($sessionTiles.get()).toEqual([])
    })

    it('fronts the surviving fresh tile after discarding the stale one', () => {
      openSessionTile('stale-bot-chat', 'center', 'workspace', undefined, botA)
      openSessionTile('live-thread', 'center', 'workspace', undefined, botA)
      $layoutTree.set(
        group(['workspace', tilePane('stale-bot-chat'), tilePane('live-thread')], { active: 'workspace', id: 'main' })
      )
      // The stale tile is even the remembered one — the exact stuck shape.
      rememberActivePane(workspaceScopeKey('bots', 'bot:a'), tilePane('stale-bot-chat'))

      expect(focusWorkspaceOwnerSessionTile('bot:a', tile => tile.storedSessionId === 'stale-bot-chat')).toBe(
        'live-thread'
      )
      expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['live-thread'])
    })

    it("only judges the probed owner's tiles — other owners keep theirs", () => {
      openSessionTile('other-bot-chat', 'center', 'workspace', undefined, botB)
      openSessionTile('stale-bot-chat', 'center', 'workspace', undefined, botA)

      expect(focusWorkspaceOwnerSessionTile('bot:a', () => true)).toBeNull()
      expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['other-bot-chat'])
    })

    it('a throwing probe keeps the tile — reconciliation must not break the click', () => {
      openSessionTile('bot-chat', 'center', 'workspace', undefined, botA)
      $layoutTree.set(group(['workspace', tilePane('bot-chat')], { active: 'workspace', id: 'main' }))

      expect(
        focusWorkspaceOwnerSessionTile('bot:a', () => {
          throw new Error('probe blew up')
        })
      ).toBe('bot-chat')
      expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['bot-chat'])
    })

    it('fronts a visible tile without a probe', () => {
      openSessionTile('bot-chat', 'center', 'workspace', undefined, botA)
      $layoutTree.set(group(['workspace', tilePane('bot-chat')], { active: 'workspace', id: 'main' }))

      expect(focusWorkspaceOwnerSessionTile('bot:a')).toBe('bot-chat')
      expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['bot-chat'])
    })
  })
})

describe('closeAllOpenSessionTiles persists Bot Mode Close All (#94137)', () => {
  afterEach(() => {
    $activeGatewayProfile.set('default')
    $layoutTree.set(null)
    $sessionTiles.set([])
  })
  it('drops persisted bot tiles so a roster/profile rehydrate cannot restore them', () => {
    openSessionTile('chat-a', 'center', 'workspace', undefined, {
      workspaceMode: 'bots',
      workspaceOwnerKey: 'bot:a'
    })
    openSessionTile('chat-b', 'center', 'workspace', undefined, {
      workspaceMode: 'bots',
      workspaceOwnerKey: 'bot:b'
    })
    $layoutTree.set(group(['workspace', tilePane('chat-a'), tilePane('chat-b')], { active: 'workspace', id: 'main' }))
    closeAllOpenSessionTiles('workspace')
    expect($sessionTiles.get()).toEqual([])
    // Profile swap re-reads the shared Bot bucket. Close All must have
    // emptied it, not only dismissed the tree panes.
    $activeGatewayProfile.set('other-profile')
    expect($sessionTiles.get()).toEqual([])
    $activeGatewayProfile.set('default')
    expect($sessionTiles.get()).toEqual([])
  })
  it('leaves session tiles stacked in a different zone open', () => {
    openSessionTile('keep', 'right', 'workspace')
    openSessionTile('close-me', 'center', 'workspace')
    $layoutTree.set(
      split('row', [
        group(['workspace', tilePane('close-me')], { active: 'workspace', id: 'main' }),
        group([tilePane('keep')], { active: tilePane('keep'), id: 'right' })
      ])
    )
    closeAllOpenSessionTiles('workspace')
    expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['keep'])
  })
})

describe('dropTilesForProfile', () => {
  const TILES_KEY = 'hermes.desktop.sessionTiles.v2'
  const BOTS_BUCKET = '__bots_workspace__'

  const storedTiles = (): Record<string, unknown> => {
    const raw = window.localStorage.getItem(TILES_KEY)

    return raw ? (JSON.parse(raw) as Record<string, unknown>) : {}
  }

  // The tile buckets are module-private and other suites leave persisted
  // entries behind, so each test re-imports a FRESH session-states module
  // (empty tilesByProfile + empty storage) instead of fighting the residue —
  // the same isolation the browser gets between app launches.
  type SessionStates = typeof SessionStatesModule
  let mod: SessionStates
  let activeGatewayProfile: { set: (name: string) => void }
  beforeEach(async () => {
    window.localStorage.clear()
    vi.resetModules()
    // Re-import the module graph so the private tile buckets start empty; the
    // profile atom session-states subscribes to is the freshly loaded one too.
    mod = await import('@/store/session-states')
    const profile = await import('@/store/profile')
    activeGatewayProfile = profile.$activeGatewayProfile
    activeGatewayProfile.set('default')
    mod.$sessionTiles.set([])
  })
  afterEach(() => {
    window.localStorage.clear()
    $activeGatewayProfile.set('default')
    $layoutTree.set(null)
    $selectedStoredSessionId.set(null)
    $sessionTiles.set([])
  })
  it("drops the deleted profile's persisted session tiles from memory and storage", () => {
    activeGatewayProfile.set('worker')
    mod.openSessionTile('worker-session-1')
    mod.openSessionTile('worker-session-2', 'left')
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['worker-session-1', 'worker-session-2'])
    expect(storedTiles()).toHaveProperty('worker')
    mod.dropTilesForProfile('worker')
    expect(mod.$sessionTiles.get()).toEqual([])
    expect(storedTiles()).not.toHaveProperty('worker')
    // Session tiles of another profile survive the drop.
    activeGatewayProfile.set('writer')
    mod.openSessionTile('writer-session-1')
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['writer-session-1'])
    expect(storedTiles()).toHaveProperty('writer')
  })
  it("drops Bot Mode tiles owned by a locally-deleted profile and keeps the other bots' tiles", () => {
    mod.openSessionTile('bot-chat-1', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'researcher-1' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'researcher-1'
    })
    mod.openSessionTile('bot-chat-2', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'writer-1' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'writer-1'
    })
    mod.dropTilesForProfile('researcher-1')
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-chat-2'])
    expect(
      (storedTiles()[BOTS_BUCKET] as Array<{ storedSessionId: string }>).map(tile => tile.storedSessionId)
    ).toEqual(['bot-chat-2'])
  })
  it('drops a source-scoped bot tile only for the exact route and keeps same-name agents elsewhere', () => {
    const route = {
      connectionId: 'source-a',
      mode: 'remote' as const,
      profile: 'worker',
      targetProfile: 'backend-worker'
    }

    mod.openSessionTile('bot-a', 'right', undefined, undefined, {
      ownerRoute: route,
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'source-a::worker'
    })
    mod.openSessionTile('bot-b', 'right', undefined, undefined, {
      ownerRoute: {
        connectionId: 'source-b',
        mode: 'remote' as const,
        profile: 'worker',
        targetProfile: 'backend-worker'
      },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'source-b::worker'
    })
    mod.openSessionTile('bot-local', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'worker' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'local::worker'
    })
    mod.dropTilesForProfile('worker', route)
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-b', 'bot-local'])
    expect(
      (storedTiles()[BOTS_BUCKET] as Array<{ storedSessionId: string }>).map(tile => tile.storedSessionId)
    ).toEqual(['bot-b', 'bot-local'])
  })

  it('keeps a same-named bot tile owned by another connection when a local profile is deleted', () => {
    mod.openSessionTile('bot-local', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'copilot' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'copilot'
    })
    mod.openSessionTile('bot-remote', 'right', undefined, undefined, {
      ownerRoute: {
        connectionId: 'work-vps',
        mode: 'remote' as const,
        profile: 'copilot',
        targetProfile: 'copilot'
      },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'work-vps::copilot'
    })

    mod.dropTilesForProfile('copilot')

    // Only the LOCAL connection's tile points at the deleted local profile; the
    // same-named agent on another connection keeps its tile and conversation.
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-remote'])
    expect(
      (storedTiles()[BOTS_BUCKET] as Array<{ storedSessionId: string }>).map(tile => tile.storedSessionId)
    ).toEqual(['bot-remote'])
  })

  it('normalizes whitespace in the deleted identity on both delete paths', () => {
    mod.openSessionTile('bot-local', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'press-bot' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'press-bot'
    })
    mod.openSessionTile('bot-routed', 'right', undefined, undefined, {
      ownerRoute: {
        connectionId: 'source-a',
        mode: 'remote' as const,
        profile: 'worker',
        targetProfile: 'backend-worker'
      },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'source-a::worker'
    })

    // Non-route delete with a whitespace-padded name matches the trimmed tile.
    mod.dropTilesForProfile('   press-bot   ')
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-routed'])

    // Route delete with padded route fields matches the exact route's tile.
    mod.dropTilesForProfile('worker', {
      connectionId: ' source-a ',
      profile: '  worker  ',
      targetProfile: '  backend-worker  '
    })
    expect(mod.$sessionTiles.get()).toEqual([])
  })

  it('keeps profile identity case-exact on both delete paths', () => {
    mod.openSessionTile('bot-local', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'press-bot' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'press-bot'
    })
    mod.openSessionTile('bot-routed', 'right', undefined, undefined, {
      ownerRoute: {
        connectionId: 'source-a',
        mode: 'remote' as const,
        profile: 'worker',
        targetProfile: 'backend-worker'
      },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'source-a::worker'
    })

    // normalizeProfileKey trims but never lowercases: a differing case is a
    // different profile identity, consistently in the local and route branches.
    mod.dropTilesForProfile('PRESS-BOT')
    mod.dropTilesForProfile('worker', {
      connectionId: 'source-a',
      profile: 'WORKER',
      targetProfile: 'backend-worker'
    })

    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-local', 'bot-routed'])
  })

  it('drops a legacy Bot tile whose ownerRoute predates the connectionId field', () => {
    // Tiles persisted before ownerRoute.connectionId existed (pre-#94235) carry
    // no connection id at all. `String(undefined ?? '').trim()` yields '', so a
    // local-delete branch comparing against `=== 'local'` never matches and the
    // tile survives every delete, resurrecting the deleted profile on relaunch
    // (hermes-agent#94235). The branch must treat a missing id as local.
    mod.openSessionTile('bot-legacy', 'right', undefined, undefined, {
      ownerRoute: { mode: 'local' as const, profile: 'press-bot' } as unknown as SessionProfileRoute,
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'press-bot'
    })

    mod.dropTilesForProfile('press-bot')

    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual([])
    expect(storedTiles()).not.toHaveProperty(BOTS_BUCKET)
  })

  it("treats a missing connectionId as the canonical 'local' spelling", () => {
    // The local-delete branch compares ownerConnection to 'local', and
    // local-mode owner routes record that same spelling. No renderer-importable
    // constant exists (LOCAL_CONNECTION_ID lives in the electron main process),
    // so this pins the two spellings together: legacy (no id), canonical
    // ('local'), and divergent ('Local') tiles differ only in this field, and
    // only the first two may be dropped by a local delete. Renaming either side
    // fails the suite before it can silently orphan local Bot tiles
    // (Enough1122 review of #94426).
    mod.openSessionTile('bot-legacy', 'right', undefined, undefined, {
      ownerRoute: { mode: 'local' as const, profile: 'press-bot' } as unknown as SessionProfileRoute,
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'press-bot'
    })
    mod.openSessionTile('bot-canonical', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'local', mode: 'local' as const, profile: 'press-bot' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'press-bot'
    })
    mod.openSessionTile('bot-divergent', 'right', undefined, undefined, {
      ownerRoute: { connectionId: 'Local', mode: 'local' as const, profile: 'press-bot' },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'press-bot'
    })

    mod.dropTilesForProfile('press-bot')

    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-divergent'])
  })

  it('throws on a route without profile instead of silently falling into the local-delete branch', () => {
    // A caller passing a route with only connectionId/targetProfile would
    // silently take the local branch and start requiring
    // `ownerConnection === 'local'` — dropping nothing remotely owned while
    // appearing to succeed. Both current call sites always populate profile, so
    // refuse the malformed shape loudly (Enough1122 review of #94426).
    mod.openSessionTile('bot-remote', 'right', undefined, undefined, {
      ownerRoute: {
        connectionId: 'work-vps',
        mode: 'remote' as const,
        profile: 'copilot',
        targetProfile: 'copilot'
      },
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'work-vps::copilot'
    })

    expect(() => mod.dropTilesForProfile('copilot', { connectionId: 'work-vps', targetProfile: 'copilot' })).toThrow(
      /route without profile/
    )
    expect(mod.$sessionTiles.get().map(tile => tile.storedSessionId)).toEqual(['bot-remote'])
  })

  // #108679: a tile record whose anchor is its OWN pane id is
  // self-referential — the re-dock target can never exist at adoption time,
  // so the tile falls through to an arbitrary same-placement neighbor
  // instead of the recorded layout. Loading must rewrite it to the
  // workspace anchor (the same surface an anchorless tile re-docks against)
  // while a REAL cross-tile anchor survives the round-trip.
  it('rewrites a self-anchored tile record to the workspace anchor at load', async () => {
    window.localStorage.setItem(
      TILES_KEY,
      JSON.stringify({
        default: [
          // Self-referential: anchor === the tile's own pane id.
          { anchor: 'session-tile:20260912_080117', storedSessionId: '20260912_080117' },
          // Legitimate: docked beside another tile.
          { anchor: 'session-tile:20260912_080117', storedSessionId: '20260912_080118' },
          // Legitimate: docked beside the workspace.
          { anchor: 'workspace', storedSessionId: '20260912_080119' }
        ]
      })
    )

    // Storage is read at module load — reset and re-import after seeding it.
    vi.resetModules()

    const fresh = await import('@/store/session-states')
    const tiles = fresh.$sessionTiles.get()
    const byId = new Map(tiles.map(tile => [tile.storedSessionId, tile]))

    // The self-anchor is dropped (the mirror re-docks those tiles against
    // the workspace by default); the other two anchors round-trip intact.
    expect(tiles).toHaveLength(3)
    expect(byId.get('20260912_080117')!.anchor).toBeUndefined()
    expect(byId.get('20260912_080118')!.anchor).toBe('session-tile:20260912_080117')
    expect(byId.get('20260912_080119')!.anchor).toBe('workspace')
  })
})

describe('releaseSessionTranscript', () => {
  afterEach(() => {
    $sessionStates.set({})
  })

  it('normalizes legacy state whose messages field is undefined', () => {
    const legacy = { busy: false, storedSessionId: 'stored' } as ClientSessionState
    $sessionStates.set({ runtime: legacy })

    expect(() => releaseSessionTranscript('runtime')).not.toThrow()
    expect($sessionStates.get().runtime).toEqual({ ...legacy, messages: [] })
  })
})

describe('orderTilesByTree', () => {
  it('no-ops (null) without a tree or below two tiles', () => {
    expect(orderTilesByTree(null, [tile('a'), tile('b')])).toBeNull()
    expect(orderTilesByTree(group([tilePane('a')]), [tile('a')])).toBeNull()
  })

  it('reorders tiles to layout-tree encounter order across a split', () => {
    const tree = split('row', [group(['workspace', tilePane('b')]), group([tilePane('a')])])

    expect(orderTilesByTree(tree, [tile('a'), tile('b')])).toEqual([tile('b'), tile('a')])
  })

  it('returns null when the array already matches strip order (skip persist)', () => {
    const tree = split('row', [group([tilePane('b')]), group([tilePane('a')])])

    expect(orderTilesByTree(tree, [tile('b'), tile('a')])).toBeNull()
  })

  it('sorts not-yet-adopted tiles after placed ones, stably', () => {
    const tree = group(['workspace', tilePane('b')])

    expect(orderTilesByTree(tree, [tile('a'), tile('b'), tile('c')])).toEqual([tile('b'), tile('a'), tile('c')])
  })
})

describe('selectionHomesToWorkspace', () => {
  const tiles = [tile('a'), tile('b')]

  it('homes for a null selection or a non-tile session', () => {
    expect(selectionHomesToWorkspace(null, tiles)).toBe(true)
    expect(selectionHomesToWorkspace('c', tiles)).toBe(true)
  })

  it('skips homing when the selected id is already an open tile', () => {
    expect(selectionHomesToWorkspace('a', tiles)).toBe(false)
  })
})

describe('nextSessionTileForWorkspace (⌘W promotion source)', () => {
  afterEach(() => {
    $layoutTree.set(null)
    $sessionTiles.set([])
  })

  it('prefers a tile stacked WITH the workspace tab (nearest-out)', () => {
    $layoutTree.set(group(['workspace', tilePane('a'), tilePane('b')], { active: 'workspace', id: 'main' }))
    $sessionTiles.set([tile('a'), tile('b')])

    expect(nextSessionTileForWorkspace()).toBe('a')
  })

  it('side-by-side layout: a tile in ANOTHER zone still promotes instead of dropping main to a fresh draft (#88924)', () => {
    // main zone holds only the workspace; the session tile lives in its own
    // zone beside it — db's three-pane report shape.
    $layoutTree.set(
      split('row', [
        group(['workspace'], { active: 'workspace', id: 'main' }),
        group([tilePane('side')], { active: tilePane('side'), id: 'right' })
      ])
    )
    $sessionTiles.set([tile('side')])

    expect(nextSessionTileForWorkspace()).toBe('side')
  })

  it('returns null when no live tile exists anywhere in the tree', () => {
    $layoutTree.set(
      split('row', [
        group(['workspace'], { active: 'workspace', id: 'main' }),
        group([tilePane('stale')], { active: tilePane('stale'), id: 'right' })
      ])
    )
    // Pane persisted in the tree but its tile is gone — must not promote a ghost.
    $sessionTiles.set([])

    expect(nextSessionTileForWorkspace()).toBe(null)
  })
})

describe('boot-restore selection homing (⌘R tab persistence)', () => {
  const mainGroup = () => group(['workspace', tilePane('t')], { active: tilePane('t'), id: 'main' })

  const activePane = () => {
    const tree = $layoutTree.get()

    return tree?.type === 'group' ? tree.active : null
  }

  it('a normal selection change fronts the workspace tab over an active tile', () => {
    $layoutTree.set(mainGroup())
    $selectedStoredSessionId.set('nav-1')

    expect(activePane()).toBe('workspace')
  })

  it('markSelectionRestore skips homing exactly once, so the persisted active tab survives a reload', () => {
    $layoutTree.set(mainGroup())
    markSelectionRestore()
    $selectedStoredSessionId.set('boot-1')

    // Boot restore: the tile tab the user reloaded on stays fronted.
    expect(activePane()).toBe(tilePane('t'))

    // One-shot consumed: the next selection change is a real navigation.
    $selectedStoredSessionId.set('nav-2')
    expect(activePane()).toBe('workspace')
  })
})

describe('$focusedStoredSessionId in Bot Mode (#96062)', () => {
  afterEach(() => {
    $layoutTree.set(null)
    $selectedStoredSessionId.set(null)
    setWorkspaceScope('sessions')
    // The cwd-ladder tests below load rows into slices the describe never
    // touched before; leave every store as empty as they found it.
    setSessions([])
    setUnlistedSessionOwnerRows([])
    $projectTree.set([])
  })

  it('a Bots-pane click keeps the main-zone bot tile focused instead of collapsing to a null selection edge', () => {
    // Bot chats open as TILES and never set $selectedStoredSessionId. Clicking
    // a roster row moves the interaction tracker to the sidebar group, whose
    // active pane is chrome ('hermes-bots:pane'), not a session tile. The old
    // derivation then fell back to the null primary selection and published a
    // NULL "focused session" edge — which the Bots plugin read as "the chat
    // lost the center", releasing its open claim and re-asserting the Bots
    // home over the still-visible chat (the reported "jumps to the list").
    setWorkspaceScope('bots', 'bot:b')
    $selectedStoredSessionId.set(null)
    $layoutTree.set(
      split('row', [
        group(['sessions', 'hermes-bots:pane'], { active: 'hermes-bots:pane', id: 'grp-sessions' }),
        group(['workspace', tilePane('chat-b')], { active: tilePane('chat-b'), id: 'grp-main' })
      ])
    )
    noteActiveTreeGroup('grp-sessions')

    expect($focusedStoredSessionId.get()).toBe('chat-b')
  })

  it('the main-zone tile also answers while the tracker sits on the workspace tab itself', () => {
    setWorkspaceScope('bots', 'bot:b')
    $selectedStoredSessionId.set(null)
    $layoutTree.set(group(['workspace', tilePane('chat-b')], { active: tilePane('chat-b'), id: 'grp-main' }))
    noteActiveTreeGroup('grp-main')

    expect($focusedStoredSessionId.get()).toBe('chat-b')
  })

  it('a closed bot chat (no tile in main) still falls back to the selection', () => {
    setWorkspaceScope('bots', 'bot:b')
    $selectedStoredSessionId.set(null)
    $layoutTree.set(
      split('row', [
        group(['sessions', 'hermes-bots:pane'], { active: 'hermes-bots:pane', id: 'grp-sessions' }),
        group(['workspace'], { active: 'workspace', id: 'grp-main' })
      ])
    )
    noteActiveTreeGroup('grp-sessions')

    // No tile owns the main zone — the chat was closed — so the null edge is
    // genuine and must still surface (that is what lets the Bots home return).
    expect($focusedStoredSessionId.get()).toBeNull()
  })

  it('sessions mode retains the active main-zone tile when the tracker sits on side chrome', () => {
    $selectedStoredSessionId.set('primary-1')
    $layoutTree.set(
      split('row', [
        group(['sessions'], { active: 'sessions', id: 'grp-sessions' }),
        group(['workspace', tilePane('stacked')], { active: tilePane('stacked'), id: 'grp-main' })
      ])
    )
    noteActiveTreeGroup('grp-sessions')

    expect($workspaceMode.get()).toBe('sessions')
    expect($focusedStoredSessionId.get()).toBe('stacked')
  })

  it('computes $focusedWorkspaceCwd from the focused tile session state or sessions list', () => {
    $selectedStoredSessionId.set('primary-1')
    setSessions([{ cwd: '/repo-stacked', id: 'stacked' } as any])
    $sessionTiles.set([{ storedSessionId: 'stacked', runtimeId: 'rt-stacked', workspaceMode: 'sessions' } as any])
    $sessionStates.set({
      'rt-stacked': { cwd: '/repo-stacked' } as any
    })
    $layoutTree.set(
      split('row', [
        group(['files'], { active: 'files', id: 'grp-files' }),
        group(['workspace', tilePane('stacked')], { active: tilePane('stacked'), id: 'grp-main' })
      ])
    )
    noteActiveTreeGroup('grp-files')

    expect($focusedStoredSessionId.get()).toBe('stacked')
    expect($focusedWorkspaceCwd.get()).toBe('/repo-stacked')
  })

  it('falls back to sessions list cwd for primary session when workspaceCwdOwner is mismatched', () => {
    $selectedStoredSessionId.set('primary-1')
    $workspaceCwdOwner.set('other-session-from-different-project')
    setCurrentCwd('/repo-other')
    setSessions([{ cwd: '/repo-primary-project', id: 'primary-1' } as any])
    $sessionTiles.set([])
    $sessionStates.set({})
    $layoutTree.set(split('row', [group(['workspace'], { active: 'workspace', id: 'grp-main' })]))
    noteActiveTreeGroup('grp-main')

    expect($focusedStoredSessionId.get()).toBe('primary-1')
    expect($focusedWorkspaceCwd.get()).toBe('/repo-primary-project')
  })

  it('resolves a cold focused tile cwd from the unlisted owner rows, not only the paginated recents page (#76535)', () => {
    // A cold restored tile outside the recents page and project preview caps
    // has no $sessions row; a resume-time by-id resolve parked its row on the
    // unlisted-owner atom, which $focusedWorkspaceCwd never searched — so
    // Files showed "No project open" for a valid tile whose cwd was known.
    $selectedStoredSessionId.set('primary-1')
    setSessions([{ cwd: '/repo-primary', id: 'primary-1' } as never])
    setUnlistedSessionOwnerRows([{ cwd: '/repo-cold', id: 'cold-4' } as never])
    $sessionTiles.set([{ storedSessionId: 'cold-4', workspaceMode: 'sessions' } as never])
    $sessionStates.set({})
    $layoutTree.set(
      split('row', [
        group(['files'], { active: 'files', id: 'grp-files' }),
        group(['workspace', tilePane('cold-4')], { active: tilePane('cold-4'), id: 'grp-main' })
      ])
    )
    noteActiveTreeGroup('grp-files')

    expect($focusedStoredSessionId.get()).toBe('cold-4')
    expect($focusedWorkspaceCwd.get()).toBe('/repo-cold')
  })

  it('resolves a cold focused tile cwd from the project tree lanes (#76535)', () => {
    // Same class, second cache: a session opened as a tab from a project
    // group lives only in the (capped) tree rows until new activity lands it
    // in recents. tileStoredRow already resolves titles this way; cwd must
    // agree.
    $selectedStoredSessionId.set('primary-1')
    setSessions([{ cwd: '/repo-primary', id: 'primary-1' } as never])
    $projectTree.set([
      {
        id: 'proj',
        label: 'proj',
        path: null,
        repos: [
          {
            id: 'repo',
            label: 'repo',
            path: null,
            groups: [
              { id: 'lane', label: 'lane', path: null, sessions: [{ cwd: '/repo-tree', id: 'tree-5' } as never] }
            ],
            sessionCount: 1
          }
        ],
        sessionCount: 1
      } as never
    ])
    $sessionTiles.set([{ storedSessionId: 'tree-5', workspaceMode: 'sessions' } as never])
    $sessionStates.set({})
    $layoutTree.set(
      split('row', [
        group(['files'], { active: 'files', id: 'grp-files' }),
        group(['workspace', tilePane('tree-5')], { active: tilePane('tree-5'), id: 'grp-main' })
      ])
    )
    noteActiveTreeGroup('grp-files')

    expect($focusedStoredSessionId.get()).toBe('tree-5')
    expect($focusedWorkspaceCwd.get()).toBe('/repo-tree')
  })

  it('widens the primary historical fallback the same way — a selected session outside recents resolves from the tree (#76535)', () => {
    // The sibling path of the same defect: the primary branch's historical
    // fallback (no owner-gated currentCwd, no live slice) scanned recents
    // only. The focused-session row ladder must agree for both branches.
    $selectedStoredSessionId.set('deep-primary')
    setCurrentCwd('')
    $sessionTiles.set([])
    $sessionStates.set({})
    $projectTree.set([
      {
        id: 'proj',
        label: 'proj',
        path: null,
        repos: [
          {
            id: 'repo',
            label: 'repo',
            path: null,
            groups: [
              {
                id: 'lane',
                label: 'lane',
                path: null,
                sessions: [{ cwd: '/repo-deep-primary', id: 'deep-primary' } as never]
              }
            ],
            sessionCount: 1
          }
        ],
        sessionCount: 1
      } as never
    ])
    $layoutTree.set(split('row', [group(['workspace'], { active: 'workspace', id: 'grp-main' })]))
    noteActiveTreeGroup('grp-main')

    expect($focusedStoredSessionId.get()).toBe('deep-primary')
    expect($focusedWorkspaceCwd.get()).toBe('/repo-deep-primary')
  })
})

describe('focusedSessionNeedsRoute', () => {
  it('routes when the session is not on screen', () => {
    expect(focusedSessionNeedsRoute(null, false)).toBe(true)
    expect(focusedSessionNeedsRoute(null, true)).toBe(true)
  })

  it('routes for the ACTIVE main session while a full page covers the workspace', () => {
    expect(focusedSessionNeedsRoute('main', true)).toBe(true)
  })

  it('skips the route when the main session is already the visible chat', () => {
    expect(focusedSessionNeedsRoute('main', false)).toBe(false)
  })

  it('never routes for a tile — its pane shows the chat on any route', () => {
    expect(focusedSessionNeedsRoute('tile', true)).toBe(false)
    expect(focusedSessionNeedsRoute('tile', false)).toBe(false)
  })
})

describe('blankDraftTile', () => {
  const bound = (storedSessionId: string, runtimeId: string): SessionTile => ({ runtimeId, storedSessionId })

  const state = (messages: number, busy = false) =>
    ({ busy, messages: Array.from({ length: messages }, (_, i) => ({ id: `m${i}` })) }) as ClientSessionState

  it('finds the open tab whose session has no messages', () => {
    const tiles = [bound('a', 'run-a'), bound('b', 'run-b')]
    const states = { 'run-a': state(3), 'run-b': state(0) }

    expect(blankDraftTile(tiles, states)).toEqual(tiles[1])
  })

  it('picks the most recent blank tab when there are several', () => {
    const tiles = [bound('a', 'run-a'), bound('b', 'run-b')]
    const states = { 'run-a': state(0), 'run-b': state(0) }

    expect(blankDraftTile(tiles, states)).toEqual(tiles[1])
  })

  it('leaves a blank-but-busy tab alone — its first turn is already in flight', () => {
    expect(blankDraftTile([bound('a', 'run-a')], { 'run-a': state(0, true) })).toBeNull()
  })

  it('treats an unbound or unpublished tile as unknown, not empty', () => {
    expect(blankDraftTile([tile('a')], {})).toBeNull()
    expect(blankDraftTile([bound('a', 'run-a')], {})).toBeNull()
  })

  it('is null when every open tab holds a conversation', () => {
    expect(blankDraftTile([bound('a', 'run-a')], { 'run-a': state(2) })).toBeNull()
    expect(blankDraftTile([], {})).toBeNull()
  })
})

// ⌘⇧T used to only restore `$sessionTiles`. Adoption inserts silently
// (activate:false), so the tab came back behind the still-fronted workspace.
// Real path: register, adopt, focus — same as paneMirror + reopen.
describe('reopenLastClosedTile focuses the restored tab', () => {
  beforeEach(() => {
    window.localStorage.clear()
    vi.resetModules()
  })

  afterEach(() => {
    vi.resetModules()
  })

  async function setup() {
    const tree = await import('@/components/pane-shell/tree/store')
    const model = await import('@/components/pane-shell/tree/model')
    const { registry } = await import('@/contrib/registry')
    const session = await import('@/store/session')
    const states = await import('@/store/session-states')
    const { $focusedStoredSessionId } = await import('@/store/session-focus')

    registry.register({
      area: 'panes',
      data: { placement: 'main', uncloseable: true },
      id: 'workspace',
      render: () => null,
      title: 'chat'
    })

    const { paneMirror } = await import('@/app/chat/pane-mirror')
    paneMirror({
      source: states.$sessionTiles,
      key: tile => tile.storedSessionId,
      prefix: 'session-tile',
      dir: tile => tile.dir,
      anchor: tile => tile.anchor,
      before: tile => tile.before,
      minWidth: '10rem',
      title: id => id,
      render: () => null,
      close: states.closeSessionTile
    })()
    tree.watchContributedPanes()
    session.$selectedStoredSessionId.set('primary')
    tree.declareDefaultTree(model.group(['workspace'], { active: 'workspace', id: 'grp-main' }))

    states.openSessionTile('closed', 'center', 'workspace')
    states.focusOpenSession('closed')
    tree.noteActiveTreeGroup('grp-main')
    expect(findGroupOfPane(tree.$layoutTree.get()!, tilePane('closed'))?.active).toBe(tilePane('closed'))

    return { $focusedStoredSessionId, states, tree }
  }

  it('restores the live strip slot after reordering and retains the exact owner', async () => {
    const { $focusedStoredSessionId, states, tree } = await setup()
    states.openSessionTile('after', 'center', 'workspace')
    tree.moveTreePane(tilePane('closed'), { groupId: 'grp-main', pos: 'center', before: 'workspace' })
    const order = findGroupOfPane(tree.$layoutTree.get()!, 'workspace')!.panes
    const ownerRoute = { connectionId: 'cloud', profile: 'agent' }
    states.patchSessionTile('closed', { ownerRoute })
    states.closeSessionTile('closed')
    tree.noteActiveTreeGroup(null)
    states.reopenLastClosedTile()
    expect(findGroupOfPane(tree.$layoutTree.get()!, 'workspace')!.panes).toEqual(order)
    expect($focusedStoredSessionId.get()).toBe('closed')
    expect(states.sessionTileOwnerRoute('closed')).toEqual(ownerRoute)
  })

  it('fronts a palette-opened tab from sidebar focus without replacing main', async () => {
    const { $focusedStoredSessionId, tree } = await setup()
    const { openSession } = await import('@/app/open-session')
    const navigate = vi.fn()
    tree.noteActiveTreeGroup('sidebar')
    openSession('palette-result', navigate, 'stack')
    expect($focusedStoredSessionId.get()).toBe('palette-result')
    expect(findGroupOfPane(tree.$layoutTree.get()!, 'workspace')!.active).toBe(tilePane('palette-result'))
    expect(navigate).not.toHaveBeenCalled()
  })

  it('fronts the restored tab after ⌘⇧T', async () => {
    const { states, tree } = await setup()

    states.closeSessionTile('closed')
    expect(states.$sessionTiles.get().some(t => t.storedSessionId === 'closed')).toBe(false)
    expect(findGroupOfPane(tree.$layoutTree.get()!, 'workspace')?.active).toBe('workspace')

    states.reopenLastClosedTile()

    expect(states.$sessionTiles.get().some(t => t.storedSessionId === 'closed')).toBe(true)
    expect(findGroupOfPane(tree.$layoutTree.get()!, tilePane('closed'))?.active).toBe(tilePane('closed'))
    expect(tree.$activeTreeGroup.get()).toBe('grp-main')
  })
})

describe('sessionTileOwnerRoute', () => {
  afterEach(() => {
    $sessionTiles.set([])
  })

  it('returns the exact owning route a bot chat tile was opened with', () => {
    // This is what lets a bot chat RPC reach the bot's OWN local gateway even
    // while chrome stays on the launch profile: the tile carries the route, so
    // the request router never has to guess from the (hidden, unlisted) row.
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'local', mode: 'local', profile: 'developer' },
        storedSessionId: 'bot-chat-developer'
      }
    ])

    expect(sessionTileOwnerRoute('bot-chat-developer')).toEqual({
      connectionId: 'local',
      mode: 'local',
      profile: 'developer'
    })
  })

  it('returns undefined for a tile with no owner route (plain session)', () => {
    $sessionTiles.set([{ storedSessionId: 'plain' }])

    expect(sessionTileOwnerRoute('plain')).toBeUndefined()
  })
})

describe('knownOwnerForSession / requestForOwnedSession (#91684 client half)', () => {
  beforeEach(() => {
    // Earlier suites leave profile-scoped tile buckets behind; pin the profile
    // BEFORE seeding tiles so the bucket subscriber cannot clobber the seed.
    $activeGatewayProfile.set('default')
    $sessionTiles.set([])
  })
  afterEach(() => {
    $sessionTiles.set([])
    setSessions([])
  })

  it('resolves the tile owner route first, translating a runtime id to its stored id', () => {
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'conn-a', profile: 'work' },
        runtimeId: 'rt-1',
        storedSessionId: 'stored-1'
      }
    ])

    expect(knownOwnerForSession('rt-1')).toEqual({ connectionId: 'conn-a', profile: 'work' })
    expect(knownOwnerForSession('stored-1')).toEqual({ connectionId: 'conn-a', profile: 'work' })
  })

  it('falls back to the session row profile when no tile route exists', () => {
    setSessions([{ id: 'stored-2', profile: 'loki' } as never])

    expect(knownOwnerForSession('stored-2')).toBe('loki')
  })

  // A tile promoted into MAIN (⌘W on the workspace tab, its tab dragged out of
  // main) loses its tile and its evicted mirror entry in the same tick, while
  // the resume has already made its runtime the active one. The composer's
  // control read for that runtime must still find the stored-id owner hint
  // instead of failing closed with "Session controls unavailable" (#108369).
  it('translates the active runtime through the selected stored id when no tile or mirror binds it', () => {
    setSessionOwnerHint('stored-main', { connectionId: 'local', profile: 'alpha' })
    $sessionTiles.set([])
    $sessionStates.set({})
    $selectedStoredSessionId.set('stored-main')
    $activeSessionId.set('rt-main')

    expect(knownOwnerForSession('rt-main')).toEqual({ connectionId: 'local', profile: 'alpha' })
    // Only MAIN's own runtime gets this rung: an unrelated runtime id stays unknown.
    expect(knownOwnerForSession('rt-other')).toBeUndefined()

    $activeSessionId.set(null)
    $selectedStoredSessionId.set(null)
  })

  it('keeps a session row connection owner when profiles share the same name', () => {
    setSessions([{ connection_id: 'source-b', id: 'stored-shared', profile: 'default' } as never])

    expect(knownOwnerForSession('stored-shared')).toEqual({ connectionId: 'source-b', profile: 'default' })
  })

  // Two connections both exposing `default`: the row only names the profile,
  // and a bare profile is resolved by the profile door against the PRIMARY
  // connection — another machine for a session that runs on a non-primary one.
  // The inbound event proved the exact owner, so it must outrank the
  // connection-blind row profile (this is what keeps the 2nd prompt of an
  // ordinary session from answering `4001 session not found`).
  it('prefers an event-proven connection over a bare row profile when two connections share the profile name', () => {
    recordSessionEventScope({ connectionId: 'local', profile: 'default', session_id: 'rt-local' })
    setSessions([{ id: 'rt-local', profile: 'default' } as never])

    expect(knownOwnerForSession('rt-local')).toEqual({ connectionId: 'local', profile: 'default' })
  })

  it('returns undefined (ambient) when no owner is known, and for null ids', () => {
    expect(knownOwnerForSession('unknown-session')).toBeUndefined()
    expect(knownOwnerForSession(null)).toBeUndefined()
    expect(knownOwnerForSession(undefined)).toBeUndefined()
  })

  it('requestForOwnedSession dispatches ambient with the exact 2-arg shape when no owner is known', async () => {
    const ambient = vi.fn(async (method: string, params?: Record<string, unknown>) => ({ method, params }))

    await requestForOwnedSession('unknown-session', ambient as never, 'approval.respond', {
      choice: 'once',
      session_id: 'unknown-session'
    })

    expect(ambient).toHaveBeenCalledTimes(1)
    expect(ambient.mock.calls[0]).toEqual(['approval.respond', { choice: 'once', session_id: 'unknown-session' }])
  })
})

describe('isSessionRemote (#94640)', () => {
  beforeEach(() => {
    $activeGatewayProfile.set('default')
    $sessionTiles.set([])
  })
  afterEach(() => {
    $sessionTiles.set([])
    setSessions([])
    $connection.set(null)
  })

  it('falls back to the ambient connection when the session has no known owner route', () => {
    $connection.set({ mode: 'remote' } as never)
    expect(isSessionRemote('unknown-session')).toBe(true)

    $connection.set({ mode: 'local' } as never)
    expect(isSessionRemote('unknown-session')).toBe(false)
  })

  it("prefers the session's OWN owner route over an ambient connection of a different mode", () => {
    // The window's active/ambient connection is local, but this session
    // belongs to a registered secondary REMOTE connection (Bot Mode / the
    // unified Sessions list). Composer image uploads must still upload
    // bytes for it — reading ambient mode here shipped a client-local
    // composer-images path to the remote backend (#94640).
    $connection.set({ mode: 'local' } as never)
    $sessionTiles.set([
      {
        ownerRoute: { connectionId: 'homelab', mode: 'remote', profile: 'default' },
        runtimeId: 'rt-1',
        storedSessionId: 'stored-1'
      }
    ])

    expect(isSessionRemote('rt-1')).toBe(true)
    expect(isSessionRemote('stored-1')).toBe(true)
  })

  it('falls back to ambient when the owner is a bare pool profile (no connectionId/mode)', () => {
    $connection.set({ mode: 'remote' } as never)
    setSessions([{ id: 'stored-2', profile: 'loki' } as never])

    expect(isSessionRemote('stored-2')).toBe(true)
  })

  it("reads a connection-tagged row's mode from the registry, not the ambient connection (#120730)", () => {
    // A row from the unified Sessions list carries connection_id but no mode;
    // its owner is { connectionId, profile }. The byte-vs-path decision must
    // come from that connection's registry kind.
    $connectionsRegistry.set({
      version: 1,
      primary: 'local',
      secureTokenStorage: true,
      connections: [
        { id: 'local', kind: 'local', label: 'This Mac', tokenSet: false, tokenPreview: null },
        { id: 'vps', kind: 'ssh', label: 'VPS', tokenSet: false, tokenPreview: null }
      ]
    })
    setSessions([
      { id: 'stored-ssh', profile: 'default', connection_id: 'vps' } as never,
      { id: 'stored-local', profile: 'default', connection_id: 'local' } as never
    ])

    try {
      $connection.set({ mode: 'local' } as never)
      expect(isSessionRemote('stored-ssh')).toBe(true)

      $connection.set({ mode: 'remote' } as never)
      expect(isSessionRemote('stored-local')).toBe(false)
    } finally {
      $connectionsRegistry.set(null)
    }
  })

  it('reads a bare-profile owner from the socket that serves it, not the ambient connection (#120730)', () => {
    // The primary socket serving 'default' is a remote backend while the window
    // shows a local source: the primary's own mode decides.
    setPrimaryGateway({} as never, 'default')
    setPrimaryGatewayConnection({ connectionId: 'vps', mode: 'remote' })
    $connection.set({ mode: 'local' } as never)
    setSessions([{ id: 'stored-primary', profile: 'default' } as never])

    try {
      expect(isSessionRemote('stored-primary')).toBe(true)
    } finally {
      setPrimaryGateway(null)
    }
  })
})

describe('rekeySessionTile (#98622 — pane identity across compression tip rotation)', () => {
  beforeEach(() => {
    $activeGatewayProfile.set('default')
    $layoutTree.set(null)
    $sessionTiles.set([])
    $selectedStoredSessionId.set(null)
    setSessions([])
  })

  afterEach(() => {
    $activeGatewayProfile.set('default')
    $layoutTree.set(null)
    $sessionTiles.set([])
    $selectedStoredSessionId.set(null)
    setSessions([])
  })

  it('re-keys the open tile to the new tip, preserving placement', () => {
    $sessionTiles.set([
      { anchor: 'workspace', before: null, dir: 'right', storedSessionId: 'tip-old' },
      { storedSessionId: 'unrelated' }
    ])

    rekeySessionTile('tip-old', 'tip-new')

    const tiles = $sessionTiles.get()
    expect(tiles.find(t => t.storedSessionId === 'tip-old')).toBeUndefined()
    const rekeyed = tiles.find(t => t.storedSessionId === 'tip-new')
    expect(rekeyed).toMatchObject({ anchor: 'workspace', before: null, dir: 'right' })
    expect(tiles.find(t => t.storedSessionId === 'unrelated')).toBeDefined()
  })

  it('keeps a Bot tile when the same stored session is selected in Sessions main', () => {
    const botTile = {
      ownerRoute: {
        connectionId: 'bot-owner',
        mode: 'remote' as const,
        profile: 'default'
      },
      storedSessionId: 'tip-old',
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'bot:bot-owner::default'
    }

    $selectedStoredSessionId.set('tip-new')
    $sessionTiles.set([botTile])

    rekeySessionTile('tip-old', 'tip-new')

    expect($sessionTiles.get()).toEqual([{ ...botTile, storedSessionId: 'tip-new' }])
  })

  it('keeps a tile owned by another backend route beside the Sessions main', () => {
    const ownerA = { connectionId: 'owner-a', mode: 'remote' as const, profile: 'default' }
    const ownerB = { connectionId: 'owner-b', mode: 'remote' as const, profile: 'default' }

    setSessions([{ connection_id: 'owner-b', id: 'tip-new', profile: 'default' } as never])
    $selectedStoredSessionId.set('tip-new')
    $sessionTiles.set([
      { ownerRoute: ownerA, storedSessionId: 'tip-old' },
      { ownerRoute: ownerB, storedSessionId: 'tip-new' }
    ])

    rekeySessionTile('tip-old', 'tip-new')

    expect($sessionTiles.get()).toEqual([
      { ownerRoute: ownerA, storedSessionId: 'tip-new' },
      { ownerRoute: ownerB, storedSessionId: 'tip-new' }
    ])
  })

  it('coalesces a minimal next tile without losing the live previous tile metadata', () => {
    const ownerRoute = {
      connectionId: 'connection-a',
      mode: 'remote' as const,
      profile: 'writer',
      targetProfile: 'writer'
    }

    const previous = {
      anchor: 'session-tile:anchor',
      before: 'session-tile:next-sibling',
      dir: 'left' as const,
      error: 'resume failed',
      ownerRoute,
      runtimeId: 'runtime-live',
      storedSessionId: 'tip-old',
      workspaceMode: 'bots' as const,
      workspaceOwnerKey: 'bot:connection-a::writer',
      workspaceTabTitle: 'Live bot chat'
    }

    const next = { storedSessionId: 'tip-new' }
    const paneId = tilePane('tip-new')

    $layoutTree.set(
      split('row', [
        group(['workspace'], { active: 'workspace', id: 'workspace-group' }),
        group([paneId], { active: paneId, id: 'tile-group' })
      ])
    )
    $sessionTiles.set([previous, next])

    rekeySessionTile('tip-old', 'tip-new')

    expect($sessionTiles.get()).toEqual([{ ...previous, storedSessionId: 'tip-new' }])
    expect(findGroupOfPane($layoutTree.get()!, paneId)).toMatchObject({ active: paneId, id: 'tile-group' })
  })

  it('drops the stale tile when the new tip already has a tile (one pane per conversation)', () => {
    $sessionTiles.set([{ storedSessionId: 'tip-old' }, { storedSessionId: 'tip-new' }])

    rekeySessionTile('tip-old', 'tip-new')

    const tiles = $sessionTiles.get()
    expect(tiles).toHaveLength(1)
    expect(tiles[0].storedSessionId).toBe('tip-new')
  })

  it('drops the stale tile when the new tip is already the main selection (main OR tile, never both)', () => {
    $selectedStoredSessionId.set('tip-new')
    $sessionTiles.set([{ storedSessionId: 'tip-old' }])

    rekeySessionTile('tip-old', 'tip-new')

    expect($sessionTiles.get()).toHaveLength(0)
  })

  it('is a no-op when no tile carries the previous id', () => {
    $sessionTiles.set([{ storedSessionId: 'other' }])

    rekeySessionTile('tip-old', 'tip-new')

    expect($sessionTiles.get()).toEqual([{ storedSessionId: 'other' }])
  })

  it('ignores degenerate inputs (empty id, same id)', () => {
    $sessionTiles.set([{ storedSessionId: 'tip-old' }])

    rekeySessionTile('', 'tip-new')
    rekeySessionTile('tip-old', 'tip-old')

    expect($sessionTiles.get()).toEqual([{ storedSessionId: 'tip-old' }])
  })
})