比较提交
7 提交
1a18a8ac85
...
178fba70ea
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
| 178fba70ea | |||
| 49dccc5eac | |||
| 124cf32fa2 | |||
| 02ac2046d6 | |||
| 0fadc699e2 | |||
| 06312447aa | |||
| b2ecd1f3a4 |
共有 14 个文件被更改,包括 1346 次插入 和 205 次删除
21
CHANGELOG.md
21
CHANGELOG.md
|
|
@ -40,6 +40,27 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
|||
|
||||
### Fixed
|
||||
|
||||
- One unreachable connection no longer freezes the whole application. The reachability probe now
|
||||
runs outside the runtime lock, so a slot that is connecting cannot block status, sending,
|
||||
cancelling or disconnecting on the other slot, and the attempt itself can be interrupted.
|
||||
- An activation rejected during validation no longer tears down a working connection or leaves the
|
||||
slot stuck in "connecting" with nothing to explain it.
|
||||
- Switching a session while the slot is being reconnected no longer writes the old session id onto
|
||||
the new connection, and no longer copies it into that profile's sticky session.
|
||||
- One connection profile can no longer be activated into both slots at once, which previously let
|
||||
the two slots overwrite each other's sticky session.
|
||||
- Disconnecting or re-pointing the operations slot is now refused while an operations task is
|
||||
active, matching the existing rule for slot assignment.
|
||||
- A rejected chat send no longer leaves the question in local history without a failure marker, and
|
||||
retrying no longer appends a second copy of it. A send that fails after AstrBot accepted it keeps
|
||||
its question, since the remote conversation already has it.
|
||||
- Streaming replies are no longer doubled in development. Event listeners that resolved after their
|
||||
component had unmounted were never unregistered, so a leaked listener applied every delta twice.
|
||||
- The composer draft, pending attachments, and the error banner are now per slot. An attachment
|
||||
uploaded on the companion slot no longer follows the user to the operations slot, and an error
|
||||
from one slot no longer appears on the other.
|
||||
- An error from sending or uploading is no longer erased half a second later by the connection
|
||||
status poll.
|
||||
- Scoped AstrBot stream event ids per chat request so the second and later messages on a
|
||||
connection are no longer discarded by the client-side event deduplicator.
|
||||
- Accepted Rust `null` values in the runtime-event, remote-session, and model-option
|
||||
|
|
|
|||
|
|
@ -553,3 +553,56 @@ pending in `docs/q9-local-acceptance.md`. Certificate pinning, signed updates, a
|
|||
remain externally blocked.
|
||||
|
||||
Next: batch R3 (isolation and state correctness), F-14 through F-19.
|
||||
|
||||
## 2026-07-27: batch R3, isolation and state correctness
|
||||
|
||||
Current stage: P02 dual connections, branch `feat/p02-dual-connections`. Six commits, one per fix.
|
||||
|
||||
### Completed
|
||||
|
||||
- **F-14** `activate_slot` no longer holds the runtime lock across the reachability probe. It is now
|
||||
three phases: validate and build the client with no lock, claim the slot in one critical section
|
||||
that installs the cancellation token up front, probe outside the lock under a biased `select!`,
|
||||
then write back only if the slot's generation still matches. One unreachable address used to
|
||||
freeze every command on both slots for up to 120 seconds, and the activation could not be
|
||||
interrupted. This also fixed an unrecorded defect: validation ran after the `Connecting` snapshot
|
||||
was written, so a rejected request tore down a working connection and parked the slot in
|
||||
`Connecting` with no client and no error.
|
||||
- **F-17** `switch_slot_session` captures the generation with the client and checks it before
|
||||
writing `active_session_id`, so a slot reset mid-switch cannot receive the old session id.
|
||||
- **F-19** One profile can no longer occupy both runtime slots. Enforced inside `activate_slot`
|
||||
(which also covers startup auto-connect), cross-checked against `connection_slots` in the
|
||||
command, and the operations switch guard now covers probe and disconnect. Both rules are
|
||||
negative — they ask only whether the profile is bound to the *other* slot — because auto-connect
|
||||
activates from `auto_connect_slot` and never writes `connection_slots`.
|
||||
- **F-18** Sends are validated before anything is written to history, via a new read-only
|
||||
`ensure_slot_can_send`. A failure that the server never received marks the row rather than
|
||||
leaving it clean; `cancelled` and `streamInterrupted` keep the question because AstrBot already
|
||||
has it.
|
||||
- **F-15** All four `listen()` call sites now unregister correctly when the promise resolves after
|
||||
the effect was cleaned up. Under StrictMode the first listener leaked on every mount, which
|
||||
doubled every character of a streamed reply.
|
||||
- **F-16** `draft`, `pendingAttachments`, and the error banner are per slot, and every async action
|
||||
pins its slot at the start. The error state was split in two: the 500ms status poll used to clear
|
||||
the shared error on success, silently erasing action errors.
|
||||
|
||||
### Test status
|
||||
|
||||
Rust 107 passed / 2 ignored (`astrbot-desktop` unit tests 76 → 87). Frontend 24 passed / 5 files
|
||||
(19 → 24, including a new `ChatPanel.test.tsx`, which the component previously had none of).
|
||||
Playwright 5 passed. `npm run build` and `npm run tauri:build` pass.
|
||||
|
||||
The new tests for F-14, F-15, and F-16 were each checked against a mutation restoring the old
|
||||
behaviour, and each fails under it, so they are not tautological.
|
||||
|
||||
### Not covered
|
||||
|
||||
`auto_connect_configured_slots` is still serial, so a dead profile delays the second profile by up
|
||||
to 120 seconds — it no longer freezes the UI, but the delay remains. The operations switch guard
|
||||
still has no production writer (F-74, audit P3-7); F-19 extends only its read side.
|
||||
|
||||
Real-hardware acceptance for R3 has not been performed; the steps are listed in
|
||||
`docs/q9-local-acceptance.md`.
|
||||
|
||||
Next: batch R4 (data and credential boundaries) or R5 (protocol hardening). Neither depends on R3,
|
||||
so they can be dispatched in parallel.
|
||||
|
|
|
|||
|
|
@ -106,6 +106,31 @@ Not executed, not claimed. Each item names the fix it is the acceptance evidence
|
|||
|
||||
Items 1 and 2 need only the installer, not a container.
|
||||
|
||||
## 2026-07-27 verification update (R3 isolation and state correctness)
|
||||
|
||||
### Gate results
|
||||
|
||||
`cargo fmt`, `cargo clippy --workspace --all-targets -D warnings`, and `cargo check` pass.
|
||||
`cargo test --workspace`: 107 passed, 0 failed, 2 ignored (`astrbot-desktop` unit tests 76 to 87).
|
||||
`npm run typecheck`, `npm run lint`, `npm run build` pass. `npm run test -- --run`: 24 passed across
|
||||
5 files, up from 19 across 4 — `ChatPanel.test.tsx` is new, the component had no tests before.
|
||||
`npm run test:e2e`: 5 passed. `npm run tauri:build`: passed;
|
||||
`target/release/bundle/nsis/AstrBot Desktop_0.1.0-alpha.2_x64-setup.exe`, 8,874,747 bytes, built
|
||||
2026-07-27 00:30:22 +0800.
|
||||
|
||||
The new tests for F-14, F-15 and F-16 were each run against a mutation restoring the old behaviour
|
||||
and each fails under it, so they exercise the invariant rather than restating the implementation.
|
||||
|
||||
### Pending, requires a live AstrBot container
|
||||
|
||||
1. With one slot pointed at an unreachable address, confirm the other slot's status, sending and
|
||||
disconnect stay responsive, and that the connecting slot can be interrupted with 断开 — F-14.
|
||||
2. Upload an attachment on the companion slot, switch to operations, send; the attachment must not
|
||||
follow. Type a draft on one slot and confirm it does not appear on the other — F-16.
|
||||
3. Send while disconnected and confirm no user row appears in history — F-18.
|
||||
4. Probe the same profile into both slots in turn; the second must be refused — F-19.
|
||||
5. Confirm a streamed reply renders each character once in a production build — F-15.
|
||||
|
||||
## Explicitly pending external acceptance
|
||||
|
||||
- HTTPS certificate pinning requires a real HTTPS endpoint and first-trust confirmation.
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@
|
|||
|---|---|---|
|
||||
| R1 发布阻断批 | **已完成,门槛已验证** | 9 项全部实现。2026-07-26 首次跑完整门槛,发现 2 处编译/lint 失败并修复(详见下方「R1 门槛验证结果」),补写 F-05 缺失的单测。现全绿。 |
|
||||
| R2 传输层批 | **已完成,门槛已验证** | F-10 – F-13 全部实现,新增 9 条 Rust 测试(`astrbot-desktop` 单元测试 67 → 76)。顺带并入 F-56(P3-4,取消不再置 Disconnected)。全绿。 |
|
||||
| R3 – R8 | 未开始 | 下一批为 R3。依赖关系见文末批次依赖图。 |
|
||||
| R3 隔离与状态正确性批 | **已完成,门槛已验证** | F-14 – F-19 全部实现,新增 11 条 Rust 测试(`astrbot-desktop` 单元测试 76 → 87)与 5 条前端测试(19 → 24,含新建的 `ChatPanel.test.tsx`)。全绿。详见下方「R3 实现记录」。 |
|
||||
| R4 – R8 | 未开始 | 下一批为 R4 或 R5,两者与 R3 无依赖,可并行分派。 |
|
||||
|
||||
> 计数订正(2026-07-27 实测):本表此前记为「67 → 73(+6)」,与
|
||||
> `r1-r2-status-2026-07-26.md` 的「67 → 76(+9)」冲突。实跑 `cargo test --workspace` 的结果是
|
||||
|
|
@ -74,6 +75,45 @@
|
|||
在把它二分到具体注入行之后才定位到真因。**F-69 不存在,已撤销。**
|
||||
后续审查必须只读运行,或用独立 worktree 隔离。
|
||||
|
||||
### R3 实现记录(2026-07-27)
|
||||
|
||||
- **F-14** `activate_slot` 拆成三段:段 0 校验与建 client(无锁),段 1 单个临界区内 bump generation、
|
||||
**当场安装** `connection_cancellation`、写 `Connecting` 快照,段 2 锁外 `tokio::select!`(`biased;`)
|
||||
探测,段 3 重新取锁后先 `ensure_generation` 再回写。监听器收到的是段 1 那个 Arc——若在此新建第二个
|
||||
token,`deactivate_slot` 将取消一个无人监听的 token,desktop-v1 的重连循环会比断开活得更久。
|
||||
**顺带修掉一个队列未记的缺陷**:原实现把校验放在 `Connecting` 快照之后,`?` 早返回会拆掉一个正常
|
||||
连接并把槽永久留在 `Connecting`(无 client、无 `last_error`)。
|
||||
- **F-17** `switch_slot_session` 在第一临界区连同 client 捕获 `generation`,回写抽成
|
||||
`commit_session_id()` 并先校验。
|
||||
- **F-19** 三层:`activate_slot` 段 1 的运行时不变量(覆盖 `auto_connect_configured_slots`,它直接调
|
||||
`activate_slot`)、`probe_connection_slot` 对 `connection_slots` 的交叉校验、运维守卫扩展到
|
||||
probe / disconnect。**两条规则都写成否定式**(只问「是否绑在另一槽」):auto-connect 依据
|
||||
`profile.auto_connect_slot` 激活且从不写 `connection_slots`,肯定式规则会打死重连。
|
||||
运维守卫今日仍无生产写入方(F-74),因此附带一条直接翻转守卫的单测,避免复刻死分支。
|
||||
- **F-18** 新增只读预检 `ensure_slot_can_send()`;条件抽成 `slot_send_precondition()` 供发送路径复用。
|
||||
`message_id` 只铸一次,失败且 `!server_received(code)` 时以 `error = true` 幂等重写该行。
|
||||
`server_received()` 只认 `cancelled` / `streamInterrupted`——这两种情况 AstrBot 已收到消息。
|
||||
配套一条穷举 `astrbot_send_error` 全部变体的测试,防止 R2 错误码改名而静默破坏分类。
|
||||
**R2 的重试循环与错误映射逐字未动**,五条 R2 哨兵测试复跑通过。
|
||||
- **F-15** 四处 `listen()` 统一改「`active` 标志 + 迟到 resolve 立即注销 + `.catch()`」。
|
||||
测试替身 `src/test/tauriEvent.ts` 采用**延迟 resolve**,否则竞态无法表达;`setup.ts` 每例后重置
|
||||
注册表(`clearMocks` 不管普通模块状态)。新建 `ChatPanel.test.tsx`。
|
||||
- **F-16** `draft` / `pendingAttachments` / 错误全部改 `Record<ChatSlot, …>`,每个异步动作开头
|
||||
`const slot = selectedSlot;` 固定槽位。**错误必须拆成两个 state**:`refresh()` 每 500ms 在成功时
|
||||
`setError(null)`,此前会在半秒内静默抹掉任何发送/上传错误横幅;轮询失败归 `runtimeError`
|
||||
(描述 IPC 通道),用户动作归 `slotError`。
|
||||
|
||||
**测试有效性**:F-14、F-15、F-16 的新测试都做过变异检验——分别注入「探测期间持锁」「旧的无条件
|
||||
赋值 unlisten」「按固定槽位读取」三种回退,对应测试全部失败,确认非同义反复。
|
||||
|
||||
**门槛结果(2026-07-27)**:`cargo fmt` / `clippy -D warnings` 通过;`cargo test --workspace`
|
||||
107 通过 / 0 失败 / 2 ignored(`astrbot-desktop` 单元 76 → 87);`npm run typecheck` / `lint`
|
||||
通过;`npm run test` 19 → 24 通过 / 5 文件;`npm run build`、`npm run test:e2e`(5/5)、
|
||||
`npm run tauri:build`(NSIS)通过。
|
||||
|
||||
**R3 未覆盖、仍开放**:`auto_connect_configured_slots` 仍串行(`commands.rs`),一个死 profile 会把
|
||||
第二个 profile 延迟至多 120s——但不再冻结 UI。属遗留限制,本批不修。
|
||||
|
||||
### R1 已改动的文件
|
||||
|
||||
新增:`src/lib/errorMessage.ts`、`src/features/pet/types.test.ts`
|
||||
|
|
|
|||
|
|
@ -14,14 +14,18 @@
|
|||
| --- | --- | --- | --- | --- |
|
||||
| R1 发布阻断批 | 9 | 已完成 | 已通过 | **未做** |
|
||||
| R2 传输层批 | 4 | 已完成 | 已通过 | **未做** |
|
||||
| R3 隔离与状态正确性 | 6 | 未开始 | — | — |
|
||||
| R3 隔离与状态正确性 | 6 | 已完成 | 已通过 | **未做** |
|
||||
| R4 数据与凭据安全 | 6 | 未开始 | — | — |
|
||||
| R5 协议健壮与契约治理 | 13 | 未开始 | — | — |
|
||||
| R6 体验、无障碍与产品红线 | 10 | 未开始 | — | — |
|
||||
| R7 性能与工程化 | 8(1 项已提前完成) | 未开始 | — | — |
|
||||
| R8 剩余 P3 | 17(1 项已提前完成) | 未开始 | — | — |
|
||||
|
||||
**已完成 15 项,剩余 58 项。** 共 10 个提交,工作区干净。
|
||||
**已完成 21 项,剩余 52 项。** 工作区干净。
|
||||
|
||||
> 2026-07-27 更新:R3(F-14 – F-19)已实现并通过门槛,实现记录见
|
||||
> [fix-queue-2026-07-26.md](./fix-queue-2026-07-26.md) 的「R3 实现记录」。R3 的真机验收项
|
||||
> 已并入 `docs/q9-local-acceptance.md` 的待真机清单。
|
||||
|
||||
> 2026-07-27 订正:R5 由 9 项增至 13 项、R8 由 16 项增至 17 项。初版队列遗漏了审计中的
|
||||
> P2-6、P2-7、P2-8、P2-29、P3-7 五条发现,现补编为 F-70 – F-74(`F-69` 保持永久空缺)。
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
// IPC wrappers for dual-slot runtime. Secrets never leave Rust.
|
||||
use desktop_protocol::TransportKind;
|
||||
use desktop_protocol::{ActiveSlotKind, ConnectionSlot, TransportKind};
|
||||
use secrecy::SecretString;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
|
@ -8,10 +8,11 @@ use tracing::{info, warn};
|
|||
|
||||
use super::{
|
||||
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest, SlotKind,
|
||||
SlotRuntimeSnapshot,
|
||||
SlotRuntimeSnapshot, server_received,
|
||||
};
|
||||
use crate::credentials::{CredentialCommandError, load_profile_secret};
|
||||
use crate::database::ApplicationDatabase;
|
||||
use crate::runtime_guards::RuntimeGuards;
|
||||
use crate::secure_store::WindowsCredentialStore;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
@ -106,6 +107,67 @@ fn slot_name(slot: SlotKind) -> &'static str {
|
|||
}
|
||||
}
|
||||
|
||||
fn active_slot_kind(slot: SlotKind) -> ActiveSlotKind {
|
||||
match slot {
|
||||
SlotKind::Companion => ActiveSlotKind::Companion,
|
||||
SlotKind::Operations => ActiveSlotKind::Operations,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rejects activating a profile that the persisted slot table binds elsewhere.
|
||||
///
|
||||
/// Deliberately a negative rule. `auto_connect_configured_slots` activates from
|
||||
/// `profile.auto_connect_slot` and never writes `connection_slots`, so a
|
||||
/// positive rule — "the profile must be assigned to the slot it is activating"
|
||||
/// — would break reconnect for every auto-connected profile.
|
||||
fn ensure_profile_not_bound_elsewhere(
|
||||
slots: &[ConnectionSlot],
|
||||
slot: SlotKind,
|
||||
profile_id: &str,
|
||||
) -> Result<(), RuntimeCommandError> {
|
||||
let requested = active_slot_kind(slot);
|
||||
let bound_elsewhere = slots
|
||||
.iter()
|
||||
.any(|entry| entry.slot != requested && entry.profile_id.as_deref() == Some(profile_id));
|
||||
if bound_elsewhere {
|
||||
return Err(RuntimeCommandError::profile_already_assigned());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Blocks operations-slot changes while an operations task is running.
|
||||
///
|
||||
/// Mirrors `slots::ensure_operations_switch_allowed`, extended to the runtime
|
||||
/// commands. A probe is only blocked when it would change which profile the
|
||||
/// operations slot holds, so reconnecting the profile already in that slot
|
||||
/// still works during a task; a disconnect is blocked outright.
|
||||
fn ensure_operations_runtime_change_allowed(
|
||||
guards: &RuntimeGuards,
|
||||
slot: SlotKind,
|
||||
current_profile_id: Option<&str>,
|
||||
next_profile_id: Option<&str>,
|
||||
) -> Result<(), RuntimeCommandError> {
|
||||
if slot != SlotKind::Operations {
|
||||
return Ok(());
|
||||
}
|
||||
if next_profile_id.is_some() && next_profile_id == current_profile_id {
|
||||
return Ok(());
|
||||
}
|
||||
let locked = guards
|
||||
.operations_switch_locked()
|
||||
.map_err(|_| RuntimeCommandError {
|
||||
code: "guardUnavailable",
|
||||
message: "The operations switch guard is unavailable.",
|
||||
})?;
|
||||
if locked {
|
||||
return Err(RuntimeCommandError {
|
||||
code: "operationsSwitchLocked",
|
||||
message: "The operations profile cannot be changed while an operations task is active.",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_session_identity(database: &ApplicationDatabase, snapshot: &SlotRuntimeSnapshot) {
|
||||
let Some(profile_id) = snapshot.profile_id.as_deref() else {
|
||||
return;
|
||||
|
|
@ -412,8 +474,24 @@ pub(crate) fn persist_runtime_event(
|
|||
pub async fn probe_connection_slot(
|
||||
database: State<'_, ApplicationDatabase>,
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
guards: State<'_, RuntimeGuards>,
|
||||
request: ProbeConnectionSlotRequest,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
let current = match request.slot {
|
||||
SlotKind::Companion => runtime.status().await.companion,
|
||||
SlotKind::Operations => runtime.status().await.operations,
|
||||
};
|
||||
ensure_operations_runtime_change_allowed(
|
||||
&guards,
|
||||
request.slot,
|
||||
current.profile_id.as_deref(),
|
||||
Some(request.profile_id.as_str()),
|
||||
)?;
|
||||
|
||||
if let Ok(slots) = database.list_connection_slots() {
|
||||
ensure_profile_not_bound_elsewhere(&slots, request.slot, &request.profile_id)?;
|
||||
}
|
||||
|
||||
let profile = database
|
||||
.profile(&request.profile_id)
|
||||
.map_err(|_| RuntimeCommandError {
|
||||
|
|
@ -527,8 +605,10 @@ pub async fn probe_connection_slot(
|
|||
#[tauri::command]
|
||||
pub async fn disconnect_connection_slot(
|
||||
runtime: State<'_, DualSlotRuntime>,
|
||||
guards: State<'_, RuntimeGuards>,
|
||||
request: DisconnectConnectionSlotRequest,
|
||||
) -> Result<(), RuntimeCommandError> {
|
||||
ensure_operations_runtime_change_allowed(&guards, request.slot, None, None)?;
|
||||
runtime.deactivate_slot(request.slot).await
|
||||
}
|
||||
|
||||
|
|
@ -629,31 +709,50 @@ pub async fn send_connection_slot_message(
|
|||
runtime: State<'_, DualSlotRuntime>,
|
||||
request: SendConnectionSlotMessageRequest,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
// Validate before touching history. This used to run the other way round,
|
||||
// so a send rejected for an empty message, a busy slot, or a disconnected
|
||||
// slot still left an unmarked `user` row behind — and each retry minted a
|
||||
// fresh `local-` id, appending another copy of the same question.
|
||||
runtime
|
||||
.ensure_slot_can_send(request.slot, &request.message)
|
||||
.await?;
|
||||
|
||||
let message_for_history = request.message.clone();
|
||||
let status = runtime.status().await;
|
||||
let initial_session = match request.slot {
|
||||
SlotKind::Companion => status.companion,
|
||||
SlotKind::Operations => status.operations,
|
||||
};
|
||||
if let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
|
||||
// One id for this send, so the failure path can address the row it wrote.
|
||||
let message_id = format!("local-{}", uuid::Uuid::new_v4());
|
||||
let persisted = match (
|
||||
initial_session.profile_id.as_deref(),
|
||||
initial_session.server_instance_id.as_deref(),
|
||||
initial_session.active_session_id.as_deref(),
|
||||
) {
|
||||
let _ = database.upsert_chat_message(
|
||||
"local-default",
|
||||
profile_id,
|
||||
slot_name(request.slot),
|
||||
server_instance_id,
|
||||
None,
|
||||
session_id,
|
||||
&format!("local-{}", uuid::Uuid::new_v4()),
|
||||
"user",
|
||||
&message_for_history,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
}
|
||||
(Some(profile_id), Some(server_instance_id), Some(session_id)) => {
|
||||
let _ = database.upsert_chat_message(
|
||||
"local-default",
|
||||
profile_id,
|
||||
slot_name(request.slot),
|
||||
server_instance_id,
|
||||
None,
|
||||
session_id,
|
||||
&message_id,
|
||||
"user",
|
||||
&message_for_history,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
Some((
|
||||
profile_id.to_owned(),
|
||||
server_instance_id.to_owned(),
|
||||
session_id.to_owned(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let result = runtime
|
||||
.send_slot_message(
|
||||
request.slot,
|
||||
|
|
@ -662,7 +761,8 @@ pub async fn send_connection_slot_message(
|
|||
request.attachments,
|
||||
)
|
||||
.await;
|
||||
if initial_session.active_session_id.is_none()
|
||||
|
||||
if persisted.is_none()
|
||||
&& let Ok(snapshot) = &result
|
||||
&& let (Some(profile_id), Some(server_instance_id), Some(session_id)) = (
|
||||
snapshot.profile_id.as_deref(),
|
||||
|
|
@ -677,15 +777,125 @@ pub async fn send_connection_slot_message(
|
|||
server_instance_id,
|
||||
None,
|
||||
session_id,
|
||||
&format!("local-{}", uuid::Uuid::new_v4()),
|
||||
&message_id,
|
||||
"user",
|
||||
&message_for_history,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
// A send the server never accepted must not leave a clean-looking row.
|
||||
// Marking rather than deleting keeps `chat_sessions.last_message_id` valid
|
||||
// and re-uses the idempotent upsert; unread counts ignore `user` rows.
|
||||
if let (Some((profile_id, server_instance_id, session_id)), Err(error)) = (&persisted, &result)
|
||||
&& !server_received(error.code)
|
||||
{
|
||||
let _ = database.upsert_chat_message(
|
||||
"local-default",
|
||||
profile_id,
|
||||
slot_name(request.slot),
|
||||
server_instance_id,
|
||||
None,
|
||||
session_id,
|
||||
&message_id,
|
||||
"user",
|
||||
&message_for_history,
|
||||
false,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
if let Ok(snapshot) = &result {
|
||||
persist_session_identity(&database, snapshot);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PROFILE_A: &str = "11111111-1111-1111-1111-111111111111";
|
||||
const PROFILE_B: &str = "22222222-2222-2222-2222-222222222222";
|
||||
const PROFILE_C: &str = "33333333-3333-3333-3333-333333333333";
|
||||
|
||||
fn slots_with(companion: Option<&str>, operations: Option<&str>) -> Vec<ConnectionSlot> {
|
||||
let mut companion_slot = ConnectionSlot::empty(ActiveSlotKind::Companion);
|
||||
companion_slot.profile_id = companion.map(str::to_owned);
|
||||
let mut operations_slot = ConnectionSlot::empty(ActiveSlotKind::Operations);
|
||||
operations_slot.profile_id = operations.map(str::to_owned);
|
||||
vec![companion_slot, operations_slot]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probing_a_profile_bound_to_the_other_slot_is_rejected() {
|
||||
let slots = slots_with(Some(PROFILE_A), None);
|
||||
|
||||
let error = ensure_profile_not_bound_elsewhere(&slots, SlotKind::Operations, PROFILE_A)
|
||||
.expect_err("a profile assigned to companion must not activate into operations");
|
||||
|
||||
assert_eq!(error.code, "profileAlreadyAssigned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_may_reconnect_the_slot_it_already_owns() {
|
||||
let slots = slots_with(Some(PROFILE_A), Some(PROFILE_B));
|
||||
|
||||
ensure_profile_not_bound_elsewhere(&slots, SlotKind::Companion, PROFILE_A)
|
||||
.expect("reconnecting the slot the profile already owns must stay allowed");
|
||||
|
||||
// A profile the slot table does not mention at all must also pass:
|
||||
// startup auto-connect activates from `auto_connect_slot` and never
|
||||
// writes `connection_slots`, so a positive rule would brick reconnect.
|
||||
ensure_profile_not_bound_elsewhere(&slots, SlotKind::Companion, PROFILE_C)
|
||||
.expect("an unassigned profile must not be blocked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn operations_runtime_changes_are_blocked_while_a_task_runs() {
|
||||
let guards = RuntimeGuards::new();
|
||||
guards
|
||||
.begin_operations_task("task-a")
|
||||
.expect("begin a task");
|
||||
|
||||
let error = ensure_operations_runtime_change_allowed(
|
||||
&guards,
|
||||
SlotKind::Operations,
|
||||
Some(PROFILE_A),
|
||||
Some(PROFILE_B),
|
||||
)
|
||||
.expect_err("switching the operations profile during a task must be refused");
|
||||
assert_eq!(error.code, "operationsSwitchLocked");
|
||||
|
||||
let error =
|
||||
ensure_operations_runtime_change_allowed(&guards, SlotKind::Operations, None, None)
|
||||
.expect_err("disconnecting operations during a task must be refused");
|
||||
assert_eq!(error.code, "operationsSwitchLocked");
|
||||
|
||||
ensure_operations_runtime_change_allowed(
|
||||
&guards,
|
||||
SlotKind::Operations,
|
||||
Some(PROFILE_A),
|
||||
Some(PROFILE_A),
|
||||
)
|
||||
.expect("reconnecting the profile the slot already holds must stay allowed");
|
||||
|
||||
ensure_operations_runtime_change_allowed(
|
||||
&guards,
|
||||
SlotKind::Companion,
|
||||
Some(PROFILE_A),
|
||||
Some(PROFILE_B),
|
||||
)
|
||||
.expect("the companion slot is not gated by the operations guard");
|
||||
|
||||
guards.end_operations_task("task-a").expect("end the task");
|
||||
ensure_operations_runtime_change_allowed(
|
||||
&guards,
|
||||
SlotKind::Operations,
|
||||
Some(PROFILE_A),
|
||||
Some(PROFILE_B),
|
||||
)
|
||||
.expect("the guard must release once no operations task remains");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,5 +16,5 @@ pub use gateway_client::{BoundGatewayEvent, GatewayClient, GatewayClientConfig,
|
|||
pub use manager::{DualConnectionManager, SlotKind};
|
||||
pub use runtime::{
|
||||
ConnectionRuntimeStatus, DualSlotRuntime, RuntimeCommandError, SlotActivationRequest,
|
||||
SlotRuntimeSnapshot,
|
||||
SlotRuntimeSnapshot, server_received,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -126,6 +126,110 @@ impl RuntimeCommandError {
|
|||
message,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancelled(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "cancelled",
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the wire code with `slots::SlotCommandError`, so the frontend
|
||||
/// needs no separate branch for the runtime-side rejection.
|
||||
pub fn profile_already_assigned() -> Self {
|
||||
Self {
|
||||
code: "profileAlreadyAssigned",
|
||||
message: "One connection profile cannot occupy both runtime slots.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn other_slot(slot: SlotKind) -> SlotKind {
|
||||
match slot {
|
||||
SlotKind::Companion => SlotKind::Operations,
|
||||
SlotKind::Operations => SlotKind::Companion,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether AstrBot already holds the message despite the send reporting an error.
|
||||
///
|
||||
/// `POST /api/v1/chat` appends the user's message as soon as it is accepted, so
|
||||
/// a cancellation or a mid-body break leaves the question in the remote
|
||||
/// conversation. The local history must match: those two codes keep the user
|
||||
/// row, everything else means the send never landed and the row is marked
|
||||
/// failed. Kept next to `astrbot_send_error`, which mints the codes.
|
||||
pub fn server_received(code: &str) -> bool {
|
||||
matches!(code, "cancelled" | "streamInterrupted")
|
||||
}
|
||||
|
||||
/// The conditions under which a slot will accept a chat send.
|
||||
///
|
||||
/// Shared by the read-only pre-flight and the send itself so the two cannot
|
||||
/// drift: the pre-flight is what lets the caller decide whether to write the
|
||||
/// optimistic user row at all.
|
||||
fn slot_send_precondition(runtime: &SlotRuntime) -> Result<(), RuntimeCommandError> {
|
||||
if runtime.message_cancellation.is_some() {
|
||||
return Err(RuntimeCommandError {
|
||||
code: "slotBusy",
|
||||
message: "This slot is already sending a message.",
|
||||
});
|
||||
}
|
||||
match runtime.client {
|
||||
Some(ActiveClient::AstrBot(_)) => Ok(()),
|
||||
Some(ActiveClient::Desktop(_)) => Err(RuntimeCommandError::unavailable(
|
||||
"Desktop mock chat send is not activated in this runtime path yet.",
|
||||
)),
|
||||
None => Err(RuntimeCommandError::unavailable(
|
||||
"The selected slot is not connected.",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client that has been constructed but not yet published into its slot.
|
||||
///
|
||||
/// Building the client is pure, so it happens before the slot lock is taken.
|
||||
enum PendingClient {
|
||||
Desktop(GatewayClient, String),
|
||||
AstrBot(AstrBotClient),
|
||||
}
|
||||
|
||||
/// The result of the out-of-lock reachability probe.
|
||||
enum ProbeOutcome {
|
||||
Connected,
|
||||
AuthFailed(&'static str),
|
||||
Unavailable(&'static str),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Rejects a write-back that belongs to a superseded activation.
|
||||
///
|
||||
/// Every activation and deactivation bumps `generation`, so a stale task that
|
||||
/// resumes after the slot was reset must not publish its result over the new
|
||||
/// occupant's state.
|
||||
fn ensure_generation(runtime: &SlotRuntime, expected: u64) -> Result<(), RuntimeCommandError> {
|
||||
if runtime.generation == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RuntimeCommandError::cancelled(
|
||||
"The request was cancelled because the slot changed.",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes a session switch onto the generation that requested it.
|
||||
///
|
||||
/// The slot lock is released while `set_session_id` runs. Without this check a
|
||||
/// deactivation or re-activation in that window would have the old session id
|
||||
/// written onto the new occupant's snapshot, and `persist_session_identity`
|
||||
/// would then copy it into that profile's sticky session.
|
||||
fn commit_session_id(
|
||||
runtime: &mut SlotRuntime,
|
||||
expected: u64,
|
||||
session_id: String,
|
||||
) -> Result<SlotRuntimeSnapshot, RuntimeCommandError> {
|
||||
ensure_generation(runtime, expected)?;
|
||||
runtime.snapshot.active_session_id = Some(session_id);
|
||||
Ok(runtime.snapshot.clone())
|
||||
}
|
||||
|
||||
impl DualSlotRuntime {
|
||||
|
|
@ -194,32 +298,13 @@ impl DualSlotRuntime {
|
|||
));
|
||||
}
|
||||
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, request.slot);
|
||||
if let Some(cancellation) = runtime.connection_cancellation.take() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
if let Some(cancellation) = runtime.message_cancellation.take() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
let generation = runtime.generation.wrapping_add(1);
|
||||
*runtime = SlotRuntime {
|
||||
snapshot: SlotRuntimeSnapshot {
|
||||
slot: request.slot,
|
||||
profile_id: Some(request.profile_id.clone()),
|
||||
transport: Some(request.transport),
|
||||
state: ConnectionState::Connecting,
|
||||
server_instance_id: None,
|
||||
active_session_id: request.session_id.clone(),
|
||||
last_error: None,
|
||||
},
|
||||
client: None,
|
||||
connection_cancellation: None,
|
||||
message_cancellation: None,
|
||||
generation,
|
||||
};
|
||||
|
||||
match request.transport {
|
||||
// Phase 0: validate the request and build the client with no lock held.
|
||||
//
|
||||
// This used to run *after* the slot had already been overwritten with a
|
||||
// `Connecting` snapshot, so a rejected request tore down a working
|
||||
// connection and then parked the slot in `Connecting` forever, with no
|
||||
// client and no `last_error`.
|
||||
let pending = match request.transport {
|
||||
TransportKind::DesktopV1 => {
|
||||
let expected = request
|
||||
.expected_server_instance_id
|
||||
|
|
@ -240,29 +325,7 @@ impl DualSlotRuntime {
|
|||
.map_err(|_| {
|
||||
RuntimeCommandError::unavailable("Desktop gateway client failed to start.")
|
||||
})?;
|
||||
match client.health().await {
|
||||
Ok(_) => {
|
||||
runtime.snapshot.state = ConnectionState::Connected;
|
||||
runtime.snapshot.server_instance_id = Some(expected);
|
||||
runtime.client = Some(ActiveClient::Desktop(client));
|
||||
}
|
||||
Err(GatewayError::HttpStatus(status)) if status.as_u16() == 401 => {
|
||||
runtime.snapshot.state = ConnectionState::AuthExpired;
|
||||
runtime.snapshot.last_error =
|
||||
Some("Desktop gateway authentication failed.".into());
|
||||
return Err(RuntimeCommandError::unavailable(
|
||||
"Desktop gateway authentication failed.",
|
||||
));
|
||||
}
|
||||
Err(_) => {
|
||||
runtime.snapshot.state = ConnectionState::ServerUnavailable;
|
||||
runtime.snapshot.last_error =
|
||||
Some("Desktop gateway health check failed.".into());
|
||||
return Err(RuntimeCommandError::unavailable(
|
||||
"Desktop gateway health check failed.",
|
||||
));
|
||||
}
|
||||
}
|
||||
PendingClient::Desktop(client, expected)
|
||||
}
|
||||
TransportKind::AstrBotOpenApi => {
|
||||
let api_key = request.api_key.clone().ok_or_else(|| {
|
||||
|
|
@ -295,42 +358,140 @@ impl DualSlotRuntime {
|
|||
},
|
||||
_ => RuntimeCommandError::unavailable("AstrBot client failed to start."),
|
||||
})?;
|
||||
match client.probe().await {
|
||||
Ok(_) => {
|
||||
runtime.snapshot.state = ConnectionState::Connected;
|
||||
runtime.snapshot.server_instance_id =
|
||||
Some(client.server_instance_id_blocking());
|
||||
runtime.client = Some(ActiveClient::AstrBot(client));
|
||||
PendingClient::AstrBot(client)
|
||||
}
|
||||
};
|
||||
|
||||
// Phase 1: claim the slot. One critical section, no await inside it.
|
||||
//
|
||||
// The cancellation token is installed here rather than after a
|
||||
// successful probe, so an activation against an unreachable address can
|
||||
// be interrupted by `deactivate_slot`.
|
||||
let (generation, cancellation) = {
|
||||
let mut guard = self.inner.lock().await;
|
||||
|
||||
// One profile may not occupy both runtime slots. The rule is
|
||||
// deliberately negative — it only inspects the *other* slot — so
|
||||
// re-activating the same slot with the same profile (a reconnect)
|
||||
// is unaffected. Enforcing it here rather than at the command layer
|
||||
// also covers startup auto-connect, which calls this directly.
|
||||
if slot_ref(&guard, other_slot(request.slot))
|
||||
.snapshot
|
||||
.profile_id
|
||||
.as_deref()
|
||||
== Some(request.profile_id.as_str())
|
||||
{
|
||||
return Err(RuntimeCommandError::profile_already_assigned());
|
||||
}
|
||||
|
||||
let runtime = slot_mut(&mut guard, request.slot);
|
||||
if let Some(cancellation) = runtime.connection_cancellation.take() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
if let Some(cancellation) = runtime.message_cancellation.take() {
|
||||
cancellation.cancel();
|
||||
}
|
||||
let generation = runtime.generation.wrapping_add(1);
|
||||
let cancellation = Arc::new(tokio_util::sync::CancellationToken::new());
|
||||
*runtime = SlotRuntime {
|
||||
snapshot: SlotRuntimeSnapshot {
|
||||
slot: request.slot,
|
||||
profile_id: Some(request.profile_id.clone()),
|
||||
transport: Some(request.transport),
|
||||
state: ConnectionState::Connecting,
|
||||
server_instance_id: None,
|
||||
active_session_id: request.session_id.clone(),
|
||||
last_error: None,
|
||||
},
|
||||
client: None,
|
||||
connection_cancellation: Some(Arc::clone(&cancellation)),
|
||||
message_cancellation: None,
|
||||
generation,
|
||||
};
|
||||
(generation, cancellation)
|
||||
};
|
||||
|
||||
// Phase 2: probe outside the lock.
|
||||
//
|
||||
// The probe uses the REST client, whose total timeout is 120s. Holding
|
||||
// the runtime lock across it blocked every command on *both* slots —
|
||||
// status polling, sending, cancelling, disconnecting — for as long as
|
||||
// one unreachable address took to time out.
|
||||
let outcome = match &pending {
|
||||
PendingClient::Desktop(client, _) => tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => ProbeOutcome::Cancelled,
|
||||
result = client.health() => match result {
|
||||
Ok(_) => ProbeOutcome::Connected,
|
||||
Err(GatewayError::HttpStatus(status)) if status.as_u16() == 401 => {
|
||||
ProbeOutcome::AuthFailed("Desktop gateway authentication failed.")
|
||||
}
|
||||
Err(error) => {
|
||||
runtime.snapshot.state = match error {
|
||||
super::AstrBotClientError::HttpStatus(status)
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 =>
|
||||
{
|
||||
ConnectionState::AuthExpired
|
||||
}
|
||||
_ => ConnectionState::ServerUnavailable,
|
||||
};
|
||||
runtime.snapshot.last_error = Some("AstrBot probe failed.".into());
|
||||
return Err(RuntimeCommandError::unavailable("AstrBot probe failed."));
|
||||
Err(_) => ProbeOutcome::Unavailable("Desktop gateway health check failed."),
|
||||
},
|
||||
},
|
||||
PendingClient::AstrBot(client) => tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => ProbeOutcome::Cancelled,
|
||||
result = client.probe() => match result {
|
||||
Ok(_) => ProbeOutcome::Connected,
|
||||
Err(AstrBotClientError::HttpStatus(status))
|
||||
if status.as_u16() == 401 || status.as_u16() == 403 =>
|
||||
{
|
||||
ProbeOutcome::AuthFailed("AstrBot probe failed.")
|
||||
}
|
||||
Err(_) => ProbeOutcome::Unavailable("AstrBot probe failed."),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Phase 3: publish the result, but only if this activation still owns
|
||||
// the slot.
|
||||
let (snapshot, listener_client) = {
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, request.slot);
|
||||
ensure_generation(runtime, generation)?;
|
||||
match outcome {
|
||||
ProbeOutcome::Cancelled => {
|
||||
*runtime = SlotRuntime::empty_with_generation(request.slot, generation);
|
||||
return Err(RuntimeCommandError::cancelled(
|
||||
"The connection attempt was cancelled.",
|
||||
));
|
||||
}
|
||||
ProbeOutcome::AuthFailed(message) => {
|
||||
runtime.snapshot.state = ConnectionState::AuthExpired;
|
||||
runtime.snapshot.last_error = Some(message.to_owned());
|
||||
runtime.connection_cancellation = None;
|
||||
return Err(RuntimeCommandError::unavailable(message));
|
||||
}
|
||||
ProbeOutcome::Unavailable(message) => {
|
||||
runtime.snapshot.state = ConnectionState::ServerUnavailable;
|
||||
runtime.snapshot.last_error = Some(message.to_owned());
|
||||
runtime.connection_cancellation = None;
|
||||
return Err(RuntimeCommandError::unavailable(message));
|
||||
}
|
||||
ProbeOutcome::Connected => {
|
||||
let (server_instance_id, client) = match pending {
|
||||
PendingClient::Desktop(client, expected) => {
|
||||
(expected, ActiveClient::Desktop(client))
|
||||
}
|
||||
PendingClient::AstrBot(client) => (
|
||||
client.server_instance_id_blocking(),
|
||||
ActiveClient::AstrBot(client),
|
||||
),
|
||||
};
|
||||
runtime.snapshot.state = ConnectionState::Connected;
|
||||
runtime.snapshot.server_instance_id = Some(server_instance_id);
|
||||
runtime.client = Some(client);
|
||||
(runtime.snapshot.clone(), runtime.client.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let listener_client = runtime.client.clone();
|
||||
let connection_cancellation = Arc::new(tokio_util::sync::CancellationToken::new());
|
||||
runtime.connection_cancellation = Some(connection_cancellation.clone());
|
||||
let snapshot = runtime.snapshot.clone();
|
||||
drop(guard);
|
||||
};
|
||||
|
||||
if let Some(client) = listener_client {
|
||||
self.start_connection_listener(
|
||||
request.slot,
|
||||
generation,
|
||||
client,
|
||||
connection_cancellation,
|
||||
);
|
||||
// The same token installed in phase 1. Creating a second one here
|
||||
// would leave `deactivate_slot` cancelling a token that no listener
|
||||
// observes, so the reconnect loop would outlive the disconnect.
|
||||
self.start_connection_listener(request.slot, generation, client, cancellation);
|
||||
}
|
||||
|
||||
Ok(snapshot)
|
||||
|
|
@ -450,9 +611,10 @@ impl DualSlotRuntime {
|
|||
if session_id.trim().is_empty() {
|
||||
return Err(RuntimeCommandError::validation("session_id is required."));
|
||||
}
|
||||
let client = {
|
||||
let (client, generation) = {
|
||||
let guard = self.inner.lock().await;
|
||||
match slot_ref(&guard, slot).client.as_ref() {
|
||||
let runtime = slot_ref(&guard, slot);
|
||||
let client = match runtime.client.as_ref() {
|
||||
Some(ActiveClient::AstrBot(client)) => client.clone(),
|
||||
Some(ActiveClient::Desktop(_)) => {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
|
|
@ -464,16 +626,15 @@ impl DualSlotRuntime {
|
|||
"Activate the connection before switching sessions.",
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
(client, runtime.generation)
|
||||
};
|
||||
client
|
||||
.set_session_id(session_id.clone())
|
||||
.await
|
||||
.map_err(|_| RuntimeCommandError::validation("The session id is invalid."))?;
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, slot);
|
||||
runtime.snapshot.active_session_id = Some(session_id);
|
||||
Ok(runtime.snapshot.clone())
|
||||
commit_session_id(slot_mut(&mut guard, slot), generation, session_id)
|
||||
}
|
||||
|
||||
pub async fn slot_capabilities(
|
||||
|
|
@ -558,6 +719,24 @@ impl DualSlotRuntime {
|
|||
.map_err(|_| RuntimeCommandError::unavailable("AstrBot file upload failed."))
|
||||
}
|
||||
|
||||
/// Read-only pre-flight for a chat send.
|
||||
///
|
||||
/// Lets the caller learn that a send will be refused *before* it writes the
|
||||
/// optimistic user row into history, so a rejected send leaves no trace.
|
||||
pub async fn ensure_slot_can_send(
|
||||
&self,
|
||||
slot: SlotKind,
|
||||
message: &str,
|
||||
) -> Result<(), RuntimeCommandError> {
|
||||
if message.trim().is_empty() {
|
||||
return Err(RuntimeCommandError::validation(
|
||||
"message must not be empty.",
|
||||
));
|
||||
}
|
||||
let guard = self.inner.lock().await;
|
||||
slot_send_precondition(slot_ref(&guard, slot))
|
||||
}
|
||||
|
||||
pub async fn send_slot_message(
|
||||
&self,
|
||||
slot: SlotKind,
|
||||
|
|
@ -591,12 +770,7 @@ impl DualSlotRuntime {
|
|||
) = {
|
||||
let mut guard = self.inner.lock().await;
|
||||
let runtime = slot_mut(&mut guard, slot);
|
||||
if runtime.message_cancellation.is_some() {
|
||||
return Err(RuntimeCommandError {
|
||||
code: "slotBusy",
|
||||
message: "This slot is already sending a message.",
|
||||
});
|
||||
}
|
||||
slot_send_precondition(runtime)?;
|
||||
let client = runtime.client.clone().ok_or_else(|| {
|
||||
RuntimeCommandError::unavailable("The selected slot is not connected.")
|
||||
})?;
|
||||
|
|
@ -763,6 +937,252 @@ fn slot_mut(inner: &mut DualSlotRuntimeInner, slot: SlotKind) -> &mut SlotRuntim
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PROFILE_A: &str = "11111111-1111-1111-1111-111111111111";
|
||||
|
||||
/// Accepts connections and never answers, so a probe stays in flight.
|
||||
///
|
||||
/// Deliberately hand-rolled rather than reusing the fake server in
|
||||
/// `astrbot_client`'s transport tests: those belong to the R2 batch and
|
||||
/// must not be reshaped to serve a different module.
|
||||
async fn spawn_unresponsive_server() -> String {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("bind a loopback listener");
|
||||
let address = listener.local_addr().expect("read the bound address");
|
||||
tokio::spawn(async move {
|
||||
let mut held = Vec::new();
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
held.push(stream);
|
||||
}
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
fn astrbot_request(slot: SlotKind, profile_id: &str, base_url: &str) -> SlotActivationRequest {
|
||||
SlotActivationRequest {
|
||||
profile_id: profile_id.into(),
|
||||
slot,
|
||||
base_url: base_url.into(),
|
||||
transport: TransportKind::AstrBotOpenApi,
|
||||
api_key: Some(SecretString::from("abk_test".to_owned())),
|
||||
bearer_token: None,
|
||||
remote_username: Some("tester".into()),
|
||||
remote_display_name: None,
|
||||
authentication_type: desktop_protocol::AuthenticationType::DeviceToken,
|
||||
session_id: None,
|
||||
expected_server_instance_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_connecting(runtime: &DualSlotRuntime, slot: SlotKind) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
let status = runtime.status().await;
|
||||
let snapshot = match slot {
|
||||
SlotKind::Companion => status.companion,
|
||||
SlotKind::Operations => status.operations,
|
||||
};
|
||||
if snapshot.state == ConnectionState::Connecting {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the connecting snapshot must be published before the probe finishes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn activation_publishes_connecting_without_holding_the_slot_lock() {
|
||||
let base_url = spawn_unresponsive_server().await;
|
||||
let runtime = Arc::new(DualSlotRuntime::new());
|
||||
|
||||
let activation = {
|
||||
let runtime = Arc::clone(&runtime);
|
||||
tokio::spawn(async move {
|
||||
runtime
|
||||
.activate_slot(astrbot_request(SlotKind::Companion, PROFILE_A, &base_url))
|
||||
.await
|
||||
})
|
||||
};
|
||||
|
||||
wait_for_connecting(&runtime, SlotKind::Companion).await;
|
||||
|
||||
// The probe is still in flight. Before this fix the runtime lock was
|
||||
// held across it, so both slots were frozen for up to 120 seconds.
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
runtime.deactivate_slot(SlotKind::Operations),
|
||||
)
|
||||
.await
|
||||
.expect("an in-flight probe must not block the other slot")
|
||||
.expect("deactivating the idle slot should succeed");
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(5), runtime.status())
|
||||
.await
|
||||
.expect("an in-flight probe must not block status reads");
|
||||
|
||||
activation.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn activation_is_cancelled_by_disconnect() {
|
||||
let base_url = spawn_unresponsive_server().await;
|
||||
let runtime = Arc::new(DualSlotRuntime::new());
|
||||
|
||||
let activation = {
|
||||
let runtime = Arc::clone(&runtime);
|
||||
tokio::spawn(async move {
|
||||
runtime
|
||||
.activate_slot(astrbot_request(SlotKind::Companion, PROFILE_A, &base_url))
|
||||
.await
|
||||
})
|
||||
};
|
||||
|
||||
wait_for_connecting(&runtime, SlotKind::Companion).await;
|
||||
|
||||
runtime
|
||||
.deactivate_slot(SlotKind::Companion)
|
||||
.await
|
||||
.expect("disconnect during activation should succeed");
|
||||
|
||||
let error = tokio::time::timeout(Duration::from_secs(5), activation)
|
||||
.await
|
||||
.expect("the activation must end once it is cancelled")
|
||||
.expect("the activation task should not panic")
|
||||
.expect_err("a cancelled activation must not report success");
|
||||
assert_eq!(error.code, "cancelled");
|
||||
|
||||
// The write-back must not resurrect the slot the disconnect cleared.
|
||||
let companion = runtime.status().await.companion;
|
||||
assert_eq!(companion.state, ConnectionState::Disconnected);
|
||||
assert!(companion.profile_id.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_the_same_profile_in_both_runtime_slots() {
|
||||
let base_url = spawn_unresponsive_server().await;
|
||||
let runtime = Arc::new(DualSlotRuntime::new());
|
||||
|
||||
let activation = {
|
||||
let runtime = Arc::clone(&runtime);
|
||||
let base_url = base_url.clone();
|
||||
tokio::spawn(async move {
|
||||
runtime
|
||||
.activate_slot(astrbot_request(SlotKind::Companion, PROFILE_A, &base_url))
|
||||
.await
|
||||
})
|
||||
};
|
||||
|
||||
wait_for_connecting(&runtime, SlotKind::Companion).await;
|
||||
|
||||
// The rejection must land before any network work, which is only
|
||||
// observable because the snapshot is published ahead of the probe.
|
||||
let error = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
runtime.activate_slot(astrbot_request(SlotKind::Operations, PROFILE_A, &base_url)),
|
||||
)
|
||||
.await
|
||||
.expect("the rejection must not wait on a probe")
|
||||
.expect_err("one profile must not occupy both runtime slots");
|
||||
assert_eq!(error.code, "profileAlreadyAssigned");
|
||||
|
||||
assert!(runtime.status().await.operations.profile_id.is_none());
|
||||
|
||||
activation.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_activation_leaves_the_slot_untouched() {
|
||||
let runtime = DualSlotRuntime::new();
|
||||
let mut request = astrbot_request(SlotKind::Companion, PROFILE_A, "http://127.0.0.1:9");
|
||||
request.api_key = None;
|
||||
|
||||
let error = runtime
|
||||
.activate_slot(request)
|
||||
.await
|
||||
.expect_err("an activation without an API key must be rejected");
|
||||
assert_eq!(error.code, "validationFailed");
|
||||
|
||||
// Validation now runs before the slot is claimed. It used to run after
|
||||
// the `Connecting` snapshot had been written, which left the slot stuck
|
||||
// in `Connecting` with no client and no error to explain it.
|
||||
let companion = runtime.status().await.companion;
|
||||
assert_eq!(companion.state, ConnectionState::Disconnected);
|
||||
assert!(companion.profile_id.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_disconnected_slot_rejects_sends_before_any_history_write() {
|
||||
let runtime = DualSlotRuntime::new();
|
||||
|
||||
let error = runtime
|
||||
.ensure_slot_can_send(SlotKind::Companion, "hello")
|
||||
.await
|
||||
.expect_err("a disconnected slot must refuse the send up front");
|
||||
assert_eq!(error.code, "runtimeUnavailable");
|
||||
|
||||
let error = runtime
|
||||
.ensure_slot_can_send(SlotKind::Companion, " ")
|
||||
.await
|
||||
.expect_err("an empty message must be refused up front");
|
||||
assert_eq!(error.code, "validationFailed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_received_covers_every_send_error_code() {
|
||||
// The two codes that mean AstrBot already appended the question, so the
|
||||
// local user row must survive the failure.
|
||||
assert!(server_received(
|
||||
astrbot_send_error(&AstrBotClientError::StreamInterrupted).code
|
||||
));
|
||||
assert!(server_received("cancelled"));
|
||||
|
||||
// Everything else means the send never landed. If R2 ever renames one
|
||||
// of these codes, this assertion is what catches the silent change.
|
||||
for error in [
|
||||
AstrBotClientError::CredentialExpired,
|
||||
AstrBotClientError::HttpStatus(reqwest::StatusCode::INTERNAL_SERVER_ERROR),
|
||||
AstrBotClientError::ApiStatus("rejected".into()),
|
||||
AstrBotClientError::Map("bad frame".into()),
|
||||
AstrBotClientError::ServerIdentityChanged,
|
||||
AstrBotClientError::ChannelClosed,
|
||||
AstrBotClientError::InvalidConfig("bad config"),
|
||||
] {
|
||||
let mapped = astrbot_send_error(&error);
|
||||
assert!(
|
||||
!server_received(mapped.code),
|
||||
"{} must not be treated as delivered",
|
||||
mapped.code
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_session_switch_does_not_write_into_a_new_generation() {
|
||||
let mut runtime = SlotRuntime::empty_with_generation(SlotKind::Companion, 7);
|
||||
|
||||
let error = commit_session_id(&mut runtime, 6, "session-old".into())
|
||||
.expect_err("a switch from a superseded generation must be rejected");
|
||||
|
||||
assert_eq!(error.code, "cancelled");
|
||||
assert!(runtime.snapshot.active_session_id.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_current_session_switch_updates_the_snapshot() {
|
||||
let mut runtime = SlotRuntime::empty_with_generation(SlotKind::Companion, 7);
|
||||
|
||||
let snapshot = commit_session_id(&mut runtime, 7, "session-new".into())
|
||||
.expect("a switch from the current generation should be published");
|
||||
|
||||
assert_eq!(snapshot.active_session_id.as_deref(), Some("session-new"));
|
||||
assert_eq!(
|
||||
runtime.snapshot.active_session_id.as_deref(),
|
||||
Some("session-new")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_astrbot_activation_without_username_or_key() {
|
||||
let runtime = DualSlotRuntime::new();
|
||||
|
|
|
|||
21
src/App.tsx
21
src/App.tsx
|
|
@ -390,13 +390,22 @@ function InAppPetOverlay() {
|
|||
}, [clampPosition, position.x, position.y]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let unlisten: (() => void) | undefined;
|
||||
void listen("pet-hide-requested", () => setVisible(false)).then(
|
||||
(cleanup) => {
|
||||
unlisten = cleanup;
|
||||
},
|
||||
);
|
||||
return () => unlisten?.();
|
||||
void listen("pet-hide-requested", () => setVisible(false))
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
unlisten = cleanup;
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
active = false;
|
||||
unlisten?.();
|
||||
unlisten = undefined;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return visible ? (
|
||||
|
|
|
|||
199
src/features/chat/ChatPanel.test.tsx
普通文件
199
src/features/chat/ChatPanel.test.tsx
普通文件
|
|
@ -0,0 +1,199 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { StrictMode } from "react";
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
activeListeners,
|
||||
emitTauriEvent,
|
||||
flushListen,
|
||||
} from "../../test/tauriEvent";
|
||||
import { ChatPanel } from "./ChatPanel";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: vi.fn(),
|
||||
}));
|
||||
|
||||
const PROFILE_ID = "11111111-1111-1111-1111-111111111111";
|
||||
const SERVER_INSTANCE_ID = "server-1";
|
||||
const SESSION_ID = "session-1";
|
||||
|
||||
function connectedSnapshot(slot: "companion" | "operations") {
|
||||
return {
|
||||
slot,
|
||||
profileId: PROFILE_ID,
|
||||
transport: "astr-bot-open-api",
|
||||
state: "connected",
|
||||
serverInstanceId: SERVER_INSTANCE_ID,
|
||||
activeSessionId: SESSION_ID,
|
||||
lastError: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mockChatCommands(options?: {
|
||||
fileUpload?: boolean;
|
||||
onSend?: (payload: unknown) => unknown;
|
||||
}) {
|
||||
vi.mocked(invoke).mockImplementation(
|
||||
async (command: string, payload?: unknown) => {
|
||||
switch (command) {
|
||||
case "connection_runtime_status":
|
||||
return {
|
||||
companion: connectedSnapshot("companion"),
|
||||
operations: connectedSnapshot("operations"),
|
||||
};
|
||||
case "list_chat_sessions":
|
||||
case "connection_slot_sessions":
|
||||
case "load_chat_messages":
|
||||
return [];
|
||||
case "connection_slot_capabilities":
|
||||
return {
|
||||
transport: "astrbot-openapi",
|
||||
textChat: true,
|
||||
streaming: true,
|
||||
modelSelection: false,
|
||||
fileUpload: options?.fileUpload ?? false,
|
||||
imageInput: false,
|
||||
models: [],
|
||||
};
|
||||
case "upload_connection_slot_file":
|
||||
return {
|
||||
attachmentId: "attachment-1",
|
||||
fileName: "note.txt",
|
||||
mimeType: "text/plain",
|
||||
sizeBytes: 4,
|
||||
};
|
||||
case "send_connection_slot_message":
|
||||
if (options?.onSend) return options.onSend(payload);
|
||||
return connectedSnapshot("companion");
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders with the slot tabs enabled, then waits for the first status poll. */
|
||||
async function renderWithTabs() {
|
||||
const view = render(<ChatPanel />);
|
||||
await flushListen();
|
||||
await screen.findByRole("tab", { name: /陪伴/ });
|
||||
return view;
|
||||
}
|
||||
|
||||
function selectSlot(name: RegExp) {
|
||||
fireEvent.click(screen.getByRole("tab", { name }));
|
||||
}
|
||||
|
||||
function composer() {
|
||||
return screen.getByLabelText("聊天消息");
|
||||
}
|
||||
|
||||
function deltaEvent(delta: string) {
|
||||
return {
|
||||
profileId: PROFILE_ID,
|
||||
slot: "companion",
|
||||
eventId: "astrbot-server-1-stream-1",
|
||||
eventType: "message.delta",
|
||||
serverInstanceId: SERVER_INSTANCE_ID,
|
||||
sessionId: SESSION_ID,
|
||||
messageId: "message-1",
|
||||
payload: { delta },
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockChatCommands();
|
||||
});
|
||||
|
||||
it("applies each streaming delta once under strict mode", async () => {
|
||||
render(
|
||||
<StrictMode>
|
||||
<ChatPanel fixedSlot="companion" />
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
// StrictMode mounts, cleans up, then mounts again. The first listener used to
|
||||
// survive that cleanup because `listen()` had not resolved yet, so every
|
||||
// delta was applied twice.
|
||||
await flushListen();
|
||||
emitTauriEvent("connection-runtime-event", deltaEvent("你好"));
|
||||
|
||||
expect(await screen.findByText("你好")).toBeInTheDocument();
|
||||
expect(screen.queryByText("你好你好")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("releases every listener on unmount", async () => {
|
||||
const view = render(<ChatPanel fixedSlot="companion" />);
|
||||
|
||||
view.unmount();
|
||||
// Settling *after* unmount is the real leak path: the cleanup has already
|
||||
// run, so the resolved unregister function must be called immediately.
|
||||
await flushListen();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(activeListeners("connection-runtime-event")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps drafts on the slot they were typed in", async () => {
|
||||
await renderWithTabs();
|
||||
|
||||
fireEvent.change(composer(), { target: { value: "写给陪伴的" } });
|
||||
expect(composer()).toHaveValue("写给陪伴的");
|
||||
|
||||
selectSlot(/运维/);
|
||||
expect(composer()).toHaveValue("");
|
||||
|
||||
selectSlot(/陪伴/);
|
||||
expect(composer()).toHaveValue("写给陪伴的");
|
||||
});
|
||||
|
||||
it("keeps attachments on the slot they were uploaded to", async () => {
|
||||
mockChatCommands({ fileUpload: true });
|
||||
await renderWithTabs();
|
||||
|
||||
const picker = screen.getByText("添加图片/文件").parentElement
|
||||
?.children[1] as HTMLInputElement;
|
||||
fireEvent.change(picker, {
|
||||
target: { files: [new File(["note"], "note.txt", { type: "text/plain" })] },
|
||||
});
|
||||
expect(await screen.findByLabelText("移除 note.txt")).toBeInTheDocument();
|
||||
|
||||
selectSlot(/运维/);
|
||||
expect(screen.queryByLabelText("移除 note.txt")).not.toBeInTheDocument();
|
||||
|
||||
// Sending from the other slot must not pick up the companion's attachment.
|
||||
fireEvent.change(composer(), { target: { value: "运维消息" } });
|
||||
fireEvent.submit(composer().closest("form") as HTMLFormElement);
|
||||
await waitFor(() => {
|
||||
expect(invoke).toHaveBeenCalledWith("send_connection_slot_message", {
|
||||
request: { slot: "operations", message: "运维消息", attachments: [] },
|
||||
});
|
||||
});
|
||||
|
||||
selectSlot(/陪伴/);
|
||||
expect(screen.getByLabelText("移除 note.txt")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows an error banner only on the slot that produced it", async () => {
|
||||
mockChatCommands({
|
||||
onSend: () => {
|
||||
throw { code: "runtimeUnavailable", message: "未连接到 AstrBot。" };
|
||||
},
|
||||
});
|
||||
await renderWithTabs();
|
||||
|
||||
fireEvent.change(composer(), { target: { value: "在线吗" } });
|
||||
fireEvent.submit(composer().closest("form") as HTMLFormElement);
|
||||
|
||||
// Also asserts the shared errorMessage() shape rather than [object Object],
|
||||
// and that the 500ms status poll no longer wipes an action error.
|
||||
expect(await screen.findByText("未连接到 AstrBot。")).toBeInTheDocument();
|
||||
|
||||
selectSlot(/运维/);
|
||||
expect(screen.queryByText("未连接到 AstrBot。")).not.toBeInTheDocument();
|
||||
|
||||
selectSlot(/陪伴/);
|
||||
expect(screen.getByText("未连接到 AstrBot。")).toBeInTheDocument();
|
||||
});
|
||||
|
|
@ -74,13 +74,28 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const historySessionId =
|
||||
selectedSessionId ?? storedSessions[selectedSlot][0]?.sessionId;
|
||||
const selectedTransport = selectedSnapshot.transport;
|
||||
const [draft, setDraft] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<Record<ChatSlot, string>>({
|
||||
companion: "",
|
||||
operations: "",
|
||||
});
|
||||
// Two separate errors on purpose. `refresh()` runs every 500ms and used to
|
||||
// write the shared error on failure and clear it on success, so any send or
|
||||
// upload error was wiped within half a second. The polling failure describes
|
||||
// the IPC channel, not a slot, so it keeps its own state and the per-slot
|
||||
// error is owned solely by user actions.
|
||||
const [runtimeError, setRuntimeError] = useState<string | null>(null);
|
||||
const [slotError, setSlotError] = useState<Record<ChatSlot, string | null>>({
|
||||
companion: null,
|
||||
operations: null,
|
||||
});
|
||||
const [capabilities, setCapabilities] =
|
||||
useState<AstrBotCapabilitySnapshot | null>(null);
|
||||
const [pendingAttachments, setPendingAttachments] = useState<
|
||||
AstrBotAttachment[]
|
||||
>([]);
|
||||
Record<ChatSlot, AstrBotAttachment[]>
|
||||
>({
|
||||
companion: [],
|
||||
operations: [],
|
||||
});
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [voiceListening, setVoiceListening] = useState(false);
|
||||
const [sending, setSending] = useState<Record<ChatSlot, boolean>>({
|
||||
|
|
@ -95,6 +110,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
companion: 0,
|
||||
operations: 0,
|
||||
});
|
||||
const selectedAttachments = pendingAttachments[selectedSlot];
|
||||
// A slot-scoped action error wins over the runtime-wide polling error.
|
||||
const visibleError = slotError[selectedSlot] ?? runtimeError;
|
||||
const activeMessages = useMemo(
|
||||
() =>
|
||||
messages.filter(
|
||||
|
|
@ -130,29 +148,49 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const result = await invoke<unknown>("connection_runtime_status");
|
||||
const parsed = connectionRuntimeStatusSchema.safeParse(result);
|
||||
if (!parsed.success) {
|
||||
setError("连接状态暂不可用,请检查连接配置。");
|
||||
setRuntimeError("连接状态暂不可用,请检查连接配置。");
|
||||
return false;
|
||||
}
|
||||
setStatus(parsed.data);
|
||||
setError(null);
|
||||
setRuntimeError(null);
|
||||
return true;
|
||||
} catch {
|
||||
setError("连接状态暂不可用,请检查本地运行时。");
|
||||
setRuntimeError("连接状态暂不可用,请检查本地运行时。");
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const reportSlotError = (slot: ChatSlot, message: string | null) => {
|
||||
setSlotError((current) => ({ ...current, [slot]: message }));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// `listen()` resolves after the effect may already have been cleaned up.
|
||||
// Assigning the unregister function unconditionally dropped it in that
|
||||
// case, and under StrictMode's mount/cleanup/mount the first listener
|
||||
// leaked permanently — every delta was then applied twice, doubling each
|
||||
// character of the streamed reply.
|
||||
let active = true;
|
||||
let unlisten: (() => void) | undefined;
|
||||
void listen<unknown>("connection-runtime-event", (event) => {
|
||||
const parsed = boundRuntimeEventSchema.safeParse(event.payload);
|
||||
if (parsed.success) {
|
||||
setMessages((current) => applyRuntimeEvents(current, [parsed.data]));
|
||||
}
|
||||
}).then((cleanup) => {
|
||||
unlisten = cleanup;
|
||||
});
|
||||
return () => unlisten?.();
|
||||
})
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
unlisten = cleanup;
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
active = false;
|
||||
unlisten?.();
|
||||
unlisten = undefined;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
|
|
@ -356,8 +394,12 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
|
||||
const uploadFiles = async (files: FileList | null) => {
|
||||
if (!files?.length) return;
|
||||
// Pin the slot for the whole action. An upload that resolves after the user
|
||||
// switched tabs must land on the slot it was uploaded to, not the one that
|
||||
// happens to be selected when the promise settles.
|
||||
const slot = selectedSlot;
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
reportSlotError(slot, null);
|
||||
try {
|
||||
const uploaded: AstrBotAttachment[] = [];
|
||||
for (const file of Array.from(files)) {
|
||||
|
|
@ -366,7 +408,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const bytes = Array.from(new Uint8Array(await file.arrayBuffer()));
|
||||
const result = await invoke<unknown>("upload_connection_slot_file", {
|
||||
request: {
|
||||
slot: selectedSlot,
|
||||
slot,
|
||||
fileName: file.name,
|
||||
mimeType: file.type || "application/octet-stream",
|
||||
bytes,
|
||||
|
|
@ -374,30 +416,37 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
});
|
||||
uploaded.push(astrbotAttachmentSchema.parse(result));
|
||||
}
|
||||
setPendingAttachments((current) => current.concat(uploaded));
|
||||
setPendingAttachments((current) => ({
|
||||
...current,
|
||||
[slot]: current[slot].concat(uploaded),
|
||||
}));
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason));
|
||||
reportSlotError(slot, errorMessage(reason));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const send = async (messageOverride?: string) => {
|
||||
const slot = selectedSlot;
|
||||
const slotAttachments = pendingAttachments[slot];
|
||||
const message =
|
||||
messageOverride?.trim() ||
|
||||
draft.trim() ||
|
||||
(pendingAttachments.length > 0 ? "Please check the attachment." : "");
|
||||
if (!message || uploading || sending[selectedSlot]) return;
|
||||
draft[slot].trim() ||
|
||||
(slotAttachments.length > 0 ? "Please check the attachment." : "");
|
||||
if (!message || uploading || sending[slot]) return;
|
||||
const id = `local-${Date.now()}`;
|
||||
const attachments = messageOverride ? [] : pendingAttachments;
|
||||
setDraft("");
|
||||
if (!messageOverride) setPendingAttachments([]);
|
||||
setSending((current) => ({ ...current, [selectedSlot]: true }));
|
||||
const attachments = messageOverride ? [] : slotAttachments;
|
||||
setDraft((current) => ({ ...current, [slot]: "" }));
|
||||
if (!messageOverride) {
|
||||
setPendingAttachments((current) => ({ ...current, [slot]: [] }));
|
||||
}
|
||||
setSending((current) => ({ ...current, [slot]: true }));
|
||||
setMessages((current) =>
|
||||
current.concat({
|
||||
id,
|
||||
sessionId: status[selectedSlot].activeSessionId,
|
||||
slot: selectedSlot,
|
||||
sessionId: status[slot].activeSessionId,
|
||||
slot,
|
||||
role: "user",
|
||||
content: message,
|
||||
}),
|
||||
|
|
@ -406,13 +455,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const result = slotRuntimeSnapshotSchema.parse(
|
||||
await invoke<unknown>("send_connection_slot_message", {
|
||||
request: {
|
||||
slot: selectedSlot,
|
||||
slot,
|
||||
message,
|
||||
attachments,
|
||||
},
|
||||
}),
|
||||
);
|
||||
setStatus((current) => ({ ...current, [selectedSlot]: result }));
|
||||
setStatus((current) => ({ ...current, [slot]: result }));
|
||||
setMessages((current) =>
|
||||
current.map((item) =>
|
||||
item.id === id
|
||||
|
|
@ -420,28 +469,29 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
: item,
|
||||
),
|
||||
);
|
||||
setError(null);
|
||||
reportSlotError(slot, null);
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason));
|
||||
reportSlotError(slot, errorMessage(reason));
|
||||
setMessages((current) =>
|
||||
current.map((item) =>
|
||||
item.id === id ? { ...item, error: true } : item,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
setSending((current) => ({ ...current, [selectedSlot]: false }));
|
||||
setSending((current) => ({ ...current, [slot]: false }));
|
||||
}
|
||||
};
|
||||
|
||||
const stopGeneration = async () => {
|
||||
const slot = selectedSlot;
|
||||
try {
|
||||
await invoke("cancel_connection_slot_message", {
|
||||
request: { slot: selectedSlot },
|
||||
request: { slot },
|
||||
});
|
||||
setSending((current) => ({ ...current, [selectedSlot]: false }));
|
||||
setSending((current) => ({ ...current, [slot]: false }));
|
||||
setMessages((current) =>
|
||||
current.map((item) =>
|
||||
item.slot === selectedSlot && item.streaming
|
||||
item.slot === slot && item.streaming
|
||||
? {
|
||||
...item,
|
||||
streaming: false,
|
||||
|
|
@ -451,18 +501,19 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
: item,
|
||||
),
|
||||
);
|
||||
setError(null);
|
||||
reportSlotError(slot, null);
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason));
|
||||
reportSlotError(slot, errorMessage(reason));
|
||||
}
|
||||
};
|
||||
|
||||
const copyMessage = async (content: string) => {
|
||||
const slot = selectedSlot;
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
setError(null);
|
||||
reportSlotError(slot, null);
|
||||
} catch {
|
||||
setError("复制失败,请检查剪贴板权限。");
|
||||
reportSlotError(slot, "复制失败,请检查剪贴板权限。");
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -476,31 +527,29 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
};
|
||||
|
||||
const startNewSession = async () => {
|
||||
if (
|
||||
!status[selectedSlot].state ||
|
||||
status[selectedSlot].state === "disconnected"
|
||||
) {
|
||||
setError("Connect the selected slot first.");
|
||||
const slot = selectedSlot;
|
||||
if (!status[slot].state || status[slot].state === "disconnected") {
|
||||
reportSlotError(slot, "Connect the selected slot first.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const sessionId = crypto.randomUUID();
|
||||
const result = slotRuntimeSnapshotSchema.parse(
|
||||
await invoke<unknown>("switch_connection_slot_session", {
|
||||
request: { slot: selectedSlot, sessionId },
|
||||
request: { slot, sessionId },
|
||||
}),
|
||||
);
|
||||
setMessages((current) =>
|
||||
current.filter(
|
||||
(item) =>
|
||||
item.slot !== selectedSlot ||
|
||||
item.sessionId !== status[selectedSlot].activeSessionId,
|
||||
item.slot !== slot ||
|
||||
item.sessionId !== status[slot].activeSessionId,
|
||||
),
|
||||
);
|
||||
setStatus((current) => ({ ...current, [selectedSlot]: result }));
|
||||
setError(null);
|
||||
setStatus((current) => ({ ...current, [slot]: result }));
|
||||
reportSlotError(slot, null);
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason));
|
||||
reportSlotError(slot, errorMessage(reason));
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -509,36 +558,39 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
};
|
||||
|
||||
const reconnectConnection = async () => {
|
||||
const profileId = status[selectedSlot].profileId;
|
||||
const slot = selectedSlot;
|
||||
const profileId = status[slot].profileId;
|
||||
if (!profileId) {
|
||||
setError("No Profile is assigned to the selected slot.");
|
||||
reportSlotError(slot, "No Profile is assigned to the selected slot.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = slotRuntimeSnapshotSchema.parse(
|
||||
await invoke<unknown>("probe_connection_slot", {
|
||||
request: { slot: selectedSlot, profileId },
|
||||
request: { slot, profileId },
|
||||
}),
|
||||
);
|
||||
setStatus((current) => ({ ...current, [selectedSlot]: result }));
|
||||
setError(null);
|
||||
setStatus((current) => ({ ...current, [slot]: result }));
|
||||
reportSlotError(slot, null);
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason));
|
||||
reportSlotError(slot, errorMessage(reason));
|
||||
}
|
||||
};
|
||||
|
||||
const disconnectConnection = async () => {
|
||||
const slot = selectedSlot;
|
||||
try {
|
||||
await invoke("disconnect_connection_slot", {
|
||||
request: { slot: selectedSlot },
|
||||
request: { slot },
|
||||
});
|
||||
await refresh();
|
||||
} catch (reason) {
|
||||
setError(errorMessage(reason));
|
||||
reportSlotError(slot, errorMessage(reason));
|
||||
}
|
||||
};
|
||||
|
||||
const toggleVoiceInput = () => {
|
||||
const slot = selectedSlot;
|
||||
if (voiceListening) {
|
||||
speechRecognition.current?.stop();
|
||||
setVoiceListening(false);
|
||||
|
|
@ -551,7 +603,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const Recognition =
|
||||
browserWindow.SpeechRecognition ?? browserWindow.webkitSpeechRecognition;
|
||||
if (!Recognition) {
|
||||
setError("当前 WebView 不支持语音输入。");
|
||||
reportSlotError(slot, "当前 WebView 不支持语音输入。");
|
||||
return;
|
||||
}
|
||||
const recognition = new Recognition();
|
||||
|
|
@ -561,14 +613,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
const result = event as {
|
||||
results?: ArrayLike<ArrayLike<{ transcript?: string }>>;
|
||||
};
|
||||
setDraft(
|
||||
Array.from(result.results ?? [])
|
||||
.map((item) => item[0]?.transcript ?? "")
|
||||
.join(""),
|
||||
);
|
||||
const transcript = Array.from(result.results ?? [])
|
||||
.map((item) => item[0]?.transcript ?? "")
|
||||
.join("");
|
||||
setDraft((current) => ({ ...current, [slot]: transcript }));
|
||||
};
|
||||
recognition.onerror = () => {
|
||||
setError("语音输入失败,请检查麦克风权限。");
|
||||
reportSlotError(slot, "语音输入失败,请检查麦克风权限。");
|
||||
setVoiceListening(false);
|
||||
};
|
||||
recognition.onend = () => setVoiceListening(false);
|
||||
|
|
@ -697,9 +748,7 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
})
|
||||
.then(() => void refresh())
|
||||
.catch((reason) =>
|
||||
setError(
|
||||
errorMessage(reason),
|
||||
),
|
||||
reportSlotError(selectedSlot, errorMessage(reason)),
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
|
@ -748,7 +797,10 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
{message.streaming ? <small>生成中</small> : null}
|
||||
</div>
|
||||
{message.content ? (
|
||||
<MessageContent content={message.content} slot={selectedSlot} />
|
||||
<MessageContent
|
||||
content={message.content}
|
||||
slot={selectedSlot}
|
||||
/>
|
||||
) : (
|
||||
<p className="message-placeholder">正在生成…</p>
|
||||
)}
|
||||
|
|
@ -810,9 +862,9 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
})
|
||||
)}
|
||||
</div>
|
||||
{error ? (
|
||||
{visibleError ? (
|
||||
<p className="chat-error" role="alert">
|
||||
{error}
|
||||
{visibleError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="chat-composer-toolbar">
|
||||
|
|
@ -840,20 +892,21 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
{voiceListening ? "停止录音" : "语音输入"}
|
||||
</button>
|
||||
</div>
|
||||
{pendingAttachments.length > 0 ? (
|
||||
{selectedAttachments.length > 0 ? (
|
||||
<div className="attachment-list">
|
||||
{pendingAttachments.map((attachment) => (
|
||||
{selectedAttachments.map((attachment) => (
|
||||
<span key={attachment.attachmentId}>
|
||||
{attachment.fileName}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`移除 ${attachment.fileName}`}
|
||||
onClick={() =>
|
||||
setPendingAttachments((current) =>
|
||||
current.filter(
|
||||
setPendingAttachments((current) => ({
|
||||
...current,
|
||||
[selectedSlot]: current[selectedSlot].filter(
|
||||
(item) => item.attachmentId !== attachment.attachmentId,
|
||||
),
|
||||
)
|
||||
}))
|
||||
}
|
||||
>
|
||||
×
|
||||
|
|
@ -871,13 +924,18 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
>
|
||||
<textarea
|
||||
aria-label="聊天消息"
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onChange={(event) =>
|
||||
setDraft((current) => ({
|
||||
...current,
|
||||
[selectedSlot]: event.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder={
|
||||
selectedSlot === "companion"
|
||||
? "和陪伴实例说点什么…(Enter 发送,Shift+Enter 换行)"
|
||||
: "向运维实例描述问题…(Enter 发送,Shift+Enter 换行)"
|
||||
}
|
||||
value={draft}
|
||||
value={draft[selectedSlot]}
|
||||
rows={3}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
|
|
@ -893,7 +951,8 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
|
|||
<button
|
||||
className="chat-send-button"
|
||||
disabled={
|
||||
(!draft.trim() && pendingAttachments.length === 0) || uploading
|
||||
(!draft[selectedSlot].trim() && selectedAttachments.length === 0) ||
|
||||
uploading
|
||||
}
|
||||
type="submit"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -44,13 +44,20 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
|
|||
const completionTimerRef = useRef<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let unlisten: (() => void) | undefined;
|
||||
let unlistenRuntime: (() => void) | undefined;
|
||||
void listen("pet-game-mode-toggle", () =>
|
||||
setGameMode((current) => !current),
|
||||
).then((cleanup) => {
|
||||
unlisten = cleanup;
|
||||
});
|
||||
)
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
unlisten = cleanup;
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
void listen<unknown>("connection-runtime-event", (event) => {
|
||||
const parsed = boundRuntimeEventSchema.safeParse(event.payload);
|
||||
if (!parsed.success || parsed.data.slot !== PET_TARGET_SLOT) return;
|
||||
|
|
@ -68,12 +75,21 @@ export function DesktopPetView({ embedded = false }: { embedded?: boolean }) {
|
|||
}, 2200);
|
||||
}
|
||||
if (parsed.data.eventType === "error") setState("error");
|
||||
}).then((cleanup) => {
|
||||
unlistenRuntime = cleanup;
|
||||
});
|
||||
})
|
||||
.then((cleanup) => {
|
||||
if (active) {
|
||||
unlistenRuntime = cleanup;
|
||||
} else {
|
||||
cleanup();
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
active = false;
|
||||
unlisten?.();
|
||||
unlistenRuntime?.();
|
||||
unlisten = undefined;
|
||||
unlistenRuntime = undefined;
|
||||
if (completionTimerRef.current !== null) {
|
||||
window.clearTimeout(completionTimerRef.current);
|
||||
completionTimerRef.current = null;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,19 @@
|
|||
import "@testing-library/jest-dom/vitest";
|
||||
import { vi } from "vitest";
|
||||
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
listen: vi.fn(async () => () => undefined),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/event", async () => {
|
||||
const { listenMock } = await import("./tauriEvent");
|
||||
return { listen: listenMock };
|
||||
});
|
||||
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach } from "vitest";
|
||||
|
||||
import { resetTauriEvent } from "./tauriEvent";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
// The registry is plain module state, so `clearMocks` does not reach it.
|
||||
// Without this, listeners leak across test files.
|
||||
resetTauriEvent();
|
||||
});
|
||||
|
|
|
|||
79
src/test/tauriEvent.ts
普通文件
79
src/test/tauriEvent.ts
普通文件
|
|
@ -0,0 +1,79 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
type EventHandler = (event: { payload: unknown }) => void;
|
||||
|
||||
interface Registration {
|
||||
name: string;
|
||||
handler: EventHandler;
|
||||
unlisten: () => void;
|
||||
settle: (unlisten: () => void) => void;
|
||||
settled: boolean;
|
||||
released: boolean;
|
||||
}
|
||||
|
||||
const registrations: Registration[] = [];
|
||||
|
||||
/**
|
||||
* A deliberately deferred stand-in for `listen()`.
|
||||
*
|
||||
* The real one resolves asynchronously, and that gap is what makes the
|
||||
* unregister race possible: a cleanup that runs before the promise settles has
|
||||
* nothing to call. A mock that resolves eagerly would hide the exact defect
|
||||
* these tests exist to catch, so this one only settles when `flushListen` says
|
||||
* so.
|
||||
*/
|
||||
export const listenMock = vi.fn(
|
||||
(name: string, handler: EventHandler) =>
|
||||
new Promise<() => void>((resolve) => {
|
||||
const registration: Registration = {
|
||||
name,
|
||||
handler,
|
||||
unlisten: () => {
|
||||
registration.released = true;
|
||||
},
|
||||
settle: resolve,
|
||||
settled: false,
|
||||
released: false,
|
||||
};
|
||||
registrations.push(registration);
|
||||
}),
|
||||
);
|
||||
|
||||
/** Settles every pending `listen()` promise. */
|
||||
export async function flushListen(): Promise<void> {
|
||||
for (const registration of registrations) {
|
||||
if (registration.settled) continue;
|
||||
registration.settled = true;
|
||||
registration.settle(registration.unlisten);
|
||||
}
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches to every handler that has not been unregistered.
|
||||
*
|
||||
* A handler is live from the moment `listen()` is called, exactly as it is in
|
||||
* Tauri — the promise only hands back the unregister function. A leaked
|
||||
* registration therefore keeps receiving events, which is what turns the race
|
||||
* into doubled streaming deltas.
|
||||
*/
|
||||
export function emitTauriEvent(name: string, payload: unknown): void {
|
||||
for (const registration of [...registrations]) {
|
||||
if (registration.name !== name || registration.released) continue;
|
||||
registration.handler({ payload });
|
||||
}
|
||||
}
|
||||
|
||||
export function activeListeners(name?: string): number {
|
||||
return registrations.filter(
|
||||
(registration) =>
|
||||
!registration.released &&
|
||||
(name === undefined || registration.name === name),
|
||||
).length;
|
||||
}
|
||||
|
||||
export function resetTauriEvent(): void {
|
||||
registrations.length = 0;
|
||||
listenMock.mockClear();
|
||||
}
|
||||
正在加载…
添加表格
在新工单中引用