TEN-framework / ten_framework

TEN, the Next-Gen AI-Agent Framework, the world's first truly real-time multimodal AI agent framework.
https://doc.theten.ai/
Other
357 stars 30 forks source link

msg can not be sent out from extension::on_stop() if the dest extension is not in the same group #305

Open leoadonia opened 4 days ago

leoadonia commented 4 days ago

tests/ten_runtime/smoke/extension_test/prepare_to_stop/different_thread.cc :

class test_extension_1 : public ten::extension_t {
 public:
  explicit test_extension_1(const std::string &name) : ten::extension_t(name) {}

  void on_cmd(ten::ten_env_t &ten_env,
              std::unique_ptr<ten::cmd_t> cmd) override {
    if (std::string(cmd->get_name()) == "hello_world") {
      ten_env.send_cmd(std::move(cmd));
      return;
    }
  }

  void on_stop(ten::ten_env_t &ten_env) override {
    auto cmd = ten::cmd_t::create("extension_1_stop");
    ten_env.send_cmd(std::move(cmd),
                     [=](ten::ten_env_t &ten_env,
                         std::unique_ptr<ten::cmd_result_t> /*cmd_result*/) {
                       ten_env.on_stop_done();
                       return true;
                     });
  }
};

class test_extension_2 : public ten::extension_t {
 public:
  explicit test_extension_2(const std::string &name) : ten::extension_t(name) {}

  void on_cmd(ten::ten_env_t &ten_env,
              std::unique_ptr<ten::cmd_t> cmd) override {
    if (std::string(cmd->get_name()) == "hello_world") {
      check = 1;
      auto cmd_result = ten::cmd_result_t::create(TEN_STATUS_CODE_OK);
      cmd_result->set_property("detail", "hello world, too");
      ten_env.return_result(std::move(cmd_result), std::move(cmd));
    } else if (std::string(cmd->get_name()) == "extension_1_stop") {
      extension_1_stop_received = true;

      // To ensure that extension 1 will be on_stop_done() after the extension 2
      // completes its job.
      ten_sleep(500);

      check = 2;

      auto cmd_result = ten::cmd_result_t::create(TEN_STATUS_CODE_OK);
      cmd_result->set_property("detail", "");
      ten_env.return_result(std::move(cmd_result), std::move(cmd));

      if (is_stopping) {
        ten_env.on_stop_done();
      }
    }
  }

  void on_stop(ten::ten_env_t &ten_env) override {
    is_stopping = true;

    if (extension_1_stop_received) {
      ten_env.on_stop_done();
    }
  }

 private:
  bool extension_1_stop_received = false;
  bool is_stopping = false;
};

Put ext_1 and ext_2 in different extension_group, ext_2 can not receive the extension_1_stop cmd. As engine will stop to dispatch msg when it is closing.

https://github.com/TEN-framework/ten_framework/blob/main/core/src/ten_runtime/engine/internal/extension_interface.c#L95

https://github.com/TEN-framework/ten_framework/blob/main/core/src/ten_runtime/engine/msg_interface/common.c#L240

https://github.com/TEN-framework/ten_framework/blob/main/core/src/ten_runtime/engine/msg_interface/common.c#L206