Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3467042000 | |||
| 80b15b24ae | |||
| b432556ee3 | |||
| 258645f182 | |||
| 5cf4a018b3 | |||
| 5d9223c32e | |||
| d32c99c927 | |||
| d36f5842b6 | |||
| 981a6b0021 |
@@ -2641,6 +2641,48 @@ const databaseTableLabelMap: Record<string, string> = {
|
||||
profile_recharge_order: '充值订单',
|
||||
profile_feedback_submission: '反馈提交',
|
||||
profile_save_archive: '存档记录',
|
||||
story_session: '剧情会话',
|
||||
story_event: '剧情事件',
|
||||
npc_state: 'NPC 状态',
|
||||
inventory_slot: '背包槽位',
|
||||
battle_state: '战斗状态',
|
||||
treasure_record: '宝藏记录',
|
||||
quest_record: '任务记录',
|
||||
quest_log: '任务日志',
|
||||
player_progression: '玩家进度',
|
||||
chapter_progression: '章节进度',
|
||||
custom_world_profile: '自定义世界档案',
|
||||
custom_world_session: '自定义世界会话',
|
||||
custom_world_agent_session: '自定义世界 Agent 会话',
|
||||
custom_world_agent_message: '自定义世界 Agent 消息',
|
||||
custom_world_agent_operation: '自定义世界 Agent 操作',
|
||||
custom_world_draft_card: '自定义世界草稿卡片',
|
||||
custom_world_gallery_entry: '自定义世界画廊条目',
|
||||
puzzle_agent_session: '拼图 Agent 会话',
|
||||
puzzle_agent_message: '拼图 Agent 消息',
|
||||
puzzle_work_profile: '拼图作品档案',
|
||||
puzzle_event: '拼图事件',
|
||||
puzzle_runtime_run: '拼图运行记录',
|
||||
puzzle_leaderboard_entry: '拼图排行榜条目',
|
||||
match3d_agent_session: '抓大鹅 Agent 会话',
|
||||
match3d_agent_message: '抓大鹅 Agent 消息',
|
||||
match3d_work_profile: '抓大鹅作品档案',
|
||||
match3d_runtime_run: '抓大鹅运行记录',
|
||||
square_hole_agent_session: '方洞挑战 Agent 会话',
|
||||
square_hole_agent_message: '方洞挑战 Agent 消息',
|
||||
square_hole_work_profile: '方洞挑战作品档案',
|
||||
square_hole_runtime_run: '方洞挑战运行记录',
|
||||
visual_novel_agent_session: '视觉小说 Agent 会话',
|
||||
visual_novel_agent_message: '视觉小说 Agent 消息',
|
||||
visual_novel_work_profile: '视觉小说作品档案',
|
||||
visual_novel_runtime_run: '视觉小说运行记录',
|
||||
visual_novel_runtime_history_entry: '视觉小说历史条目',
|
||||
visual_novel_runtime_event: '视觉小说运行事件',
|
||||
big_fish_creation_session: '大鱼吃小鱼创建会话',
|
||||
big_fish_agent_message: '大鱼吃小鱼 Agent 消息',
|
||||
big_fish_asset_slot: '大鱼吃小鱼资产槽位',
|
||||
big_fish_event: '大鱼吃小鱼事件',
|
||||
big_fish_runtime_run: '大鱼吃小鱼运行记录',
|
||||
asset_object: '资产对象',
|
||||
asset_entity_binding: '资产实体绑定',
|
||||
asset_event: '资产事件',
|
||||
@@ -2682,6 +2724,48 @@ const databaseTableDescriptionMap: Record<string, string> = {
|
||||
profile_recharge_order: '充值订单表',
|
||||
profile_feedback_submission: '反馈提交记录表',
|
||||
profile_save_archive: '用户存档记录表',
|
||||
story_session: '剧情会话表',
|
||||
story_event: '剧情事件表',
|
||||
npc_state: 'NPC 状态表',
|
||||
inventory_slot: '背包槽位表',
|
||||
battle_state: '战斗状态表',
|
||||
treasure_record: '宝藏记录表',
|
||||
quest_record: '任务记录表',
|
||||
quest_log: '任务日志表',
|
||||
player_progression: '玩家进度表',
|
||||
chapter_progression: '章节进度表',
|
||||
custom_world_profile: '自定义世界档案表',
|
||||
custom_world_session: '自定义世界会话表',
|
||||
custom_world_agent_session: '自定义世界 Agent 会话表',
|
||||
custom_world_agent_message: '自定义世界 Agent 消息表',
|
||||
custom_world_agent_operation: '自定义世界 Agent 操作表',
|
||||
custom_world_draft_card: '自定义世界草稿卡片表',
|
||||
custom_world_gallery_entry: '自定义世界画廊条目表',
|
||||
puzzle_agent_session: '拼图 Agent 会话表',
|
||||
puzzle_agent_message: '拼图 Agent 消息表',
|
||||
puzzle_work_profile: '拼图作品档案表',
|
||||
puzzle_event: '拼图事件表',
|
||||
puzzle_runtime_run: '拼图运行记录表',
|
||||
puzzle_leaderboard_entry: '拼图排行榜条目表',
|
||||
match3d_agent_session: '抓大鹅 Agent 会话表',
|
||||
match3d_agent_message: '抓大鹅 Agent 消息表',
|
||||
match3d_work_profile: '抓大鹅作品档案表',
|
||||
match3d_runtime_run: '抓大鹅运行记录表',
|
||||
square_hole_agent_session: '方洞挑战 Agent 会话表',
|
||||
square_hole_agent_message: '方洞挑战 Agent 消息表',
|
||||
square_hole_work_profile: '方洞挑战作品档案表',
|
||||
square_hole_runtime_run: '方洞挑战运行记录表',
|
||||
visual_novel_agent_session: '视觉小说 Agent 会话表',
|
||||
visual_novel_agent_message: '视觉小说 Agent 消息表',
|
||||
visual_novel_work_profile: '视觉小说作品档案表',
|
||||
visual_novel_runtime_run: '视觉小说运行记录表',
|
||||
visual_novel_runtime_history_entry: '视觉小说历史条目表',
|
||||
visual_novel_runtime_event: '视觉小说运行事件表',
|
||||
big_fish_creation_session: '大鱼吃小鱼创建会话表',
|
||||
big_fish_agent_message: '大鱼吃小鱼 Agent 消息表',
|
||||
big_fish_asset_slot: '大鱼吃小鱼资产槽位表',
|
||||
big_fish_event: '大鱼吃小鱼事件表',
|
||||
big_fish_runtime_run: '大鱼吃小鱼运行记录表',
|
||||
asset_object: '资产对象表',
|
||||
asset_entity_binding: '资产实体绑定表',
|
||||
asset_event: '资产事件表',
|
||||
|
||||
@@ -175,107 +175,6 @@ test('灰度发布页可选择模板库并默认启用零比例灰度', async ()
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度发布页可选择游戏发布开关,默认保持「未开启即开放」语义', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
|
||||
await screen.findByRole('button', { name: 'editor.new-toolbar' });
|
||||
await user.selectOptions(screen.getByLabelText('Gate Key 前缀'), [
|
||||
'game-distribution',
|
||||
]);
|
||||
|
||||
expect((screen.getByLabelText('Gate Key') as HTMLInputElement).value).toBe(
|
||||
'game-distribution:publish',
|
||||
);
|
||||
expect(
|
||||
(screen.getByLabelText('Gate Key 目标') as HTMLSelectElement).value,
|
||||
).toBe('publish');
|
||||
// 该开关的语义是「未配置/关闭 = 默认开放」,所以选中后不能默认打开收紧。
|
||||
expect((screen.getByLabelText('启用') as HTMLInputElement).checked).toBe(
|
||||
false,
|
||||
);
|
||||
expect((screen.getByLabelText('灰度比例') as HTMLInputElement).value).toBe(
|
||||
'0',
|
||||
);
|
||||
expect(
|
||||
(screen.getByLabelText('描述') as HTMLTextAreaElement).value,
|
||||
).toContain('游戏发布入口灰度');
|
||||
});
|
||||
|
||||
test('灰度发布页保存游戏发布开关时写入白名单与比例', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(upsertAdminFeatureGateConfig).mockResolvedValueOnce({
|
||||
gates: [
|
||||
...configResponse.gates,
|
||||
{
|
||||
gateKey: 'game-distribution:publish',
|
||||
enabled: true,
|
||||
rolloutPercent: 20,
|
||||
allowUserIds: ['user-internal'],
|
||||
allowUserTags: [],
|
||||
denyUserIds: [],
|
||||
description: '游戏发布入口灰度',
|
||||
updatedAt: '2026-09-22T10:00:00Z',
|
||||
},
|
||||
],
|
||||
});
|
||||
render(
|
||||
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
|
||||
await screen.findByRole('button', { name: 'editor.new-toolbar' });
|
||||
await user.selectOptions(screen.getByLabelText('Gate Key 前缀'), [
|
||||
'game-distribution',
|
||||
]);
|
||||
fireEvent.click(screen.getByLabelText('启用'));
|
||||
fireEvent.change(screen.getByLabelText('灰度比例'), {
|
||||
target: { value: '20' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('允许用户 ID'), {
|
||||
target: { value: 'user-internal' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('描述'), {
|
||||
target: { value: '游戏发布入口灰度' },
|
||||
});
|
||||
await user.click(screen.getByRole('button', { name: '保存配置' }));
|
||||
await user.click(screen.getByRole('button', { name: '确认' }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(upsertAdminFeatureGateConfig).toHaveBeenCalledWith('admin-token', {
|
||||
gateKey: 'game-distribution:publish',
|
||||
enabled: true,
|
||||
rolloutPercent: 20,
|
||||
allowUserIds: ['user-internal'],
|
||||
allowUserTags: [],
|
||||
denyUserIds: [],
|
||||
description: '游戏发布入口灰度',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('未创建的预设开关在后台可见并可一键配置', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<AdminGrayReleaseConfigPage token="admin-token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
|
||||
const row = await screen.findByText('game-distribution:publish');
|
||||
expect(row).not.toBeNull();
|
||||
// 该开关默认未创建:列表里给出「配置」入口,点击后按默认关闭填充表单。
|
||||
const configureButton = row.closest('tr')?.querySelector('button');
|
||||
expect(configureButton).not.toBeNull();
|
||||
await user.click(configureButton!);
|
||||
|
||||
expect((screen.getByLabelText('Gate Key') as HTMLInputElement).value).toBe(
|
||||
'game-distribution:publish',
|
||||
);
|
||||
expect((screen.getByLabelText('启用') as HTMLInputElement).checked).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度发布页保存时转换数组和百分比', async () => {
|
||||
const user = userEvent.setup();
|
||||
vi.mocked(upsertAdminFeatureGateConfig).mockResolvedValueOnce({
|
||||
|
||||
@@ -28,7 +28,6 @@ interface GateTargetOption {
|
||||
const GATE_PREFIX_LABELS: Record<string, string> = {
|
||||
'image-editor': '画布',
|
||||
agc: '客户端',
|
||||
'game-distribution': '游戏分发',
|
||||
};
|
||||
|
||||
const FIXED_GATE_TARGETS: GateTargetOption[] = [
|
||||
@@ -46,14 +45,6 @@ const FIXED_GATE_TARGETS: GateTargetOption[] = [
|
||||
label: 'Agent 侧边栏',
|
||||
description: '画布 Agent 入口灰度',
|
||||
},
|
||||
{
|
||||
prefix: 'game-distribution',
|
||||
suffix: 'publish',
|
||||
key: 'game-distribution:publish',
|
||||
label: '游戏发布',
|
||||
description:
|
||||
'游戏发布入口灰度:未配置或关闭时对已登录作者默认开放,开启后只放行白名单 / 灰度命中',
|
||||
},
|
||||
];
|
||||
|
||||
export function AdminGrayReleaseConfigPage({
|
||||
@@ -206,11 +197,6 @@ export function AdminGrayReleaseConfigPage({
|
||||
setErrorMessage('');
|
||||
}
|
||||
|
||||
// 预设里尚未创建行的开关也要可见:运营需要先看到 key 才能配置灰度。
|
||||
const unconfiguredGateTargets = FIXED_GATE_TARGETS.filter(
|
||||
(option) => !gates.some((gate) => gate.gateKey === option.key),
|
||||
);
|
||||
|
||||
function buildPayload(): AdminUpsertFeatureGateConfigRequest {
|
||||
return {
|
||||
gateKey: gateKey.trim(),
|
||||
@@ -457,53 +443,6 @@ export function AdminGrayReleaseConfigPage({
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="admin-panel">
|
||||
<div className="admin-panel-heading">
|
||||
<h3>可配置开关</h3>
|
||||
<span>{unconfiguredGateTargets.length}</span>
|
||||
</div>
|
||||
{unconfiguredGateTargets.length ? (
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table admin-table-compact">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Gate</th>
|
||||
<th>说明</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{unconfiguredGateTargets.map((option) => (
|
||||
<tr key={option.key}>
|
||||
<td>
|
||||
{option.key}
|
||||
<small>
|
||||
{GATE_PREFIX_LABELS[option.prefix] ?? option.prefix} ·{' '}
|
||||
{option.label}
|
||||
</small>
|
||||
</td>
|
||||
<td>{option.description}</td>
|
||||
<td>
|
||||
<button
|
||||
className="admin-text-button"
|
||||
type="button"
|
||||
onClick={() => applyGateTarget(option)}
|
||||
>
|
||||
配置
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="admin-empty-state">
|
||||
{isLoading ? '加载中' : '预设开关都已创建'}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{confirmDialog}
|
||||
|
||||
@@ -34,6 +34,7 @@ mod direct_thread_wire;
|
||||
mod direct_tool_bridge;
|
||||
mod direct_tool_calls;
|
||||
mod direct_tools_mcp;
|
||||
mod direct_turn_failure;
|
||||
mod direct_turn_metrics;
|
||||
mod direct_turn_stream;
|
||||
mod direct_validation;
|
||||
@@ -72,6 +73,7 @@ pub(crate) use direct_thread_wire::*;
|
||||
pub(crate) use direct_tool_bridge::*;
|
||||
pub(crate) use direct_tool_calls::*;
|
||||
pub(crate) use direct_tools_mcp::*;
|
||||
pub(crate) use direct_turn_failure::*;
|
||||
pub(crate) use direct_turn_metrics::*;
|
||||
pub(crate) use direct_turn_stream::*;
|
||||
pub(crate) use direct_validation::DirectValidationConfig;
|
||||
|
||||
@@ -3548,12 +3548,20 @@ impl CodexAppServerConnection {
|
||||
let direct_turn_user_item_id = direct_persisted_user_item
|
||||
.as_ref()
|
||||
.and_then(direct_thread_item_identity);
|
||||
// 回合终态兜底:`turn.started` 进队列之后就武装,写完终态即解除。宿主在这两者之间任何
|
||||
// 提前收场(panic、future 被丢弃、以后新增的早退)都由它补一条失败终态,否则前端只能
|
||||
// 永远停在"还在跑"。
|
||||
let mut direct_turn_failure_guard: Option<DirectTurnFailureGuard> = None;
|
||||
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::turn_started(direct_turn_started_at_ms)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
);
|
||||
direct_turn_failure_guard = Some(DirectTurnFailureGuard::arm(
|
||||
direct_thread_id.clone(),
|
||||
direct_turn_user_item_id.clone(),
|
||||
));
|
||||
if let Some(user_item) = direct_persisted_user_item.as_ref() {
|
||||
if let Some(entry_item) = direct_thread_event_item(history_root, user_item) {
|
||||
// 这里的条目时间可能是启动应答后的观测时间;前端按同一用户条目身份
|
||||
@@ -4061,11 +4069,30 @@ impl CodexAppServerConnection {
|
||||
.map(|(_, at)| *at)
|
||||
.unwrap_or_else(direct_tool_call_now_ms)
|
||||
};
|
||||
append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::turn_completed(status, completed_at)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
// 终态只有 `turn.completed` 一种事件:失败时同一个事件带 `failure` 载荷(原因由宿主
|
||||
// 脱敏 + 截断后写进去),其余(`completed` / `interrupted` / `aborted`)不带载荷。
|
||||
// 失败不再只写一个 `status="failed"`:那让失败与正常结束在协议上长得一样,前端只能
|
||||
// 另开一条通道(命令返回 / 另一条 IPC)去拿原因,也就等于承认事件流讲不清一轮怎么结束。
|
||||
let failure = direct_turn_failure(
|
||||
&status,
|
||||
collect_result.as_ref().map(String::as_str),
|
||||
history_root,
|
||||
);
|
||||
match failure {
|
||||
Some(failure) => append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::turn_completed_failed(failure, completed_at)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
),
|
||||
None => append_direct_thread_event(
|
||||
&direct_thread_id,
|
||||
DirectThreadEvent::turn_completed(status, completed_at)
|
||||
.with_user_item_id(direct_turn_user_item_id.as_deref()),
|
||||
),
|
||||
};
|
||||
if let Some(guard) = direct_turn_failure_guard.as_mut() {
|
||||
guard.disarm();
|
||||
}
|
||||
}
|
||||
let text = collect_result?;
|
||||
guard.armed = false;
|
||||
|
||||
@@ -603,6 +603,30 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
/// 失败终态与正常终态同权:`turn.completed(status="failed")` 必须顶替更早的 `turn.started`
|
||||
/// 成为锚点,否则队列被回收后新订阅只会看到 `turn.started`,把这轮已收口的回合重放成"还在跑"。
|
||||
#[test]
|
||||
fn failed_turn_completed_replaces_started_anchor() {
|
||||
let mut manager = DirectThreadManager::with_limits(100, 100_000);
|
||||
manager.append("thread-1", DirectThreadEvent::turn_started(1_000));
|
||||
manager.append(
|
||||
"thread-1",
|
||||
DirectThreadEvent::turn_completed_failed(
|
||||
crate::agent::DirectTurnFailure::new("host-dropped", "回合宿主任务提前结束"),
|
||||
FIXED_AT_MS,
|
||||
),
|
||||
);
|
||||
|
||||
let bootstrap = manager.subscribe("thread-1");
|
||||
assert!(matches!(
|
||||
bootstrap.events.as_slice(),
|
||||
[DirectThreadEvent::TurnCompleted { status, failure, at, .. }]
|
||||
if status == "failed"
|
||||
&& failure.as_ref().is_some_and(|failure| failure.kind == "host-dropped")
|
||||
&& *at == Some(FIXED_AT_MS)
|
||||
));
|
||||
}
|
||||
|
||||
/// 阶段时间必须随事件一起进队列:bootstrap 与重复订阅都拿到**原值**,
|
||||
/// 重放不得重新取钟(否则每次重连都会把已固定的起止时间改掉)。
|
||||
#[test]
|
||||
|
||||
@@ -211,6 +211,30 @@ impl DirectThreadRequestKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// 失败终态的可下发载荷(`turn.completed.status == "failed"` 时必有,其余终态没有)。
|
||||
///
|
||||
/// `kind` 是稳定分类,只给界面选语气,不参与流程分支;`message` 是**已在宿主侧脱敏并截断**的
|
||||
/// 可展示原因——失败原因只走这一条通道,前端不再从命令返回或另一条 IPC 里另造文案。
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
|
||||
pub(crate) struct DirectTurnFailure {
|
||||
/// 稳定失败分类:`timeout` / `model-failed` / `transport-failed` / `request-rejected` /
|
||||
/// `host-dropped`。
|
||||
pub(crate) kind: String,
|
||||
/// 脱敏 + 截断后的失败原因。
|
||||
pub(crate) message: String,
|
||||
}
|
||||
|
||||
impl DirectTurnFailure {
|
||||
pub(crate) fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind: kind.into(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Thread Manager 下发的运行态事件。
|
||||
///
|
||||
/// 顺序由数组顺序给出(同一个 subscriber 的 `consume` 按队列顺序返回),因此不需要 `seq`:
|
||||
@@ -250,7 +274,13 @@ pub(crate) enum DirectThreadEvent {
|
||||
},
|
||||
#[serde(rename = "turn.completed")]
|
||||
TurnCompleted {
|
||||
/// 终态语义:`completed` / `interrupted` / `aborted` 是正常收场;`failed` 是**失败**,
|
||||
/// 此时必须带 `failure` 载荷。
|
||||
status: String,
|
||||
/// 失败载荷:只有 `status == "failed"` 才有;失败原因只从这里下发一次。
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
failure: Option<DirectTurnFailure>,
|
||||
/// 本轮终态的阶段时间(毫秒):宿主处理终态的毫秒钟,或 `durationMs` + 高精度起点的派生值。
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional, as = "Option<f64>")]
|
||||
@@ -301,11 +331,30 @@ impl DirectThreadEvent {
|
||||
pub(crate) fn turn_completed(status: String, at: u64) -> Self {
|
||||
Self::TurnCompleted {
|
||||
status,
|
||||
failure: None,
|
||||
at: Some(at),
|
||||
user_item_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 失败终态:`status` 固定 `"failed"`,原因必须随事件一起带出去。
|
||||
pub(crate) fn turn_completed_failed(failure: DirectTurnFailure, at: u64) -> Self {
|
||||
Self::TurnCompleted {
|
||||
status: "failed".to_string(),
|
||||
failure: Some(failure),
|
||||
at: Some(at),
|
||||
user_item_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 失败载荷:只有失败终态有。
|
||||
pub(crate) fn failure(&self) -> Option<&DirectTurnFailure> {
|
||||
match self {
|
||||
Self::TurnCompleted { failure, .. } => failure.as_ref(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 附上本轮开口用户条目的 canonical itemId。
|
||||
///
|
||||
/// 只在构造之后补一次身份,避免 `turn.started` / `turn.completed` 的既有调用点(含各处兜底
|
||||
@@ -317,8 +366,14 @@ impl DirectThreadEvent {
|
||||
.map(str::to_string);
|
||||
match self {
|
||||
Self::TurnStarted { at, .. } => Self::TurnStarted { at, user_item_id },
|
||||
Self::TurnCompleted { status, at, .. } => Self::TurnCompleted {
|
||||
Self::TurnCompleted {
|
||||
status,
|
||||
failure,
|
||||
at,
|
||||
..
|
||||
} => Self::TurnCompleted {
|
||||
status,
|
||||
failure,
|
||||
at,
|
||||
user_item_id,
|
||||
},
|
||||
@@ -1351,4 +1406,56 @@ mod tests {
|
||||
);
|
||||
assert_eq!(item_event.user_item_id(), None);
|
||||
}
|
||||
|
||||
/// 失败终态:`status="failed"` 必须带 `failure{kind,message}`,正常终态不带;载荷跟着身份
|
||||
/// 一起流转,缺载荷的 `failed` 事件仍能反序列化(前端按"没有原因"处理,不猜)。
|
||||
#[test]
|
||||
fn turn_completed_carries_failure_payload_only_when_failed() {
|
||||
let failed = DirectThreadEvent::turn_completed_failed(
|
||||
DirectTurnFailure::new("model-failed", "上游返回 500:模型服务暂不可用"),
|
||||
4_000,
|
||||
)
|
||||
.with_user_item_id(Some("direct-codex:turn-1:user"));
|
||||
assert_eq!(
|
||||
failed.failure(),
|
||||
Some(&DirectTurnFailure::new(
|
||||
"model-failed",
|
||||
"上游返回 500:模型服务暂不可用"
|
||||
))
|
||||
);
|
||||
assert_eq!(failed.user_item_id(), Some("direct-codex:turn-1:user"));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&failed).expect("serialize failed turn"),
|
||||
json!({
|
||||
"type": "turn.completed",
|
||||
"status": "failed",
|
||||
"failure": {"kind": "model-failed", "message": "上游返回 500:模型服务暂不可用"},
|
||||
"at": 4_000u64,
|
||||
"userItemId": "direct-codex:turn-1:user",
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<DirectThreadEvent>(
|
||||
serde_json::to_value(&failed).expect("serialize")
|
||||
)
|
||||
.expect("round trip"),
|
||||
failed
|
||||
);
|
||||
|
||||
// 正常终态不带载荷,也不回写 `failure: null`。
|
||||
let completed = DirectThreadEvent::turn_completed("completed".to_string(), 5_000);
|
||||
assert_eq!(completed.failure(), None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&completed).expect("serialize completed turn"),
|
||||
json!({"type": "turn.completed", "status": "completed", "at": 5_000u64})
|
||||
);
|
||||
|
||||
// 精简 / 旧形状:`failed` 但没有载荷也要能反序列化。
|
||||
let sparse: DirectThreadEvent = serde_json::from_value(json!({
|
||||
"type": "turn.completed",
|
||||
"status": "failed",
|
||||
}))
|
||||
.expect("failed turn without failure payload");
|
||||
assert_eq!(sparse.failure(), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
//! 失败终态的宿主侧策略:把"这一轮为什么失败"翻译成可下发的 `failure` 载荷,并在宿主自己
|
||||
//! 提前收场时补一条失败终态。
|
||||
//!
|
||||
//! 这个模块只有三件事,别再往里加第四件:
|
||||
//! 1. [`direct_turn_failure_kind`]:把 `LlmError` 归到稳定分类(只给界面选语气);
|
||||
//! 2. [`direct_turn_failure`]:判定这一轮的终态是不是失败,是的话给出脱敏后的原因;
|
||||
//! 3. [`DirectTurnFailureGuard`]:`turn.started` 之后武装、写完终态解除的 Drop 兜底。
|
||||
//!
|
||||
//! 失败载荷的**形状**属于线上协议,定义在 `direct_thread_wire.rs`(`DirectTurnFailure`);
|
||||
//! 这里只负责"什么算失败、原因怎么写、什么时候兜底",不碰事件队列的搬运规则。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use platform_llm::LlmError;
|
||||
|
||||
use super::{
|
||||
append_direct_thread_event, direct_tool_call_now_ms, redact_agent_runtime_error,
|
||||
DirectThreadEvent, DirectTurnFailure,
|
||||
};
|
||||
|
||||
/// `turn.completed.failure.message` 的字符上限:与本地错误文案同一档——够说清原因,又不至于
|
||||
/// 把整段上游报文塞进事件队列。
|
||||
const DIRECT_TURN_FAILURE_MESSAGE_MAX_CHARS: usize = 600;
|
||||
|
||||
/// 宿主任务提前结束(panic / future 被丢弃 / 终态之前的早退)时的分类与文案。
|
||||
const DIRECT_TURN_FAILURE_HOST_DROPPED_KIND: &str = "host-dropped";
|
||||
const DIRECT_TURN_FAILURE_HOST_DROPPED_MESSAGE: &str =
|
||||
"陶泥儿回合的宿主任务提前结束(崩溃或任务被取消),本轮已按失败收口,请重试。";
|
||||
|
||||
/// 稳定失败分类:`timeout` / `model-failed` / `transport-failed` / `request-rejected`。
|
||||
///
|
||||
/// 分类只影响界面语气,前端不得拿它做流程分支(流程判据只有"收到终态事件"这一条)。
|
||||
fn direct_turn_failure_kind(error: &LlmError) -> &'static str {
|
||||
match error {
|
||||
LlmError::Timeout { .. } => "timeout",
|
||||
LlmError::InvalidConfig(_) | LlmError::InvalidRequest(_) => "request-rejected",
|
||||
LlmError::Connectivity { .. } | LlmError::Transport(_) | LlmError::StreamUnavailable => {
|
||||
"transport-failed"
|
||||
}
|
||||
LlmError::Upstream { .. } | LlmError::EmptyResponse | LlmError::Deserialize(_) => {
|
||||
"model-failed"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 这一轮的终态是不是「失败」?是的话给出失败载荷(原因已脱敏并截断)。
|
||||
///
|
||||
/// 失败有两个来源,都必须进 `turn.completed(status="failed")` 的 `failure` 载荷:
|
||||
/// - `collect_result` 是错误:真失败(模型 / 传输 / 历史落盘),原因直接从错误里取;
|
||||
/// - `collect_result` 是交付报告、但 `status` 已经判成 `failed`:宿主收束了一个失败的回合,
|
||||
/// 原因用那份报告本身(它本来就是给用户看的失败说明)。
|
||||
///
|
||||
/// 其余终态(`completed` / `interrupted` / `aborted`)都不是失败,返回 `None`,事件不带载荷。
|
||||
pub(crate) fn direct_turn_failure(
|
||||
status: &str,
|
||||
collect_result: Result<&str, &LlmError>,
|
||||
history_root: &Path,
|
||||
) -> Option<DirectTurnFailure> {
|
||||
let (kind, message) = match collect_result {
|
||||
Err(error) => (
|
||||
direct_turn_failure_kind(error).to_string(),
|
||||
error.to_string(),
|
||||
),
|
||||
Ok(report) if status == "failed" => ("model-failed".to_string(), report.to_string()),
|
||||
Ok(_) => return None,
|
||||
};
|
||||
Some(DirectTurnFailure::new(
|
||||
kind,
|
||||
redact_agent_runtime_error(
|
||||
history_root,
|
||||
&message,
|
||||
DIRECT_TURN_FAILURE_MESSAGE_MAX_CHARS,
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
/// 回合终态兜底守卫:`turn.started` 发出去之后,这一轮在宿主侧只剩两条收场路径——正常路径
|
||||
/// 写完终态事件(然后 [`Self::disarm`]),或者这个守卫的 `Drop`。
|
||||
///
|
||||
/// 兜底覆盖三种"走不到终态"的情况:panic 展开、future 被丢弃(任务 / 进程取消),以及今后在
|
||||
/// 终态事件之前新增的 `?` 早退。它们都再也没有机会补终态事件,前端只能永远停在"还在跑";
|
||||
/// 这里在 Drop 里补一条 `status="failed"` + `host-dropped` 的终态,让前端拿到收口依据。
|
||||
///
|
||||
/// 与 `CodexTurnGuard` / `CodexTurnStartGuard` 是**三件事**,不要合并:那两个守卫管的是
|
||||
/// app-server 连接与 `turn/start` 请求的回收,Drop 里不产出任何事件。
|
||||
///
|
||||
/// 已知边界(不为它加路径):宿主进程被强杀(`kill -9`)时没有任何 `Drop` 会执行,前端仍会停在
|
||||
/// 运行态;`turn.started` 之前的早退根本不武装这个守卫——没有开始就没有"未收口的回合"。
|
||||
pub(crate) struct DirectTurnFailureGuard {
|
||||
thread_id: String,
|
||||
user_item_id: Option<String>,
|
||||
armed: bool,
|
||||
}
|
||||
|
||||
impl DirectTurnFailureGuard {
|
||||
/// 武装:调用点必须是 `turn.started` **已经**进入队列之后。
|
||||
pub(crate) fn arm(thread_id: String, user_item_id: Option<String>) -> Self {
|
||||
Self {
|
||||
thread_id,
|
||||
user_item_id,
|
||||
armed: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// 解除:终态事件(正常或失败)已经写完,兜底不再需要。
|
||||
pub(crate) fn disarm(&mut self) {
|
||||
self.armed = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DirectTurnFailureGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.armed {
|
||||
return;
|
||||
}
|
||||
append_direct_thread_event(
|
||||
&self.thread_id,
|
||||
DirectThreadEvent::turn_completed_failed(
|
||||
DirectTurnFailure::new(
|
||||
DIRECT_TURN_FAILURE_HOST_DROPPED_KIND,
|
||||
DIRECT_TURN_FAILURE_HOST_DROPPED_MESSAGE,
|
||||
),
|
||||
direct_tool_call_now_ms(),
|
||||
)
|
||||
.with_user_item_id(self.user_item_id.as_deref()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agent::{consume_direct_thread, subscribe_direct_thread};
|
||||
|
||||
fn history_root() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from("/tmp/direct-turn-failure-test")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_error_variants_map_to_stable_kinds() {
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::Timeout { attempts: 3 }),
|
||||
"timeout"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::InvalidConfig("missing key".into())),
|
||||
"request-rejected"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::InvalidRequest("bad payload".into())),
|
||||
"request-rejected"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::Connectivity {
|
||||
attempts: 2,
|
||||
message: "reset".into(),
|
||||
}),
|
||||
"transport-failed"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::Transport("stream closed".into())),
|
||||
"transport-failed"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::StreamUnavailable),
|
||||
"transport-failed"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::Upstream {
|
||||
status_code: 500,
|
||||
message: "boom".into(),
|
||||
}),
|
||||
"model-failed"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::EmptyResponse),
|
||||
"model-failed"
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure_kind(&LlmError::Deserialize("bad json".into())),
|
||||
"model-failed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_failed_terminals_carry_a_failure_payload() {
|
||||
// 正常终态:无论交付报告写了什么都不是失败。
|
||||
assert_eq!(
|
||||
direct_turn_failure("completed", Ok("本轮交付已完成"), &history_root()),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure("interrupted", Ok("本轮已被终止"), &history_root()),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
direct_turn_failure("aborted", Ok("已结束这一轮占用"), &history_root()),
|
||||
None
|
||||
);
|
||||
|
||||
// 失败且拿得到错误:分类取自错误,原因取自错误文本。
|
||||
let error =
|
||||
LlmError::Transport("DirectProject 收尾历史失败:写入 project.jsonl 失败".into());
|
||||
let failure = direct_turn_failure("failed", Err(&error), &history_root())
|
||||
.expect("transport error must produce a failure payload");
|
||||
assert_eq!(failure.kind, "transport-failed");
|
||||
assert!(failure.message.contains("收尾历史失败"));
|
||||
|
||||
// 失败但拿到的是交付报告:宿主已经收束了这一轮,报告本身就是失败说明。
|
||||
let failure = direct_turn_failure(
|
||||
"failed",
|
||||
Ok("宿主尚未确认交付完成;请核对未完成项。"),
|
||||
&history_root(),
|
||||
)
|
||||
.expect("failed status must produce a failure payload");
|
||||
assert_eq!(failure.kind, "model-failed");
|
||||
assert_eq!(failure.message, "宿主尚未确认交付完成;请核对未完成项。");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_message_is_redacted_and_truncated() {
|
||||
let root = history_root();
|
||||
let with_path = format!("落盘失败:{} 不可写", root.display());
|
||||
let failure = direct_turn_failure("failed", Ok(&with_path), &history_root())
|
||||
.expect("failed status must produce a failure payload");
|
||||
assert!(!failure.message.contains("/tmp/direct-turn-failure-test"));
|
||||
assert!(failure.message.contains("$PROJECT_ROOT"));
|
||||
|
||||
let long = "x".repeat(4_000);
|
||||
let failure = direct_turn_failure("failed", Ok(&long), &history_root())
|
||||
.expect("failed status must produce a failure payload");
|
||||
// 按字符截断,最多再多一个省略号标记。
|
||||
assert!(failure.message.chars().count() <= DIRECT_TURN_FAILURE_MESSAGE_MAX_CHARS + 1);
|
||||
assert!(failure.message.ends_with('…'));
|
||||
}
|
||||
|
||||
/// 兜底:守卫武装后没被解除就 Drop,必须补一条失败终态(panic / future 被丢弃走的就是这条)。
|
||||
#[test]
|
||||
fn armed_guard_appends_host_dropped_terminal_on_drop() {
|
||||
let thread_id = "test-thread-failure-guard-armed";
|
||||
let subscription = subscribe_direct_thread(thread_id);
|
||||
let guard = DirectTurnFailureGuard::arm(
|
||||
thread_id.to_string(),
|
||||
Some("direct-codex:turn-1:user".to_string()),
|
||||
);
|
||||
drop(guard);
|
||||
|
||||
let events = consume_direct_thread(&subscription.subscription_id)
|
||||
.expect("consume guard terminal")
|
||||
.events;
|
||||
assert!(matches!(
|
||||
events.as_slice(),
|
||||
[DirectThreadEvent::TurnCompleted { status, failure, user_item_id, .. }]
|
||||
if status == "failed"
|
||||
&& failure.as_ref().is_some_and(|failure| failure.kind == "host-dropped")
|
||||
&& user_item_id.as_deref() == Some("direct-codex:turn-1:user")
|
||||
));
|
||||
}
|
||||
|
||||
/// 解除之后就闭嘴:正常写完终态的回合不得再多出一条兜底终态。
|
||||
#[test]
|
||||
fn disarmed_guard_appends_nothing() {
|
||||
let thread_id = "test-thread-failure-guard-disarmed";
|
||||
let subscription = subscribe_direct_thread(thread_id);
|
||||
let mut guard = DirectTurnFailureGuard::arm(thread_id.to_string(), None);
|
||||
guard.disarm();
|
||||
drop(guard);
|
||||
|
||||
assert!(consume_direct_thread(&subscription.subscription_id)
|
||||
.expect("consume disarmed guard")
|
||||
.events
|
||||
.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -5974,19 +5974,15 @@ pub(crate) fn create_local_project_checkpoint(
|
||||
create_local_project_checkpoint_at(root)
|
||||
}
|
||||
|
||||
/// 为发布导出试玩包:项目还没有可玩入口时先跑项目自己的 `npm run build`。
|
||||
///
|
||||
/// 作者只点一次「发布」:已有 `game/index.html` 或 `dist/index.html` 直接打包;只有源码时
|
||||
/// 走 `project.verify` 的受控 npm 运行器构建后再打包,失败信息带构建日志尾部。
|
||||
#[tauri::command]
|
||||
pub(crate) async fn export_local_project_package(
|
||||
pub(crate) fn export_local_project_package(
|
||||
project_path: String,
|
||||
) -> Result<LocalProjectExportPackageResult, String> {
|
||||
let root = Path::new(project_path.trim());
|
||||
enforce_project_permission_policy(root, "project.export_package")?;
|
||||
let _lock = acquire_project_write_lock(root, "project.export_package")?;
|
||||
advance_agent_runtime_project_revision_locked(root)?;
|
||||
export_local_project_package_for_publish_at(root).await
|
||||
export_local_project_package_at(root)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -136,159 +136,6 @@ pub(crate) fn export_local_project_package_at(
|
||||
///
|
||||
/// The caller receives the package bytes and a deterministic file manifest, but
|
||||
/// never receives a filesystem path that it could accidentally send to the API.
|
||||
/// 发布前构建的超时上限:与 `project.verify` 的上限保持一致(构建属于常规步骤,
|
||||
/// 给足时间但必须有界),避免发布路径越过校验器允许的区间。
|
||||
pub(crate) const PUBLISH_BUILD_TIMEOUT_SECONDS: u64 = 300;
|
||||
|
||||
/// 找到声明了 `scripts.build` 的 npm 工作目录(项目根或 `game/` 子工程)。
|
||||
///
|
||||
/// 只读 `package.json`,不执行任何东西;真正的执行交给 `project.verify` 的受控
|
||||
/// npm 运行器(脚本白名单含 `build`、禁止项目级 `.npmrc` 改写语义、沙箱与超时都在那里)。
|
||||
pub(crate) fn resolve_publish_build_cwd(root: &Path) -> Result<Option<&'static str>, String> {
|
||||
for cwd in [".", "game"] {
|
||||
let package_root = if cwd == "." {
|
||||
root.to_path_buf()
|
||||
} else {
|
||||
resolve_local_project_path(root, cwd)?
|
||||
};
|
||||
let package_path = package_root.join("package.json");
|
||||
let metadata = match fs::symlink_metadata(&package_path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if metadata.file_type().is_symlink() || !metadata.is_file() {
|
||||
continue;
|
||||
}
|
||||
let Ok(content) = fs::read_to_string(&package_path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(package) = serde_json::from_str::<serde_json::Value>(&content) else {
|
||||
continue;
|
||||
};
|
||||
let declared = package
|
||||
.get("scripts")
|
||||
.and_then(|scripts| scripts.get("build"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty());
|
||||
if declared.is_some() {
|
||||
return Ok(Some(cwd));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// 读取声明的 build 脚本原文:`project.verify` 用它做 expectedCommand 反漂移校验。
|
||||
pub(crate) fn read_publish_build_command(
|
||||
root: &Path,
|
||||
cwd_relative: &str,
|
||||
) -> Result<String, String> {
|
||||
let package_root = if cwd_relative == "." {
|
||||
root.to_path_buf()
|
||||
} else {
|
||||
resolve_local_project_path(root, cwd_relative)?
|
||||
};
|
||||
let package_path = package_root.join("package.json");
|
||||
let content = fs::read_to_string(&package_path).map_err(|error| {
|
||||
format!(
|
||||
"读取 package.json 失败:{}: {error}",
|
||||
package_path.display()
|
||||
)
|
||||
})?;
|
||||
let package: serde_json::Value = serde_json::from_str(&content)
|
||||
.map_err(|error| format!("解析 package.json 失败:{error}"))?;
|
||||
package
|
||||
.get("scripts")
|
||||
.and_then(|scripts| scripts.get("build"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| "package.json 未定义 build 脚本".to_string())
|
||||
}
|
||||
|
||||
/// 构建失败的日志尾部:命令输出有界,直接回传最后一段给作者判断。
|
||||
fn publish_build_failure_tail(output: &str) -> String {
|
||||
const MAX_CHARS: usize = 2_000;
|
||||
let trimmed = output.trim();
|
||||
let chars = trimmed.chars().count();
|
||||
if chars <= MAX_CHARS {
|
||||
return trimmed.to_string();
|
||||
}
|
||||
let tail = trimmed.chars().skip(chars - MAX_CHARS).collect::<String>();
|
||||
format!("…{tail}")
|
||||
}
|
||||
|
||||
/// 发布前构建计划:在哪个目录构建、构建脚本原文、以及是否需要先装依赖。
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct PublishBuildPlan {
|
||||
pub(crate) cwd_relative: &'static str,
|
||||
pub(crate) command: String,
|
||||
/// `game/` 子工程缺 `node_modules` 时为 true:构建前必须先跑 `project.bootstrap`。
|
||||
pub(crate) needs_dependency_install: bool,
|
||||
}
|
||||
|
||||
/// 解析发布前构建计划;项目没有任何可构建的 npm 工程时返回可操作错误。
|
||||
pub(crate) fn resolve_publish_build_plan(root: &Path) -> Result<PublishBuildPlan, String> {
|
||||
let Some(cwd_relative) = resolve_publish_build_cwd(root)? else {
|
||||
return Err(
|
||||
"项目还没有可玩入口,且项目根 / game 目录的 package.json 都没有 build 脚本:请让 Agent 生成可玩产物,或补上 build 脚本后重试"
|
||||
.to_string(),
|
||||
);
|
||||
};
|
||||
let command = read_publish_build_command(root, cwd_relative)?;
|
||||
let needs_dependency_install =
|
||||
cwd_relative == "game" && !root.join("game").join("node_modules").is_dir();
|
||||
Ok(PublishBuildPlan {
|
||||
cwd_relative,
|
||||
command,
|
||||
needs_dependency_install,
|
||||
})
|
||||
}
|
||||
|
||||
/// 为发布导出试玩包:项目还没有可玩入口时,先跑项目自己的 `npm run build`。
|
||||
///
|
||||
/// 作者只需要点一次「发布」:已有可玩产物(`game/index.html` 或 `dist/index.html`)直接打包;
|
||||
/// 只有源码时用 `project.verify` 的受控 npm 运行器执行 build,再校验入口并打包。构建失败
|
||||
/// 返回带日志尾部的可操作错误,不回传本地路径。
|
||||
pub(crate) async fn export_local_project_package_for_publish_at(
|
||||
root: &Path,
|
||||
) -> Result<LocalProjectExportPackageResult, String> {
|
||||
if validate_project_game_entry(root).is_ok() {
|
||||
return export_local_project_package_at(root);
|
||||
}
|
||||
let plan = resolve_publish_build_plan(root)?;
|
||||
// `game/` 子工程构建前必须先有依赖:缺 node_modules 时由发布流程自己补一次安装,
|
||||
// 否则作者要点两次(先 bootstrap 再发布)。
|
||||
if plan.needs_dependency_install {
|
||||
let bootstrap =
|
||||
crate::project::run_project_bootstrap_at(root, PUBLISH_BUILD_TIMEOUT_SECONDS).await?;
|
||||
if bootstrap.status != "completed" {
|
||||
return Err(format!(
|
||||
"安装 game 依赖失败(npm install 未通过):\n{}",
|
||||
publish_build_failure_tail(&bootstrap.output)
|
||||
));
|
||||
}
|
||||
}
|
||||
let built = crate::project::verification::run_project_verification_with_commit_at(
|
||||
root,
|
||||
"build",
|
||||
&plan.command,
|
||||
PUBLISH_BUILD_TIMEOUT_SECONDS,
|
||||
plan.cwd_relative,
|
||||
|| Ok(()),
|
||||
)
|
||||
.await?;
|
||||
if built.status != "completed" {
|
||||
return Err(format!(
|
||||
"构建可玩版本失败(npm run build 未通过):\n{}",
|
||||
publish_build_failure_tail(&built.output)
|
||||
));
|
||||
}
|
||||
validate_project_game_entry(root)
|
||||
.map_err(|error| format!("构建完成但项目仍没有可玩入口:{error}"))?;
|
||||
export_local_project_package_at(root)
|
||||
}
|
||||
|
||||
pub(crate) fn read_local_project_export_package_at(
|
||||
root: &Path,
|
||||
package_relative_path: &str,
|
||||
|
||||
@@ -3935,165 +3935,6 @@ fn local_project_export_package_uses_runtime_whitelist_and_records() {
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publish_build_plan_prefers_game_subproject_and_requires_dependencies() {
|
||||
let root = unique_project_path();
|
||||
init_local_game_project_at(&root, "project-plan-game", "Phaser 工程").expect("project init");
|
||||
|
||||
// 脚手架是 game/ + vite build(Phaser 4 工程):缺依赖时必须先 install。
|
||||
let plan = resolve_publish_build_plan(&root).expect("解析构建计划");
|
||||
assert_eq!(plan.cwd_relative, "game");
|
||||
assert_eq!(plan.command, "vite build");
|
||||
assert!(
|
||||
plan.needs_dependency_install,
|
||||
"缺少 game/node_modules 时应先装依赖"
|
||||
);
|
||||
|
||||
fs::create_dir_all(root.join("game/node_modules")).expect("create node_modules");
|
||||
let installed = resolve_publish_build_plan(&root).expect("解析构建计划");
|
||||
assert!(
|
||||
!installed.needs_dependency_install,
|
||||
"已有依赖时不应重复 install"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publish_build_plan_falls_back_to_root_npm_build() {
|
||||
let root = unique_project_path();
|
||||
init_local_game_project_at(&root, "project-plan-root", "根工程构建").expect("project init");
|
||||
// 去掉 game 子工程的 build,改用项目根 npm 工程构建。
|
||||
fs::write(
|
||||
root.join("game/package.json"),
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "plan-root-game",
|
||||
"private": true,
|
||||
"scripts": { "check": "node -e \"process.exit(0)\"" }
|
||||
}))
|
||||
.expect("serialize game package json"),
|
||||
)
|
||||
.expect("write game package json");
|
||||
fs::write(
|
||||
root.join("package.json"),
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "plan-root-fixture",
|
||||
"private": true,
|
||||
"scripts": { "build": "node build-root.mjs" }
|
||||
}))
|
||||
.expect("serialize root package json"),
|
||||
)
|
||||
.expect("write root package json");
|
||||
|
||||
let plan = resolve_publish_build_plan(&root).expect("解析构建计划");
|
||||
assert_eq!(plan.cwd_relative, ".");
|
||||
assert_eq!(plan.command, "node build-root.mjs");
|
||||
assert!(!plan.needs_dependency_install);
|
||||
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_export_runs_project_build_before_packaging() {
|
||||
let root = unique_project_path();
|
||||
init_local_game_project_at(&root, "project-auto-build", "自动构建发布项目")
|
||||
.expect("project init");
|
||||
// 只有源码:package.json 声明 build,构建脚本产出 dist/ 可玩产物。
|
||||
fs::write(
|
||||
root.join("package.json"),
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "publish-auto-build-fixture",
|
||||
"private": true,
|
||||
"scripts": { "build": "node build-publish.mjs" }
|
||||
}))
|
||||
.expect("serialize package json"),
|
||||
)
|
||||
.expect("write package json");
|
||||
fs::write(
|
||||
root.join("build-publish.mjs"),
|
||||
r#"import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
mkdirSync('dist/assets', { recursive: true });
|
||||
writeFileSync('dist/index.html', '<!doctype html><html><head><meta charset="utf-8"><title>Auto Build</title><script src="assets/app.js"></script></head><body><h1>AUTO-BUILD</h1></body></html>');
|
||||
writeFileSync('dist/assets/app.js', 'document.documentElement.dataset.autoBuild = "1";');
|
||||
"#,
|
||||
)
|
||||
.expect("write build script");
|
||||
write_local_project_file_at(&root, "exports/README.md", "publish notes").expect("write readme");
|
||||
|
||||
let result = export_local_project_package_for_publish_at(&root)
|
||||
.await
|
||||
.expect("发布前构建并导出");
|
||||
|
||||
assert!(root.join("dist/index.html").is_file());
|
||||
assert!(root.join("dist/assets/app.js").is_file());
|
||||
assert!(result
|
||||
.package_relative_path
|
||||
.starts_with("exports/playtest-package-"));
|
||||
let log = fs::read_to_string(root.join(".agent/logs/command.log")).unwrap_or_default();
|
||||
assert!(
|
||||
log.contains("project.verify build"),
|
||||
"发布前应记录一次 project.verify build:{log}"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_export_skips_build_when_playable_entry_exists() {
|
||||
let root = unique_project_path();
|
||||
init_existing_html_project_at(&root, "project-publish-skip", "已构建发布项目")
|
||||
.expect("project init");
|
||||
write_local_project_file_at(&root, "game/index.html", &fake_llm_game_draft().game_html)
|
||||
.expect("write playable html");
|
||||
write_local_project_file_at(&root, "exports/README.md", "publish notes").expect("write readme");
|
||||
|
||||
let result = export_local_project_package_for_publish_at(&root)
|
||||
.await
|
||||
.expect("已有可玩入口时直接导出");
|
||||
|
||||
assert!(result.package_relative_path.ends_with(".zip"));
|
||||
let log = fs::read_to_string(root.join(".agent/logs/command.log")).unwrap_or_default();
|
||||
assert!(
|
||||
!log.contains("project.verify build"),
|
||||
"已有可玩入口时不应触发构建:{log}"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn publish_export_reports_actionable_error_without_entry_or_build_script() {
|
||||
let root = unique_project_path();
|
||||
init_local_game_project_at(&root, "project-no-entry", "缺少可玩入口项目")
|
||||
.expect("project init");
|
||||
// 脚手架默认带 build 脚本;这里改成只有 check 脚本,模拟“没有可玩产物且没有构建脚本”。
|
||||
fs::write(
|
||||
root.join("game/package.json"),
|
||||
serde_json::to_string_pretty(&serde_json::json!({
|
||||
"name": "publish-no-entry-fixture",
|
||||
"private": true,
|
||||
"scripts": { "check": "node -e \"process.exit(0)\"" }
|
||||
}))
|
||||
.expect("serialize package json"),
|
||||
)
|
||||
.expect("write package json");
|
||||
|
||||
let error = export_local_project_package_for_publish_at(&root)
|
||||
.await
|
||||
.expect_err("缺少入口且没有 build 脚本时必须失败关闭");
|
||||
|
||||
assert!(
|
||||
error.contains("还没有可玩入口"),
|
||||
"错误应说明缺少可玩入口:{error}"
|
||||
);
|
||||
assert!(
|
||||
error.contains("build 脚本"),
|
||||
"错误应指向 build 脚本:{error}"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_project_export_package_publish_payload_contains_bytes_and_file_digests() {
|
||||
let root = unique_project_path();
|
||||
|
||||
@@ -1206,27 +1206,16 @@ export function App({
|
||||
* 权限口径沿用本地命令:`project.export_package` 需要确认时先入队,确认后再导出;
|
||||
* 导出结果只留在壳里,发布面板关闭即丢弃,不写入项目。
|
||||
*/
|
||||
/**
|
||||
* 发布相关提示同时写工作台状态与 DirectProject 对话。
|
||||
*
|
||||
* 普通项目走 `DirectProjectChatView` 时并不渲染工作台状态行,只写 workspaceStatus
|
||||
* 会让「点了发布没反应」;这里统一通过聊天容器的 announce 出口回话。
|
||||
*/
|
||||
function announcePublishMessage(message: string) {
|
||||
setWorkspaceStatus(message);
|
||||
directProjectChatRef.current?.announce(message);
|
||||
}
|
||||
|
||||
async function requestGamePublish() {
|
||||
const invoke = resolveTauriInvoke();
|
||||
if (!invoke) {
|
||||
announcePublishMessage('需要在 Tauri App 内发布');
|
||||
setWorkspaceStatus('需要在 Tauri App 内发布');
|
||||
return;
|
||||
}
|
||||
const nextProjectPath =
|
||||
resolveChatProjectPath(localProject) ?? projectPath.trim();
|
||||
if (!nextProjectPath) {
|
||||
announcePublishMessage('先打开一个项目再发布');
|
||||
setWorkspaceStatus('先打开一个项目再发布');
|
||||
return;
|
||||
}
|
||||
const runExport = async () => {
|
||||
@@ -1235,9 +1224,7 @@ export function App({
|
||||
'export_local_project_package',
|
||||
{ projectPath: nextProjectPath },
|
||||
);
|
||||
announcePublishMessage(
|
||||
`已构建并打包试玩包:${result.packageRelativePath}`,
|
||||
);
|
||||
setWorkspaceStatus(`已导出本地试玩包:${result.packageRelativePath}`);
|
||||
setPublishPackageResult(result);
|
||||
setPublishPanelOpen(true);
|
||||
appendLocalPermissionLog(
|
||||
@@ -1246,7 +1233,7 @@ export function App({
|
||||
'project.export_package',
|
||||
);
|
||||
} catch (error) {
|
||||
announcePublishMessage(
|
||||
setWorkspaceStatus(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
Component,
|
||||
createContext,
|
||||
isValidElement,
|
||||
memo,
|
||||
useContext,
|
||||
} from 'react';
|
||||
import ReactMarkdown, { type Components } from 'react-markdown';
|
||||
@@ -303,15 +302,7 @@ const streamingMarkdownComponents: Components = {
|
||||
p: StreamingMarkdownParagraph,
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析器的输入只有 `text` / `role` / `streaming` / `preserveBlankLines` 这几个标量,所以
|
||||
* 内容没变的旧消息在父级重渲染时可以直接跳过:Markdown 解析与语法高亮是这个组件里最贵的
|
||||
* 两件事(`react-markdown` 每次渲染都会重建 `unified()` 处理器并重跑全部插件),而旧消息
|
||||
* 的文本永远不会再改。
|
||||
*/
|
||||
export const ChatMarkdownMessage = memo(ChatMarkdownMessageImpl);
|
||||
|
||||
function ChatMarkdownMessageImpl({
|
||||
export function ChatMarkdownMessage({
|
||||
text,
|
||||
role,
|
||||
streaming = false,
|
||||
@@ -326,13 +317,8 @@ function ChatMarkdownMessageImpl({
|
||||
<ReactMarkdown
|
||||
skipHtml
|
||||
remarkPlugins={[remarkGfm]}
|
||||
// 流式中不高亮:高亮要跑一遍完整 AST + highlight.js,而流式增量会让同一段代码
|
||||
// 每来一个 chunk 就重新高亮一次(文本还在长,结果立刻作废)。文本定稿时
|
||||
// `streaming` 变回 false,这一笔高亮自然补上。
|
||||
rehypePlugins={
|
||||
streaming || text.length > MAX_HIGHLIGHT_CHARACTERS
|
||||
? []
|
||||
: [rehypeHighlight]
|
||||
text.length <= MAX_HIGHLIGHT_CHARACTERS ? [rehypeHighlight] : []
|
||||
}
|
||||
components={
|
||||
streaming ? streamingMarkdownComponents : markdownComponents
|
||||
|
||||
+3
-10
@@ -1,5 +1,5 @@
|
||||
import { ChevronDown, Lightbulb } from 'lucide-react';
|
||||
import { memo, useMemo, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { AgentMessageContent } from '../../../../../../../../packages/shared/src/components/AgentMessageContent';
|
||||
import { AgentProcessSummary } from '../../../../../../../../packages/shared/src/components/AgentProcessSummary';
|
||||
@@ -12,9 +12,7 @@ import { agentProcessPreview } from '../../../../../features/project-workspace/a
|
||||
* 折叠态是单行纯文本预览(Markdown 只取可见文字,符号不进预览);展开态复用助手正文的
|
||||
* 安全 Markdown 链路。这里只有表现与展开态,思考内容本身由两条产品路径各自的事实源提供。
|
||||
*/
|
||||
export const AgentReasoning = memo(AgentReasoningImpl);
|
||||
|
||||
function AgentReasoningImpl({
|
||||
export function AgentReasoning({
|
||||
text,
|
||||
label = '思考过程',
|
||||
testId,
|
||||
@@ -24,12 +22,7 @@ function AgentReasoningImpl({
|
||||
testId?: string;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
/*
|
||||
折叠态那一行预览是**完整 Markdown AST 解析**(`remark-parse` + `unified`),和展开态
|
||||
`react-markdown` 那次解析是两笔开销;上面那层 `memo` 让内容没变的思考块整个跳过,
|
||||
这里的 `useMemo` 再兜一层,避免同一文本在真正重渲染时被重算。
|
||||
*/
|
||||
const preview = useMemo(() => agentProcessPreview(text), [text]);
|
||||
const preview = agentProcessPreview(text);
|
||||
return (
|
||||
<AgentMessageContent
|
||||
as="details"
|
||||
|
||||
+8
-16
@@ -104,7 +104,7 @@ export type DirectProjectChatControllerProps = {
|
||||
* 传输层(三条通道,前端各拉各的)
|
||||
* A 运行态:notify → invoke consume_direct_project_thread → events[](实时)
|
||||
* B 历史: invoke read_direct_project_history_slice → items[](分页,文件尾反向扫描)
|
||||
* C 本地: 前端自己造(乐观用户气泡、忙态、失败 / 终止说明)
|
||||
* C 本地: 前端自己造(乐观用户气泡、忙态、终止说明)
|
||||
* ▼
|
||||
* 前端
|
||||
* useDirectThreadChatSubscription reducer:A + B 进同一份 state(turnRunning / history / live)
|
||||
@@ -121,6 +121,8 @@ export type DirectProjectChatControllerProps = {
|
||||
* 经历史切片读取(首屏按 `lastCompletedItemId` 锚定)。
|
||||
* - 运行态事件(subscribe / consume / notify):进程内;`turn.started` / `turn.completed` 是原生回合
|
||||
* 活跃与否的**唯一**判据;可回收事件被回收后靠 `lifecycle_anchor` 保住最新一条生命周期事件。
|
||||
* 失败也走这条流:`turn.completed.failure` 自己带脱敏后的原因,reducer 把它落成本轮说明条目;
|
||||
* 命令返回那条通道只提供横幅与诊断,不再写聊天文案。
|
||||
* - 本地发送:只存在于本次会话,`projectPath` 变化即清空;乐观气泡与原生条目同身份
|
||||
* (`direct-codex:{clientTurnId}:user`),所以两边按**身份**合并,不按时间戳猜。
|
||||
*
|
||||
@@ -131,7 +133,8 @@ export type DirectProjectChatControllerProps = {
|
||||
* 3. notify → consume → `turn.started`:reducer 的 `turnRunning=true`、`turnStartedAt`、`turnUserItemId`。
|
||||
* 4. `item.completed`(本轮用户条目回显):同身份条目已在历史里就合并进去,否则进 `live`;本地气泡此时被去重。
|
||||
* 5. `item.delta` / `item.started` / `item.completed`:正文追加、工具卡片 upsert(先到定形、后到只补空)。
|
||||
* 6. `turn.completed`:`live` 并入 `history` 后清空,`turnEndedAt` 冻结,边界按身份盖到本轮开口条目上。
|
||||
* 6. `turn.completed`:`live` 并入 `history` 后清空,`turnEndedAt` 冻结,边界按身份盖到本轮开口条目上;
|
||||
* 带 `failure` 载荷时,说明条目已经在上一步由 reducer 落进 `live`,随本轮一起并入历史。
|
||||
* 7. 命令收尾(`finally`):刷新清单 → `endTurnCommand()` 清掉忙态与在途身份 → 出队下一轮。
|
||||
* **顺序是契约**:出队会同步开始下一轮并设上它自己的忙态,所以清忙态必须早于出队;
|
||||
* 权限被拒那种「本轮从未发出但要继续出队」的情况,也只标记 `queueAdvance`、由这里统一收口。
|
||||
@@ -592,13 +595,6 @@ export function useDirectProjectChatController({
|
||||
});
|
||||
return;
|
||||
}
|
||||
// 真失败:这条命令返回就说明这一轮在宿主那边已经收场,但终态事件可能永远不来
|
||||
// (app-server 崩了、任务被中止、panic 都只留下一条开着的 `turn.started`)。
|
||||
// 按本轮身份放掉原生忙态,否则界面会一直显示「正在处理」、输入盒一直排队。
|
||||
// 主动终止与「正在跑的是另一轮」不走这里:前者宿主必然补终态,后者不是这一轮。
|
||||
directThread.stopCommandTurn(
|
||||
directCodexConversationMessageId(input.clientTurnId, 'user'),
|
||||
);
|
||||
void captureAgentRuntimeError(error, DIRECT_CODEX_AGENT_ID);
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
let persistedDetail = '';
|
||||
@@ -621,14 +617,10 @@ export function useDirectProjectChatController({
|
||||
true,
|
||||
);
|
||||
if (projectPathRef.current !== nextProjectPath) return;
|
||||
// 聊天里的失败说明不再由这里写:宿主已经把脱敏后的原因放进了
|
||||
// `turn.completed.failure`,reducer 会把它落成本轮最后一条条目(唯一来源)。这里只保留
|
||||
// 运行错误横幅(含 `详情:` 那份长 detail)与诊断留痕,两条通道不再各写一份文案。
|
||||
onRuntimeError(visibleMessage);
|
||||
appendLocalMessage({
|
||||
role: 'assistant',
|
||||
text: visibleMessage,
|
||||
runtimeOwned: true,
|
||||
messageId: `direct-codex:${input.clientTurnId}:failure`,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
-14
@@ -19,7 +19,6 @@ import {
|
||||
mergeDirectHistoryItems,
|
||||
resolveDirectThreadBootstrap,
|
||||
selectDirectChatEntries,
|
||||
stopDirectThreadTurn,
|
||||
} from '../conversation/directThreadChat';
|
||||
import type { DirectThreadConsumeResult } from '../generated/DirectThreadConsumeResult';
|
||||
import type { DirectThreadItem } from '../generated/DirectThreadItem';
|
||||
@@ -41,11 +40,6 @@ export type DirectThreadChatSubscription = {
|
||||
mergeHistoryItems: (items: readonly DirectThreadItem[]) => void;
|
||||
/** 终止成功(`released`)时手动放掉回合占用:订阅可能要等下一个事件才知道。 */
|
||||
markTurnStopped: () => void;
|
||||
/**
|
||||
* 本地命令失败收场时按身份放掉这一轮:宿主的终态事件可能永远不会来(进程崩了 /
|
||||
* 任务被中止),不能一直挂在 `turn.started` 上显示「正在处理」。
|
||||
*/
|
||||
stopCommandTurn: (userItemId: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -191,13 +185,6 @@ export function useDirectThreadChatSubscription({
|
||||
[],
|
||||
);
|
||||
|
||||
const stopCommandTurn = useMemo(
|
||||
() => (userItemId: string) => {
|
||||
setState((current) => stopDirectThreadTurn(current, userItemId));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const entries = useMemo(() => selectDirectChatEntries(state), [state]);
|
||||
|
||||
return {
|
||||
@@ -207,6 +194,5 @@ export function useDirectThreadChatSubscription({
|
||||
anchorGateRef,
|
||||
mergeHistoryItems,
|
||||
markTurnStopped,
|
||||
stopCommandTurn,
|
||||
};
|
||||
}
|
||||
|
||||
+25
-60
@@ -5,6 +5,10 @@
|
||||
* 运行态独有条目。这里不做可见性判断(那是投影的事):DirectProject 同一时刻只有一个回合在跑,
|
||||
* `turn.started` / `turn.completed` 只切换"是否还在跑"这一个布尔;回合身份只用原生生命周期
|
||||
* 事件自带的 canonical user identity(`userItemId`)做展示边界关联,不新建回合注册表。
|
||||
*
|
||||
* 失败(`turn.completed.status === "failed"`)不是第二套生命周期:终态还是同一个事件,只是带了
|
||||
* `failure` 载荷。这里把载荷落成本轮最后一条说明条目再走同一个收口函数——失败文案的唯一来源
|
||||
* 就是事件流,命令返回只服务运行错误横幅与诊断。
|
||||
*/
|
||||
|
||||
import type { GameCreatorDirectToolCall } from '../../../../app/types';
|
||||
@@ -14,6 +18,10 @@ import type { DirectThreadHistorySlice } from '../generated/DirectThreadHistoryS
|
||||
import type { DirectThreadItem } from '../generated/DirectThreadItem';
|
||||
import type { DirectThreadSubscriptionBootstrap } from '../generated/DirectThreadSubscriptionBootstrap';
|
||||
import { projectDirectThreadItem } from './directThreadItemProjection';
|
||||
import {
|
||||
directTurnFailureItemId,
|
||||
directTurnFailureNoticeText,
|
||||
} from './directTurnFailure';
|
||||
|
||||
export type DirectChatEntryKind = 'message' | 'reasoning' | 'tool';
|
||||
|
||||
@@ -65,16 +73,6 @@ export type DirectThreadChatState = {
|
||||
* 也不用时间戳近似。空串 = 原生没给身份(旧事件),此时不猜历史归属。
|
||||
*/
|
||||
turnUserItemId: string;
|
||||
/**
|
||||
* 「本地命令已经返回、宿主却一直没给终态」的那一轮身份(见 `stopDirectThreadTurn`)。
|
||||
*
|
||||
* `turn.started` 与 `turn.completed` 是原生回合唯一的开闭配对,但**进程崩了、任务被
|
||||
* 中止、panic** 这类收场不会补终态事件,只留一条永远开着的 `turn.started`:界面上就
|
||||
* 一直显示「正在处理」,输入盒也一直忙。本地那一条命令(`chat_with_game_creator_direct_codex`)
|
||||
* 返回时说到底就是"这一轮在宿主那边已经收场",这条身份就是它的记录:同身份的
|
||||
* `turn.started` 迟到 / 重放回来不再复活这一轮,避免收口之后又被拉回运行态。
|
||||
*/
|
||||
commandClosedTurnUserItemId: string;
|
||||
/** 历史切片条目,保持文件顺序。 */
|
||||
history: DirectChatEntry[];
|
||||
/** 当前回合的运行态条目,保持到达顺序;回合结束即并入历史并清空。 */
|
||||
@@ -87,40 +85,11 @@ export function emptyDirectThreadChatState(): DirectThreadChatState {
|
||||
turnStartedAt: 0,
|
||||
turnEndedAt: 0,
|
||||
turnUserItemId: '',
|
||||
commandClosedTurnUserItemId: '',
|
||||
history: [],
|
||||
live: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地命令失败收场:这一轮命令已经返回,宿主却还在事件流里挂着 `turn.started`。
|
||||
*
|
||||
* 只放掉"是否在跑",**不写终态时间**——命令返回不等于我们知道这一轮真正的结束时刻,
|
||||
* 编一个只会让耗时变成假数。收口后同身份的 `turn.started` 迟到 / 重放回来不再复活,
|
||||
* 免得刚修好的"还在处理"又被拉起来。宿主随后真发来 `turn.completed` 时照旧正常收口。
|
||||
*
|
||||
* 身份不同的轮次不动:宿主同时只允许一条回合,但"正在跑的是另一轮"(`another-turn-running`)
|
||||
* 这种拒绝也要能原样报给用户,不能顺手把别人那轮抹掉。空身份(宿主没能落上身份)时按
|
||||
* 本轮处理,否则这条兜底永远盖不住协议早期失败。
|
||||
*/
|
||||
export function stopDirectThreadTurn(
|
||||
state: DirectThreadChatState,
|
||||
userItemId: string,
|
||||
): DirectThreadChatState {
|
||||
if (state.turnUserItemId !== '' && state.turnUserItemId !== userItemId) {
|
||||
return state;
|
||||
}
|
||||
if (!state.turnRunning && state.commandClosedTurnUserItemId === userItemId) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
turnRunning: false,
|
||||
commandClosedTurnUserItemId: userItemId,
|
||||
};
|
||||
}
|
||||
|
||||
/** 时间戳合法性:缺失 / 0 / 非有限都算没有这个边界,不用它计任何耗时。 */
|
||||
function validBoundaryAt(value: number | null | undefined): number {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
||||
@@ -341,14 +310,6 @@ export function reduceDirectThreadEvent(
|
||||
// 本轮的 canonical user identity 跟着事件走:新回合就换成新的;旧原生不带身份时
|
||||
// 清空而不是继承上一轮,避免上一轮迟到的终态按身份匹配到这一轮。
|
||||
const turnUserItemId = readDirectThreadEventUserItemId(event);
|
||||
// 本地命令已经收过场的那一轮:迟到的 `turn.started` 不得把它拉回运行态(见
|
||||
// `commandClosedTurnUserItemId`)。身份按 clientTurnId 唯一,只挡它自己那一轮。
|
||||
if (
|
||||
turnUserItemId !== '' &&
|
||||
turnUserItemId === state.commandClosedTurnUserItemId
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
turnRunning: true,
|
||||
@@ -370,20 +331,23 @@ export function reduceDirectThreadEvent(
|
||||
return state;
|
||||
}
|
||||
// 已经收口、而且没有新的运行态条目:重复 / 迟到的终态事件不改动时间,也不复活运行态。
|
||||
// 例外是"本地命令兜底收口"的那一轮(`commandClosedTurnUserItemId` 命中且还没有终态
|
||||
// 时间):那次收口本来就没写时间,宿主这份迟到的终态要拿来补上真正的结束时刻。
|
||||
const lateTerminalForCommandClosedTurn =
|
||||
eventUserItemId !== '' &&
|
||||
eventUserItemId === state.commandClosedTurnUserItemId &&
|
||||
state.turnEndedAt <= 0;
|
||||
if (
|
||||
!state.turnRunning &&
|
||||
state.live.length === 0 &&
|
||||
!lateTerminalForCommandClosedTurn
|
||||
) {
|
||||
if (!state.turnRunning && state.live.length === 0) {
|
||||
return state;
|
||||
}
|
||||
return finishDirectThreadTurn(state, eventAt);
|
||||
// 失败终态带 `failure` 载荷:先把它落成本轮最后一条说明条目,再和正常终态走同一个收口
|
||||
// 函数。载荷在、原因非空才算一条说明;空原因不补一条空气泡(终态照样收口)。
|
||||
const failure = event.failure;
|
||||
const withNotice =
|
||||
failure && failure.message.trim()
|
||||
? upsertLiveEntry(state, {
|
||||
itemId: directTurnFailureItemId(eventUserItemId, eventAt),
|
||||
kind: 'message',
|
||||
role: 'assistant',
|
||||
text: directTurnFailureNoticeText(failure.message),
|
||||
at: eventAt,
|
||||
})
|
||||
: state;
|
||||
return finishDirectThreadTurn(withNotice, eventAt);
|
||||
}
|
||||
case 'item.delta':
|
||||
return appendLiveText(state, event);
|
||||
@@ -426,7 +390,8 @@ export function reduceDirectThreadEvent(
|
||||
/**
|
||||
* 回合收口:把运行态条目并入历史、清空运行态,并固定本轮终态时间。
|
||||
*
|
||||
* `endedAt` 只接受明确的终态时间(`turn.completed.at`,或宿主终止收口时观测到的时刻):
|
||||
* `endedAt` 只接受明确的终态时间:`turn.completed.at`(正常与失败同源),或宿主终止收口时
|
||||
* 观测到的时刻。
|
||||
* 缺失就是缺失,宁可不显示总耗时,也不用最后一条工具 / 正文的时间顶替。
|
||||
* 已经冻结的终态时间不会被后来的调用抬高;开始时间只记原生值,用户实际发送时间的优先级
|
||||
* 由投影层决定(条目上的 `at` 才是气泡时间)。
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 失败终态的展示口径:`turn.completed.failure` 载荷怎么变成聊天里那条说明。
|
||||
*
|
||||
* 只放两条规则,别在这里做事件归并(那是 `directThreadChat.ts` 的事):
|
||||
* 1. 说明条目的展示身份怎么派生;
|
||||
* 2. 事件里的原始原因怎么变成用户可见文案。
|
||||
*
|
||||
* 为什么值得单独一个文件:这两条是**跨侧约定**——身份要和前端自己造的说明(终止 / announce)
|
||||
* 区分开又保持可预期,文案映射要和运行错误横幅用同一份规则。把它们散在 reducer 里,读代码的人
|
||||
* 只能靠猜"这条失败说明是从哪冒出来的"。
|
||||
*/
|
||||
|
||||
import { projectRuntimeVisibleError } from '../../../../features/agent-runtime';
|
||||
|
||||
/** 没有本轮开口条目身份时的兜底展示身份前缀(正常路径不会用到)。 */
|
||||
const DIRECT_TURN_FAILURE_FALLBACK_ITEM_ID = 'direct-thread-turn-failure';
|
||||
|
||||
/**
|
||||
* 失败说明条目的**展示身份**:本轮开口用户条目的 canonical identity + `:failure` 后缀。
|
||||
*
|
||||
* 它是派生身份,不是原生条目身份——宿主只在 `turn.completed.failure` 里给原因,不额外造条目。
|
||||
* 用本轮身份派生可以保证"同一轮只有一条说明、跨轮不会合并",也不会和原生 itemId 撞车。
|
||||
* 身份不可证明(本轮没有落盘用户条目)时退化成与事件时间绑定的固定形状:它随事件固定、
|
||||
* 重放不变,又不会让两轮失败互相覆盖。
|
||||
*/
|
||||
export function directTurnFailureItemId(
|
||||
userItemId: string | null | undefined,
|
||||
at: number,
|
||||
): string {
|
||||
const identity = typeof userItemId === 'string' ? userItemId.trim() : '';
|
||||
if (identity) return `${identity}:failure`;
|
||||
return at > 0
|
||||
? `${DIRECT_TURN_FAILURE_FALLBACK_ITEM_ID}:${at}`
|
||||
: DIRECT_TURN_FAILURE_FALLBACK_ITEM_ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败原因的可见文案:与运行错误横幅共用同一份映射(`projectRuntimeVisibleError`)。
|
||||
*
|
||||
* 事件里的 `message` 是宿主已脱敏 + 截断的原始原因,这里只做"给人看"的那一步,不再另开文案
|
||||
* 规则,也不在这里判断"这算不算失败"(那由事件载荷的有没有决定)。
|
||||
*/
|
||||
export function directTurnFailureNoticeText(message: string): string {
|
||||
const raw = typeof message === 'string' ? message.trim() : '';
|
||||
return projectRuntimeVisibleError(raw, '陶泥儿智能创作', true);
|
||||
}
|
||||
+4
-1
@@ -239,7 +239,10 @@ function newTurn(key: string): DirectChatTurnEntries {
|
||||
* 条目 + 运行期本地消息 → 回合列表。
|
||||
*
|
||||
* 每个用户条目开一个新回合;本地用户气泡(乐观发送)也算开新回合;本地 assistant 消息
|
||||
* (失败 / 终止说明)挂到当前回合末尾。同身份的本地消息不重复渲染:条目赢。
|
||||
* (终止说明、壳层 `announce`)挂到当前回合末尾。同身份的本地消息不重复渲染:条目赢。
|
||||
*
|
||||
* 失败说明不在这条本地通道里:它是宿主 `turn.completed.failure` 载荷落成的普通条目,来源与
|
||||
* 顺序都归 reducer。
|
||||
*/
|
||||
export function buildDirectChatTurns({
|
||||
entries,
|
||||
|
||||
+9
@@ -2,6 +2,7 @@
|
||||
import type { DirectThreadDeltaKind } from './DirectThreadDeltaKind';
|
||||
import type { DirectThreadItem } from './DirectThreadItem';
|
||||
import type { DirectThreadRequestKind } from './DirectThreadRequestKind';
|
||||
import type { DirectTurnFailure } from './DirectTurnFailure';
|
||||
|
||||
/**
|
||||
* Thread Manager 下发的运行态事件。
|
||||
@@ -41,7 +42,15 @@ export type DirectThreadEvent =
|
||||
}
|
||||
| {
|
||||
type: 'turn.completed';
|
||||
/**
|
||||
* 终态语义:`completed` / `interrupted` / `aborted` 是正常收场;`failed` 是**失败**,
|
||||
* 此时必须带 `failure` 载荷。
|
||||
*/
|
||||
status: string;
|
||||
/**
|
||||
* 失败载荷:只有 `status == "failed"` 才有;失败原因只从这里下发一次。
|
||||
*/
|
||||
failure?: DirectTurnFailure;
|
||||
/**
|
||||
* 本轮终态的阶段时间(毫秒):宿主处理终态的毫秒钟,或 `durationMs` + 高精度起点的派生值。
|
||||
*/
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* 失败终态的可下发载荷(`turn.completed.status == "failed"` 时必有,其余终态没有)。
|
||||
*
|
||||
* `kind` 是稳定分类,只给界面选语气,不参与流程分支;`message` 是**已在宿主侧脱敏并截断**的
|
||||
* 可展示原因——失败原因只走这一条通道,前端不再从命令返回或另一条 IPC 里另造文案。
|
||||
*/
|
||||
export type DirectTurnFailure = {
|
||||
/**
|
||||
* 稳定失败分类:`timeout` / `model-failed` / `transport-failed` / `request-rejected` /
|
||||
* `host-dropped`。
|
||||
*/
|
||||
kind: string;
|
||||
/**
|
||||
* 脱敏 + 截断后的失败原因。
|
||||
*/
|
||||
message: string;
|
||||
};
|
||||
@@ -504,7 +504,7 @@ export function registerChatComposerControlTests() {
|
||||
});
|
||||
});
|
||||
|
||||
it('stops claiming the turn is running when a failed send left turn.started open', async () => {
|
||||
it('closes the turn from the host failure payload instead of leaving it running', async () => {
|
||||
let harness: ReturnType<typeof createProjectChatRuntimeHarness> | null =
|
||||
null;
|
||||
const { surface } = await openDirectCodexSurface(
|
||||
@@ -512,13 +512,23 @@ export function registerChatComposerControlTests() {
|
||||
chat_with_game_creator_direct_codex: (
|
||||
args: Record<string, unknown> | undefined,
|
||||
) => {
|
||||
// 宿主先认领了这一轮(turn.started),随后崩掉:没有终态事件,命令以失败返回。
|
||||
harness?.emitDirectThreadEvents({
|
||||
type: 'turn.started',
|
||||
at: 5_000,
|
||||
userItemId: `direct-codex:${String(args?.clientTurnId ?? '')}:user`,
|
||||
});
|
||||
throw new Error('模拟宿主崩溃:turn.started 之后没有终态事件');
|
||||
// 宿主先认领了这一轮(turn.started),随后失败收场:失败原因由终态事件自己带出来,
|
||||
// 命令也以失败返回(真实宿主是先 append 终态、再把错误抛回前端)。
|
||||
const userItemId = `direct-codex:${String(args?.clientTurnId ?? '')}:user`;
|
||||
harness?.emitDirectThreadEvents(
|
||||
{ type: 'turn.started', at: 5_000, userItemId },
|
||||
{
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: {
|
||||
kind: 'request-rejected',
|
||||
message: 'codex-app-server-error:context-window-exceeded',
|
||||
},
|
||||
at: 6_000,
|
||||
userItemId,
|
||||
},
|
||||
);
|
||||
throw new Error('模拟宿主失败:错误只走终态事件,命令只回报失败');
|
||||
},
|
||||
},
|
||||
(directHarness) => {
|
||||
@@ -526,20 +536,28 @@ export function registerChatComposerControlTests() {
|
||||
},
|
||||
);
|
||||
const composer = within(surface).getByLabelText('陶泥儿对话内容');
|
||||
await submitDirectTurn(surface, composer, '崩掉的那条');
|
||||
await submitDirectTurn(surface, composer, '超限的那条');
|
||||
|
||||
// 聊天里的失败说明来自事件载荷(经同一份可见文案映射),不是命令返回的错误文本。
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
within(surface).getAllByText('陶泥儿智能创作 执行失败,请稍后重试')
|
||||
.length,
|
||||
within(surface).getAllByText(
|
||||
'陶泥儿智能创作 模型上下文已超限,请缩小任务范围后重试',
|
||||
).length,
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
// 命令已经收场:卡片和输入区都不能再声称"还在处理"。
|
||||
// 终态已经到了:卡片和输入区都不能再声称"还在处理"。
|
||||
expect(within(surface).queryAllByText('陶泥儿正在处理')).toHaveLength(0);
|
||||
expect(within(surface).queryByRole('button', { name: '终止' })).toBeNull();
|
||||
expect(
|
||||
within(surface).getByRole('button', { name: '发送' }),
|
||||
).not.toBeNull();
|
||||
// 命令返回那条通道只负责横幅:它不写第二条聊天文案。
|
||||
expect(
|
||||
within(surface).queryAllByText(
|
||||
'模拟宿主失败:错误只走终态事件,命令只回报失败',
|
||||
),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('keeps the next queued turn busy when the write gate refuses the running one', async () => {
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
reduceDirectThreadEvents,
|
||||
resolveDirectThreadBootstrap,
|
||||
selectDirectChatEntries,
|
||||
stopDirectThreadTurn,
|
||||
} from '../src/view/project-development/chat/conversation/directThreadChat';
|
||||
import type { DirectThreadItem } from '../src/view/project-development/chat/conversation/directThreadItemProjection';
|
||||
import type { DirectThreadEvent } from '../src/view/project-development/chat/generated/DirectThreadEvent';
|
||||
@@ -177,54 +176,6 @@ describe('DirectProject 聊天 reducer', () => {
|
||||
expect(selectDirectChatEntries(done)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('本地命令兜底收口后,迟到的同名 turn.started 不复活这一轮', () => {
|
||||
const identity = 'direct-codex:client-turn-1:user';
|
||||
const running = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
event(withUserItemId({ type: 'turn.started', at: 1_000 }, identity)),
|
||||
event({ type: 'item.completed', item: messageItem() }),
|
||||
]);
|
||||
expect(running.turnRunning).toBe(true);
|
||||
|
||||
const stopped = stopDirectThreadTurn(running, identity);
|
||||
expect(stopped.turnRunning).toBe(false);
|
||||
// 兜底收口不写终态时间:命令返回不等于知道这一轮真正的结束时刻。
|
||||
expect(stopped.turnEndedAt).toBe(0);
|
||||
|
||||
// 同一轮迟到的 turn.started 不再把它拉回运行态,运行态条目也没丢。
|
||||
const revived = reduceDirectThreadEvents(stopped, [
|
||||
event(withUserItemId({ type: 'turn.started', at: 2_000 }, identity)),
|
||||
]);
|
||||
expect(revived.turnRunning).toBe(false);
|
||||
expect(selectDirectChatEntries(revived)).toHaveLength(1);
|
||||
|
||||
// 宿主随后补上的真终态照旧收口,并把真正的结束时间补上。
|
||||
const late = reduceDirectThreadEvents(revived, [
|
||||
event(
|
||||
withUserItemId(
|
||||
{ type: 'turn.completed', status: 'failed', at: 3_000 },
|
||||
identity,
|
||||
),
|
||||
),
|
||||
]);
|
||||
expect(late.turnRunning).toBe(false);
|
||||
expect(late.turnEndedAt).toBe(3_000);
|
||||
});
|
||||
|
||||
it('本地命令兜底收口不碰身份不同的那轮', () => {
|
||||
const other = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
event(
|
||||
withUserItemId(
|
||||
{ type: 'turn.started', at: 1_000 },
|
||||
'direct-codex:client-turn-9:user',
|
||||
),
|
||||
),
|
||||
]);
|
||||
expect(
|
||||
stopDirectThreadTurn(other, 'direct-codex:client-turn-1:user')
|
||||
.turnRunning,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('历史切片搬运层不合并,合并发生在前端投影', () => {
|
||||
const state = mergeDirectHistoryItems(emptyDirectThreadChatState(), [
|
||||
toolStarted(),
|
||||
@@ -333,6 +284,165 @@ describe('DirectProject 聊天 reducer', () => {
|
||||
expect(entries[0]?.toolCall?.detail.command).toBe('{"cmd": "ls"}');
|
||||
});
|
||||
|
||||
describe('失败终态(turn.completed 带 failure 载荷)', () => {
|
||||
it('失败也是终态:收口本轮、冻结终点,并把原因落成本轮最后一条说明', () => {
|
||||
const failed = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
withUserItemId(
|
||||
event({ type: 'turn.started', at: 1_000_000 }),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
event({ type: 'item.started', at: 1_000_100, item: toolStarted() }),
|
||||
withUserItemId(
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: {
|
||||
kind: 'transport-failed',
|
||||
message: 'DirectProject 收尾历史失败:未确认历史完整落盘',
|
||||
},
|
||||
at: 1_000_900,
|
||||
}),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
]);
|
||||
|
||||
expect(failed.turnRunning).toBe(false);
|
||||
expect(failed.turnEndedAt).toBe(1_000_900);
|
||||
expect(failed.live).toHaveLength(0);
|
||||
const notice = failed.history.at(-1);
|
||||
expect(notice?.itemId).toBe('direct-codex:turn-1:user:failure');
|
||||
expect(notice?.role).toBe('assistant');
|
||||
expect(notice?.text).toBe('陶泥儿智能创作 执行失败,请稍后重试');
|
||||
// 本轮开口条目照样按身份拿到边界(失败与正常终态同源)。
|
||||
expect(selectDirectChatEntries(failed)[0]?.turnEndedAt).toBe(1_000_900);
|
||||
expect(selectDirectChatEntries(failed)[0]?.turnStartedAt).toBe(1_000_000);
|
||||
});
|
||||
|
||||
it('失败说明的可见文案与运行错误横幅共用同一份映射', () => {
|
||||
const failed = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
withUserItemId(
|
||||
event({ type: 'turn.started', at: 1_000 }),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: {
|
||||
kind: 'request-rejected',
|
||||
message: 'codex-app-server-error:context-window-exceeded',
|
||||
},
|
||||
at: 2_000,
|
||||
}),
|
||||
]);
|
||||
expect(failed.history.at(-1)?.text).toBe(
|
||||
'陶泥儿智能创作 模型上下文已超限,请缩小任务范围后重试',
|
||||
);
|
||||
});
|
||||
|
||||
it('重复 / 迟到的失败终态不追加第二条说明,也不抬高冻结终点或复活运行态', () => {
|
||||
const failed = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
withUserItemId(
|
||||
event({ type: 'turn.started', at: 1_000_000 }),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
withUserItemId(
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: { kind: 'model-failed', message: '模型服务暂不可用' },
|
||||
at: 1_000_900,
|
||||
}),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
]);
|
||||
|
||||
const replayed = reduceDirectThreadEvents(failed, [
|
||||
withUserItemId(
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: { kind: 'model-failed', message: '模型服务暂不可用' },
|
||||
at: 9_900_000,
|
||||
}),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
]);
|
||||
expect(replayed.turnRunning).toBe(false);
|
||||
expect(replayed.turnEndedAt).toBe(1_000_900);
|
||||
expect(
|
||||
replayed.history.filter((entry) => entry.itemId.endsWith(':failure')),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('身份不匹配的失败终态不动正在跑的这一轮', () => {
|
||||
const running = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
withUserItemId(
|
||||
event({ type: 'turn.started', at: 2_000_000 }),
|
||||
'direct-codex:turn-2:user',
|
||||
),
|
||||
]);
|
||||
const untouched = reduceDirectThreadEvents(running, [
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: { kind: 'model-failed', message: '上一轮的失败' },
|
||||
at: 2_000_900,
|
||||
userItemId: 'direct-codex:turn-1:user',
|
||||
}),
|
||||
]);
|
||||
expect(untouched.turnRunning).toBe(true);
|
||||
expect(untouched.turnEndedAt).toBe(0);
|
||||
expect(untouched.history).toHaveLength(0);
|
||||
expect(untouched.live).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('空原因不落说明条目,但终态照样收口', () => {
|
||||
const failed = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
withUserItemId(
|
||||
event({ type: 'turn.started', at: 1_000 }),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
withUserItemId(
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: { kind: 'host-dropped', message: ' ' },
|
||||
at: 2_000,
|
||||
}),
|
||||
'direct-codex:turn-1:user',
|
||||
),
|
||||
]);
|
||||
expect(failed.turnRunning).toBe(false);
|
||||
expect(failed.turnEndedAt).toBe(2_000);
|
||||
expect(failed.history).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('没有身份时用事件时间派生说明身份,两轮失败不会合并成一条', () => {
|
||||
const first = reduceDirectThreadEvents(emptyDirectThreadChatState(), [
|
||||
event({ type: 'turn.started', at: 1_000 }),
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: { kind: 'model-failed', message: '第一轮失败' },
|
||||
at: 2_000,
|
||||
}),
|
||||
]);
|
||||
const second = reduceDirectThreadEvents(first, [
|
||||
event({ type: 'turn.started', at: 3_000 }),
|
||||
event({
|
||||
type: 'turn.completed',
|
||||
status: 'failed',
|
||||
failure: { kind: 'model-failed', message: '第二轮失败' },
|
||||
at: 4_000,
|
||||
}),
|
||||
]);
|
||||
expect(second.history.map((entry) => entry.itemId)).toEqual([
|
||||
'direct-thread-turn-failure:2000',
|
||||
'direct-thread-turn-failure:4000',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('事件级计时边界', () => {
|
||||
/** 工具的开始 / 完成只读事件级 `at`,条目 `item.at` 不作起止。 */
|
||||
it('工具耗时只读事件级 at,不把 item.at 当开始或完成', () => {
|
||||
|
||||
@@ -24,6 +24,8 @@ AGC 项目开发聊天框当前同时从三处取数据:Direct 回合事件(
|
||||
- 合并只在前端,规则只保留「先到定形、后到补空白」:第一次见到的快照决定卡片形状,后续快照只补输出与状态,不做逐字段优先级表。只有"后到信息一定更全"时才例外:正文取更长的一份、工具状态允许从 `running` 升级到终态、`updatedAt` 取较新的时间。
|
||||
- 前端不保留增量缓冲:`item.delta` 直接追加到运行态条目的正文(正文只增不减)。`turn.completed` 把当前回合的运行态条目并入历史再清空,条目既不消失也不重复。
|
||||
- 活动回合的唯一判据是「出现过 `turn.started` 且未出现 `turn.completed`」;进程重启后队列消失,历史里的半截回合一律按已结束渲染。
|
||||
- 终态事件只有 `turn.completed` 一种,它同时承载三种语义:`status !== "failed"` 是正常结束 / 中断 / 终止,`status === "failed"` 是**失败**,且必须再带 `failure { kind, message }`(`message` 已脱敏截断)。失败原因只走这一条通道:前端不再从命令返回或另一条 IPC 里另造失败文案,聊天里那条失败说明仍落在同一个展示位上(本轮最后一条助手气泡、只在运行期显示),只是数据来源换成事件载荷;命令返回只用于运行错误横幅与诊断留痕。
|
||||
- 宿主侧兜底:`turn.started` 发出之后才武装 Drop 守卫,正常写完终态即解除;panic、future 被丢弃、终态之前的早退由守卫补一条 `status="failed"` + `failure.kind="host-dropped"` 的终态,避免前端永远停在"还在跑"。已知边界见「影响」一节。
|
||||
- 分页锚点取原始条目 id;一次翻页操作在前端自动连拉,直到出现可显示条目或 `hasMore=false`,上限 5 页。
|
||||
- `notify` 是唯一唤醒来源:`subscribe` 的 bootstrap 事件本身就是该 subscriber 此刻要处理的事件(游标已在队尾),前端直接 reduce 它们,不需要为了取这批事件再补一次 `consume`,之后完全由 `notify` 驱动,不设低频 tick 或任何轮询兜底。唯一例外是回执竞态:Rust 侧一注册完 subscriber 就开始 `notify`,前端却要等回执才知道自己的 `subscriptionId`,这段窗口内的通知只能记成欠账,回执到达后立刻补一次 `consume` 取回,否则该回合的尾部事件会卡在队列里等一个可能永不出现的下一次通知。
|
||||
- 迁移按一次干净切换落地:不做灰度、不做运行时开关、不双跑;允许提交序列里存在「新源已启用、旧代码尚未删除」的中间窗口,禁止反向的「新源未启用、旧源已删」。
|
||||
@@ -50,7 +52,9 @@ AGC 项目开发聊天框当前同时从三处取数据:Direct 回合事件(
|
||||
|
||||
- 旧项目磁盘上遗留的 `turn-stream.jsonl` / `tool-calls.jsonl` 保留不动,不迁移、不清理、不再由 DirectProject 聊天框读取。
|
||||
- 工具卡片的脱敏与截断必须在读取期执行一次,不能因为"原始条目已在磁盘"就把未脱敏内容直接渲染到界面。
|
||||
- 回合结束语义务必由 `turn.completed` 判定;缺少该事件的残留回合不得被渲染成运行中。
|
||||
- 回合结束语义务必由 `turn.completed` 判定(失败时同一事件带 `failure` 载荷,不新增事件类型);缺少该事件的残留回合不得被渲染成运行中。
|
||||
- 两条已知边界,都**不**在本次补路径:① 宿主进程被强杀(`kill -9`)时没有任何 `Drop` 会执行,前端仍会停在运行态,那要靠前端自己的"命令已返回却没有任何终态事件"判据;② `turn.started` 之前的早退(`turn/start` 请求失败、响应缺 `turn.id`、历史注入参数构建失败等)不产生回合、也不补终态事件——它们不会留下永远开着的回合,出问题时只有运行错误横幅解释。
|
||||
- 失败原因里的 `message` 是宿主侧脱敏 + 截断后的可展示文本,前端仍按既有口径做一次可见文案映射(`projectRuntimeVisibleError`),映射规则不因这次改动改变。
|
||||
- 「活动回合的唯一判据」约束的是**原生回合**:界面上的「本地已发出、原生还没认领」是投影的展示态(`DirectChatTurn.state = 'awaiting-start'`),由本地在途用户条目身份派生,不构成第二套原生生命周期,也不参与 `turnRunning` 的判定。
|
||||
- 三层数据流、变量归属与一次发送的时序写在代码里:`apps/ai-game-creator-shell/src/view/project-development/chat/controller/useDirectProjectChatController.ts` 的模块注释;回合三态的定义与判据真值表在 `apps/ai-game-creator-shell/src/view/project-development/chat/conversation/directTurnPresentation.ts` 的 `DirectChatTurnState`。改判据时同步这两处与对应测试。
|
||||
- 验收证据是端到端行为,不是单元测试:回合进行中杀掉应用进程后重开项目,应看到部分文本与工具卡片按原顺序出现且不显示忙碌;正常结束后重进应与实时渲染一致;文件系统不得再新增 `turn-stream.jsonl` / `tool-calls.jsonl`。
|
||||
|
||||
@@ -116,11 +116,6 @@
|
||||
- 发布入口灰度下发:`GET /api/runtime/frontend-config` 新增 `gameDistributionPublishEnabled`,复用既有 `is_game_distribution_publish_enabled_for_user`(未配置 `game-distribution:publish` 或 `enabled=false` 时对已登录作者默认开放,显式收紧后只放行白名单/灰度命中,匿名恒为 false),避免前端入口与写入口出现两套判据。网页端 `PlatformEntryActiveFlowShell` 据此隐藏「发布游戏 / 发布新版本」入口,`/games/publish` 直接访问时渲染「发布功能正在灰度中」并提供重新检查;AGC 端 `readGamePublishAvailability` 同样读该字段,只有命中才把发布回调交给 DirectProject 聊天头。
|
||||
- 灰度验证:`cargo test -p api-server frontend_runtime_config`(6 passed,含新增的 `frontend_runtime_config_game_distribution_publish_is_scoped_to_authenticated_gate`:无 gate 行 → 登录作者 true/匿名 false;`enabled=true` 无白名单 → false;白名单命中 → true;`deny_user_ids` → false;`enabled=false` → true;`rolloutPercent=100` → true)、网页发布页 15 用例(含灰度未命中隐藏表单与「重新检查」放行)、平台壳 18 用例(含广场入口按灰度隐藏/显示)、AGC 发布服务 6 用例(含字段缺失与读取失败按不开放处理)。
|
||||
|
||||
- Phaser 一键发布闭环(作者不构建、不打 ZIP):`export_local_project_package` 改为发布前构建——已有可玩入口直接打包,否则解析 `game/` 或项目根的 npm `build` 脚本(`resolve_publish_build_plan`),缺 `game/node_modules` 时先跑 `project.bootstrap`,再走 `project.verify` 的受控 npm 运行器执行 build,最后校验入口并打包;构建或安装失败返回带日志尾部的可操作错误。真实 Phaser 4.2.1 + Vite 7 工程验证:构建产物使用相对引用(`./assets/...`),ZIP 370,969 B 经真实素材直传 + 创建游戏/版本/上传/送审/审核通过后,发行网关 `index.html` 200(323 B)与 `assets/index-DZGg_tPs.js` 200(1,388,719 B),网页播放页在 `allow-scripts` 沙箱 iframe 内渲染出 `PHASER-PUBLISH-OK` 与可点击按钮。
|
||||
- 发行网关根路径:`GET /api/game-distribution/releases/{gameId}` 与带尾斜杠的同一路径等价于 `index.html`(生产由每游戏 origin 映射根路径,本地直连网关或入口直接填网关地址时同样可玩);路由级用例覆盖 Cookie 拒绝门与根路径。
|
||||
|
||||
- 发布灰度改为**默认关闭**并修掉客户端“看得到点不动”:`is_game_distribution_publish_enabled_for_user` 现在要求 gate 行存在且 `enabled=true`(未登录、无行、`enabled=false` 一律 false),因此没配灰度时 `gameDistributionPublishEnabled=false`,AGC 不再渲染「发布到游戏广场」按钮、网页入口也不出现;AGC 侧新增 `announcePublishMessage`,把「已构建并打包试玩包」「先打开一个项目再发布」等提示通过 DirectProject 聊天容器的 `announce` 出口回话(普通项目不渲染工作台状态行,之前只写 workspaceStatus 才会表现为点击无反应)。后台「灰度发布配置」新增「可配置开关」列表:预设开关在未创建行时也可见并可一键配置(不再需要先猜 gate key)。
|
||||
|
||||
## 尚未完成
|
||||
|
||||
- 真实独立发行域名、通配 TLS 与 CDN 仍属部署侧:边缘模板与门禁已就绪,本地已用真实 nginx 验证按主机映射、Cookie 403 与命名空间隔离,但仍需在真实域名/证书下跑一次“审核通过 → 游玩 → 换版 → 下架”并确认 CDN TTL 不超过 60 秒窗口。
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user