Relay does not turn off

I have TYWRA-RF flashed with Esphome.

TYWRA-RF is WIFI relay with one relay (connected to P24 of CB3S) and two buttons (connected to P14 and P6 of CB3S).

I am going to connect the relay to a door button switch. The door button switch opens the sliding door by a short press and the door closes automatically after some time.
When I want to keep the door open, I just keep on pressing the door button switch. The door closes automatically when the door button switch is released.

In order to emulate such behavior of the door and the door button switch with TYWRA-RF, the two buttons and one relay should work like below.

Physical button 1: when pressed, the relay is turned on for 1 second and then automatically turned off (emulates a short press of the door button switch).

Physical button 2: when pressed, the relay is turned on until button 2 is pressed again (emulates long press of the door button switch).

With my code, button 2 turns on the relay on the first press but does not turn off the relay on the second press whereas button 1 works as intended (the relay is automatically turned off after 1 second).

When I press GUI button 2 at the frontend (Home Assistant or web), the relay is turned on but the GUI button 2 turns itself off after about 1 second (the relay stays on).

I cannot figure out what is wrong with my code. Any help would be appreciated.

Here is my code.

esphome:
  name: tywra-rf
  friendly_name: TYWRA-RF

bk72xx:
  board: wb3s

logger:

web_server:

captive_portal:

mdns:

api:

ota:
  - platform: web_server
  - platform: esphome

wifi:
  networks:
  - ssid: !secret wifi_ssid1
    password: !secret wifi_password1

binary_sensor:
  - platform: gpio
    id: button_1
    pin:
      number: P14
      inverted: true
      mode: INPUT_PULLUP
    on_press:
      then:
        - switch.toggle: door_open
  - platform: gpio
    id: button_2
    pin:
      number: P6
      inverted: true
      mode: INPUT_PULLUP
    on_press:
      then:
        - switch.toggle: door_open_n_hold

output:
  - platform: gpio
    id: door_relay
    pin:
      number: P24
      inverted: false

switch:
  - platform: template
    id: door_open
    name: Door open
    turn_on_action:
      - script.execute: pulsetime
    turn_off_action:
      - script.stop: pulsetime
  - platform: template
    id: door_open_n_hold
    name: Door open and hold
    turn_on_action:
      - output.turn_on: door_relay
    turn_off_action:
      - output.turn_off: door_relay

script:
  - id: pulsetime
    then:
      - output.turn_on: door_relay
      - delay: 1s
      - output.turn_off: door_relay
      - switch.turn_off: door_open

Add
optimistic: true
to your template switches and see how it behaves.

It works now. Thank you.

You are welcome.