> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 会话生命周期事件

> 说明如何在 Laravel Copilot SDK 中订阅会话的创建、更新、删除以及前台状态变更事件。

## 会话生命周期事件

会话生命周期事件是通知会话的创建、删除、更新以及前台 / 后台状态变化（TUI+服务器模式下）的事件。

## 事件类型

在 `SessionLifecycleEventType` enum 中定义了 5 个事件类型。

| 事件                   | 说明     |
| -------------------- | ------ |
| `session.created`    | 创建了新会话 |
| `session.deleted`    | 会话被删除  |
| `session.updated`    | 会话被更新  |
| `session.foreground` | 会话移到前台 |
| `session.background` | 会话移到后台 |

```php theme={null}
use Revolution\Copilot\Enums\SessionLifecycleEventType;

// 获取事件类型的值
echo SessionLifecycleEventType::SESSION_CREATED->value; // 'session.created'
```

## 订阅事件

使用 `onLifecycle()` 方法可以订阅会话生命周期事件。

```php theme={null}
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionLifecycleEvent;

// 获取 Client 并订阅生命周期事件
$client = Copilot::client();

// 订阅所有生命周期事件
$unsubscribe = $client->onLifecycle(function (SessionLifecycleEvent $event) {
    match ($event->type) {
        SessionLifecycleEventType::SESSION_CREATED => info("会话创建: {$event->sessionId}"),
        SessionLifecycleEventType::SESSION_DELETED => info("会话删除: {$event->sessionId}"),
        SessionLifecycleEventType::SESSION_FOREGROUND => info("前台: {$event->sessionId}"),
        SessionLifecycleEventType::SESSION_BACKGROUND => info("后台: {$event->sessionId}"),
        default => null,
    };
});

// 取消订阅
$unsubscribe();
```

## SessionLifecycleEvent

`SessionLifecycleEvent` 是包含生命周期事件详情的 readonly class。

```php theme={null}
use Revolution\Copilot\Types\SessionLifecycleEvent;
use Revolution\Copilot\Types\SessionLifecycleEventMetadata;

readonly class SessionLifecycleEvent implements Arrayable
{
    public function __construct(
        public SessionLifecycleEventType $type,  // 事件类型
        public string $sessionId,                 // 会话 ID
        public ?SessionLifecycleEventMetadata $metadata = null,  // 元数据（删除时不包含）
    ) {}
}
```

### SessionLifecycleEventMetadata

包含会话元数据的类（删除事件中不包含）。

```php theme={null}
readonly class SessionLifecycleEventMetadata implements Arrayable
{
    public function __construct(
        public string $startTime,      // 会话开始时间
        public string $modifiedTime,   // 最后更新时间
        public ?string $summary = null, // 会话摘要
    ) {}
}
```

## 前台会话管理

当连接到以 TUI+服务器模式（`--ui-server`）运行的服务器时，可以管理前台会话。

### 获取当前的前台会话

```php theme={null}
use Revolution\Copilot\Facades\Copilot;

$client = Copilot::client();

// 获取当前显示在 TUI 中的会话 ID
$sessionId = $client->getForegroundSessionId();

if ($sessionId !== null) {
    echo "当前的前台会话: {$sessionId}";
}
```

### 设置前台会话

```php theme={null}
use Revolution\Copilot\Facades\Copilot;

$client = Copilot::client();

// 在 TUI 中显示特定会话
$client->setForegroundSessionId('session-123');
```

## ForegroundSessionInfo

包含前台会话信息的 readonly class。

```php theme={null}
use Revolution\Copilot\Types\ForegroundSessionInfo;

readonly class ForegroundSessionInfo implements Arrayable
{
    public function __construct(
        public ?string $sessionId = null,      // 前台会话 ID
        public ?string $workspacePath = null,  // 工作区路径
    ) {}
}
```

## 在 TCP 模式下的使用

以 TUI+服务器模式启动 Copilot CLI，从 SDK 连接就可以利用生命周期事件。

```bash theme={null}
# 以 TUI+服务器模式启动 Copilot CLI
copilot --ui-server --port 8080
```

```php theme={null}
use Revolution\Copilot\Facades\Copilot;

// 以 TCP 模式连接服务器
$client = Copilot::useTcp('tcp://127.0.0.1:8080')->client();

// 订阅生命周期事件
$client->onLifecycle(function (SessionLifecycleEvent $event) {
    // 事件处理
});
```

## 注意事项

* `session.foreground` 和 `session.background` 事件仅在 TUI+服务器模式下发生
* 会话被删除时（`session.deleted`）`metadata` 属性为 `null`
* `onLifecycle()` 会返回用于取消订阅的回调函数
* 这与 [Session Hooks](/zh/packages/laravel-copilot-sdk/hooks) 中的 `onSessionStart` 或 `onSessionEnd` 是不同的功能

<Info>
  最新信息请参考 [GitHub 仓库](https://github.com/invokable/laravel-copilot-sdk)。
</Info>


## Related topics

- [Eloquent 入门](/zh/eloquent.md)
- [请求生命周期](/zh/lifecycle.md)
- [会话钩子](/zh/packages/laravel-copilot-sdk/hooks.md)
- [Eloquent 自定义类型转换](/zh/advanced/eloquent-casts.md)
- [SessionConfig](/zh/packages/laravel-copilot-sdk/session-config.md)
