Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edfd1f9143 | |||
| 423f2d7184 | |||
| aa9076c95c | |||
| 41366dd71d | |||
| f4b496caca | |||
| fc0fd846f9 | |||
| fa99d9ad62 | |||
| 64a52005f8 | |||
| 645d806fed | |||
| 0b9d16e8f1 | |||
| d5c4e0e780 | |||
| 30e27abc60 | |||
| b607501916 | |||
| 46e3cd9744 | |||
| 5fb3db662b | |||
| 87b798322e | |||
| ec286b3480 | |||
| 35733f0e33 | |||
| 3c7b02b9f8 | |||
| f2030a616f | |||
| b3b5d77990 | |||
| 1da106af7d | |||
| cd2edd6966 | |||
| 22e830ff93 | |||
| c266ae7b50 | |||
| a543b75cf7 | |||
| f213987f9a | |||
| 2c623bb577 | |||
| 3353906e6f | |||
| 17716347e2 | |||
| 9ad66a67a3 | |||
| ba3aa3ccdb | |||
| 2b38eaafba | |||
| 7d5b9071e7 | |||
| 9e83f1d88c | |||
| 7e35d7c344 | |||
| 5ec40c8b83 | |||
| 948a80fc49 | |||
| dfd6fadedf |
-16
@@ -172,20 +172,6 @@ _Avoid_: 多步骤向导、完整规则编辑器、拖拽编辑器
|
|||||||
Bark Battle 平台作品闭环按契约与领域规则、后端存储/API、最小前端纵切、投影体验、收口验证的顺序推进。
|
Bark Battle 平台作品闭环按契约与领域规则、后端存储/API、最小前端纵切、投影体验、收口验证的顺序推进。
|
||||||
_Avoid_: mock 先行堆积、前后端各自发散、先做排行榜 UI
|
_Avoid_: mock 先行堆积、前后端各自发散、先做排行榜 UI
|
||||||
|
|
||||||
## 项目开发对话(DirectProject)
|
|
||||||
|
|
||||||
**项目对话历史**:
|
|
||||||
AGC 本地项目内 Codex 原始对话条目的持久集合,是聊天展示、工具卡片和线程恢复注入的唯一持久事实源。
|
|
||||||
_Avoid_: 会话缓存、展示态历史、按 UI 需要另存的对话副本
|
|
||||||
|
|
||||||
**运行态事件**:
|
|
||||||
Thread Manager 向订阅者推送的当前回合原始事件流,只服务运行期间与短期断线恢复,不替代项目对话历史。
|
|
||||||
_Avoid_: 进度通知、快照轮询、第二套历史
|
|
||||||
|
|
||||||
**聊天投影**:
|
|
||||||
把项目对话历史条目与运行态事件转换成消息气泡和工具卡片的读取期转换;不持久化,也不构成事实源。
|
|
||||||
_Avoid_: 投影缓存文件、已脱敏卡片库、第二套 reducer
|
|
||||||
|
|
||||||
## Relationships
|
## Relationships
|
||||||
|
|
||||||
- 一个 **汪汪声浪大作战** 单局包含多个 **有效声浪触发**。
|
- 一个 **汪汪声浪大作战** 单局包含多个 **有效声浪触发**。
|
||||||
@@ -220,5 +206,3 @@ _Avoid_: 投影缓存文件、已脱敏卡片库、第二套 reducer
|
|||||||
- “入口闭环”曾可能只指内部 demo 或单个详情 CTA;已解析为 **正式作品入口闭环**,不新增独立专区或活动页。
|
- “入口闭环”曾可能只指内部 demo 或单个详情 CTA;已解析为 **正式作品入口闭环**,不新增独立专区或活动页。
|
||||||
- “创作编辑”曾可能指多步骤向导或完整编辑器;已解析为 **轻配置编辑流程**,使用单页表单 + 预览卡片完成保存草稿、发布和发布后跳转作品详情。
|
- “创作编辑”曾可能指多步骤向导或完整编辑器;已解析为 **轻配置编辑流程**,使用单页表单 + 预览卡片完成保存草稿、发布和发布后跳转作品详情。
|
||||||
- “实施顺序”曾可能按 UI 或功能并行发散;已解析为契约/领域规则先行,再做后端存储/API,随后打通最小前端纵切,最后补投影体验与收口验证。
|
- “实施顺序”曾可能按 UI 或功能并行发散;已解析为契约/领域规则先行,再做后端存储/API,随后打通最小前端纵切,最后补投影体验与收口验证。
|
||||||
- “回合进度事件”曾同时指 Direct turn update 与 Thread Manager 运行态事件;已解析为 AGC 项目开发对话只保留 **运行态事件**。
|
|
||||||
- “哪些消息可显示”曾可能由后端历史分页判断;已解析为可见性判断属于 **聊天投影**,后端只按原始条目分页,前端负责跳过不可显示条目并推进分页锚点。
|
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ mod direct_project_history;
|
|||||||
mod direct_project_turn_history;
|
mod direct_project_turn_history;
|
||||||
mod direct_runtime;
|
mod direct_runtime;
|
||||||
mod direct_thread_manager;
|
mod direct_thread_manager;
|
||||||
mod direct_thread_wire;
|
|
||||||
mod direct_tool_bridge;
|
mod direct_tool_bridge;
|
||||||
mod direct_tool_calls;
|
mod direct_tool_calls;
|
||||||
mod direct_tools_mcp;
|
mod direct_tools_mcp;
|
||||||
@@ -56,7 +55,6 @@ pub(crate) use direct_project_history::*;
|
|||||||
pub(crate) use direct_project_turn_history::*;
|
pub(crate) use direct_project_turn_history::*;
|
||||||
pub(crate) use direct_runtime::*;
|
pub(crate) use direct_runtime::*;
|
||||||
pub(crate) use direct_thread_manager::*;
|
pub(crate) use direct_thread_manager::*;
|
||||||
pub(crate) use direct_thread_wire::*;
|
|
||||||
pub(crate) use direct_tool_bridge::*;
|
pub(crate) use direct_tool_bridge::*;
|
||||||
pub(crate) use direct_tool_calls::*;
|
pub(crate) use direct_tool_calls::*;
|
||||||
pub(crate) use direct_tools_mcp::*;
|
pub(crate) use direct_tools_mcp::*;
|
||||||
|
|||||||
@@ -564,17 +564,6 @@ enum CodexTurnEvent {
|
|||||||
item_id: String,
|
item_id: String,
|
||||||
delta: String,
|
delta: String,
|
||||||
},
|
},
|
||||||
/// 思考正文增量:app-server `item/reasoning/summaryTextDelta` 的明文思考文本。
|
|
||||||
///
|
|
||||||
/// `item/reasoning/summaryTextDelta`(core `ReasoningContentDelta`)与
|
|
||||||
/// `item/reasoning/textDelta`(core `ReasoningRawContentDelta`)都进这条通道:前者是
|
|
||||||
/// reasoning item 的 `summary`,后者是它的 `content`,两段文本都随 `item/completed`
|
|
||||||
/// 落进 `project.jsonl`、此前也已经在完成时展示给用户。plan 文本与命令输出仍然只降级为
|
|
||||||
/// 活动状态,不下发正文。
|
|
||||||
ReasoningDelta {
|
|
||||||
item_id: String,
|
|
||||||
delta: String,
|
|
||||||
},
|
|
||||||
IntermediateText(String),
|
IntermediateText(String),
|
||||||
Activity(&'static str),
|
Activity(&'static str),
|
||||||
Item {
|
Item {
|
||||||
@@ -582,7 +571,7 @@ enum CodexTurnEvent {
|
|||||||
params: serde_json::Value,
|
params: serde_json::Value,
|
||||||
},
|
},
|
||||||
Request {
|
Request {
|
||||||
kind: DirectThreadRequestKind,
|
event_type: &'static str,
|
||||||
params: serde_json::Value,
|
params: serde_json::Value,
|
||||||
},
|
},
|
||||||
RawItem(serde_json::Value),
|
RawItem(serde_json::Value),
|
||||||
@@ -752,14 +741,23 @@ fn direct_codex_safe_activity_for_item_value(item: &serde_json::Value) -> &'stat
|
|||||||
direct_codex_safe_activity_for_item(item_type)
|
direct_codex_safe_activity_for_item(item_type)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 运行态事件载荷:与历史切片同形的脱敏原始条目;拿不到身份或类型就整条跳过。
|
/// Project an app-server item into the small public payload carried by the
|
||||||
///
|
/// DirectProject event queue. Full item contents are persisted in JSONL and
|
||||||
/// 这里不生成工具卡片形状:标题、折叠摘要和可见性都是前端投影的职责。
|
/// must not be forwarded through the runtime event stream.
|
||||||
fn direct_thread_event_item(
|
fn direct_thread_item_started_payload(item: &serde_json::Value) -> serde_json::Value {
|
||||||
root: &std::path::Path,
|
serde_json::json!({
|
||||||
item: &serde_json::Value,
|
"itemType": item
|
||||||
) -> Option<DirectThreadItem> {
|
.get("type")
|
||||||
direct_thread_item_from_value(root, item, direct_tool_call_now_ms())
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.unwrap_or("unknown"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn direct_thread_item_id(item: &serde_json::Value) -> Option<String> {
|
||||||
|
item.get("id")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(str::to_string)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn direct_codex_command_is_game_verification(command: &str) -> bool {
|
fn direct_codex_command_is_game_verification(command: &str) -> bool {
|
||||||
@@ -976,21 +974,19 @@ fn direct_codex_safe_activity_for_notification(method: &str) -> Option<&'static
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn direct_codex_request_event_type(method: &str) -> Option<DirectThreadRequestKind> {
|
fn direct_codex_request_event_type(method: &str) -> Option<&'static str> {
|
||||||
match method {
|
match method {
|
||||||
"item/fileChange/requestApproval"
|
"item/fileChange/requestApproval"
|
||||||
| "item/commandExecution/requestApproval"
|
| "item/commandExecution/requestApproval"
|
||||||
| "item/permissions/requestApproval" => Some(DirectThreadRequestKind::ApprovalRequested),
|
| "item/permissions/requestApproval" => Some("approval.requested"),
|
||||||
"item/tool/requestUserInput" | "item/mcpToolCall/requestUserInput" => {
|
"item/tool/requestUserInput" | "item/mcpToolCall/requestUserInput" => Some("ask.requested"),
|
||||||
Some(DirectThreadRequestKind::AskRequested)
|
|
||||||
}
|
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn direct_codex_resolution_event_type(method: &str) -> Option<DirectThreadRequestKind> {
|
fn direct_codex_resolution_event_type(method: &str) -> Option<&'static str> {
|
||||||
match method {
|
match method {
|
||||||
"serverRequest/resolved" => Some(DirectThreadRequestKind::RequestResolved),
|
"serverRequest/resolved" => Some("request.resolved"),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1063,33 +1059,6 @@ fn direct_codex_notification_event(
|
|||||||
intermediate_text: Option<String>,
|
intermediate_text: Option<String>,
|
||||||
safe_activity: Option<&'static str>,
|
safe_activity: Option<&'static str>,
|
||||||
) -> Option<CodexTurnEvent> {
|
) -> Option<CodexTurnEvent> {
|
||||||
// 思考正文走独立通道,交给 DirectProject 的运行态事件;它不因为
|
|
||||||
// "preparing 活动" 的降级规则被丢掉,否则界面只能等 item/completed 才看到思考。
|
|
||||||
//
|
|
||||||
// 两条通知都下发正文,不下发活动文本:
|
|
||||||
// - `item/reasoning/summaryTextDelta`(core `ReasoningContentDelta`)→ reasoning item 的 `summary`;
|
|
||||||
// - `item/reasoning/textDelta`(core `ReasoningRawContentDelta`)→ reasoning item 的 `content`,
|
|
||||||
// 正是 `project.jsonl` 里保存、并在此前 `item/completed` 已经展示给用户的同一段文本。
|
|
||||||
// 因此这里只是把"完成时才看到"提前为"边生成边看到",没有放宽可见文本的范围;
|
|
||||||
// 未识别的 plan 文本与命令输出仍然只降级为活动状态,不下发正文。
|
|
||||||
if matches!(
|
|
||||||
method,
|
|
||||||
"item/reasoning/summaryTextDelta" | "item/reasoning/textDelta"
|
|
||||||
) {
|
|
||||||
return params
|
|
||||||
.get("delta")
|
|
||||||
.and_then(serde_json::Value::as_str)
|
|
||||||
.filter(|value| !value.is_empty())
|
|
||||||
.map(|delta| CodexTurnEvent::ReasoningDelta {
|
|
||||||
item_id: params
|
|
||||||
.get("itemId")
|
|
||||||
.and_then(serde_json::Value::as_str)
|
|
||||||
.filter(|value| !value.is_empty())
|
|
||||||
.map(str::to_string)
|
|
||||||
.unwrap_or_else(|| "direct-missing-item".to_string()),
|
|
||||||
delta: delta.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let (activity, intermediate_text) = match (&intermediate_text, safe_activity) {
|
let (activity, intermediate_text) = match (&intermediate_text, safe_activity) {
|
||||||
(Some(_), Some(activity)) if activity == "preparing" => (Some(activity), None),
|
(Some(_), Some(activity)) if activity == "preparing" => (Some(activity), None),
|
||||||
_ => (safe_activity, intermediate_text),
|
_ => (safe_activity, intermediate_text),
|
||||||
@@ -2957,7 +2926,18 @@ impl CodexAppServerConnection {
|
|||||||
turn_start_guard.armed = false;
|
turn_start_guard.armed = false;
|
||||||
let direct_thread_id = history_root.to_string_lossy().into_owned();
|
let direct_thread_id = history_root.to_string_lossy().into_owned();
|
||||||
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||||
append_direct_thread_event(&direct_thread_id, DirectThreadEvent::turn_started());
|
append_direct_thread_event(
|
||||||
|
&direct_thread_id,
|
||||||
|
DirectThreadRawEventDraft {
|
||||||
|
event_type: "turn.started".to_string(),
|
||||||
|
turn_id: turn_id.clone(),
|
||||||
|
item_id: None,
|
||||||
|
payload: serde_json::json!({
|
||||||
|
"threadId": thread_id,
|
||||||
|
"turnId": turn_id,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let mut receiver = self.register_turn(&turn_id).await;
|
let mut receiver = self.register_turn(&turn_id).await;
|
||||||
let mut direct_project_history = DirectProjectHistoryAccumulator::default();
|
let mut direct_project_history = DirectProjectHistoryAccumulator::default();
|
||||||
@@ -3012,13 +2992,12 @@ impl CodexAppServerConnection {
|
|||||||
direct_project_history.observe_delta(&item_id, &delta);
|
direct_project_history.observe_delta(&item_id, &delta);
|
||||||
append_direct_thread_event(
|
append_direct_thread_event(
|
||||||
&direct_thread_id,
|
&direct_thread_id,
|
||||||
// 事件自足:增量自带 item 身份与正文类别(正文 / 思考),
|
DirectThreadRawEventDraft {
|
||||||
// 前端 reducer 不允许靠猜 itemId 的来源决定 kind。
|
event_type: "item.delta".to_string(),
|
||||||
DirectThreadEvent::item_delta(
|
turn_id: turn_id.clone(),
|
||||||
item_id.clone(),
|
item_id: Some(item_id.clone()),
|
||||||
DirectThreadDeltaKind::Message,
|
payload: serde_json::json!({ "delta": delta.clone() }),
|
||||||
delta.clone(),
|
},
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
streamed_text.push_str(&delta);
|
streamed_text.push_str(&delta);
|
||||||
@@ -3049,18 +3028,6 @@ impl CodexAppServerConnection {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(CodexTurnEvent::ReasoningDelta { item_id, delta }) => {
|
|
||||||
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
|
||||||
append_direct_thread_event(
|
|
||||||
&direct_thread_id,
|
|
||||||
DirectThreadEvent::item_delta(
|
|
||||||
item_id,
|
|
||||||
DirectThreadDeltaKind::Reasoning,
|
|
||||||
delta,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(CodexTurnEvent::IntermediateText(text)) => {
|
Some(CodexTurnEvent::IntermediateText(text)) => {
|
||||||
if let Some(observer) = direct_observer.as_deref_mut() {
|
if let Some(observer) = direct_observer.as_deref_mut() {
|
||||||
observer(DirectCodexTurnObservation::IntermediateText(text));
|
observer(DirectCodexTurnObservation::IntermediateText(text));
|
||||||
@@ -3073,7 +3040,6 @@ impl CodexAppServerConnection {
|
|||||||
"rawResponseItem/completed 缺少 item".to_string(),
|
"rawResponseItem/completed 缺少 item".to_string(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let entry_item = direct_thread_event_item(history_root, &item);
|
|
||||||
let history_root = history_root.to_path_buf();
|
let history_root = history_root.to_path_buf();
|
||||||
let history_item = item.clone();
|
let history_item = item.clone();
|
||||||
tokio::task::spawn_blocking(move || {
|
tokio::task::spawn_blocking(move || {
|
||||||
@@ -3087,15 +3053,19 @@ impl CodexAppServerConnection {
|
|||||||
})?
|
})?
|
||||||
.map_err(platform_llm::LlmError::InvalidRequest)?;
|
.map_err(platform_llm::LlmError::InvalidRequest)?;
|
||||||
direct_project_history.complete_item(&item);
|
direct_project_history.complete_item(&item);
|
||||||
if let Some(entry_item) = entry_item {
|
let item_id = direct_thread_item_id(&item);
|
||||||
append_direct_thread_event(
|
append_direct_thread_event(
|
||||||
&direct_thread_id,
|
&direct_thread_id,
|
||||||
DirectThreadEvent::item_completed(entry_item),
|
DirectThreadRawEventDraft {
|
||||||
);
|
event_type: "item.completed".to_string(),
|
||||||
}
|
turn_id: turn_id.clone(),
|
||||||
|
item_id,
|
||||||
|
payload: serde_json::json!({}),
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(CodexTurnEvent::Request { kind, params }) => {
|
Some(CodexTurnEvent::Request { event_type, params }) => {
|
||||||
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
if self.inner.workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||||
let request_id = params
|
let request_id = params
|
||||||
.get("requestId")
|
.get("requestId")
|
||||||
@@ -3105,7 +3075,14 @@ impl CodexAppServerConnection {
|
|||||||
.map(str::to_string);
|
.map(str::to_string);
|
||||||
append_direct_thread_event(
|
append_direct_thread_event(
|
||||||
&direct_thread_id,
|
&direct_thread_id,
|
||||||
DirectThreadEvent::request(kind, request_id),
|
DirectThreadRawEventDraft {
|
||||||
|
event_type: event_type.to_string(),
|
||||||
|
turn_id: turn_id.clone(),
|
||||||
|
item_id: None,
|
||||||
|
payload: request_id
|
||||||
|
.map(|id| serde_json::json!({ "requestId": id }))
|
||||||
|
.unwrap_or_else(|| serde_json::json!({})),
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3216,14 +3193,16 @@ impl CodexAppServerConnection {
|
|||||||
&& self.inner.workspace_mode
|
&& self.inner.workspace_mode
|
||||||
== CodexAppServerWorkspaceMode::DirectProject
|
== CodexAppServerWorkspaceMode::DirectProject
|
||||||
{
|
{
|
||||||
if let Some(entry_item) =
|
let item_id = direct_thread_item_id(item);
|
||||||
direct_thread_event_item(history_root, item)
|
append_direct_thread_event(
|
||||||
{
|
&direct_thread_id,
|
||||||
append_direct_thread_event(
|
DirectThreadRawEventDraft {
|
||||||
&direct_thread_id,
|
event_type: "item.started".to_string(),
|
||||||
DirectThreadEvent::item_started(entry_item),
|
turn_id: turn_id.clone(),
|
||||||
);
|
item_id,
|
||||||
}
|
payload: direct_thread_item_started_payload(item),
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3265,7 +3244,12 @@ impl CodexAppServerConnection {
|
|||||||
{
|
{
|
||||||
append_direct_thread_event(
|
append_direct_thread_event(
|
||||||
&direct_thread_id,
|
&direct_thread_id,
|
||||||
DirectThreadEvent::turn_completed(status.to_string()),
|
DirectThreadRawEventDraft {
|
||||||
|
event_type: "turn.completed".to_string(),
|
||||||
|
turn_id: turn_id.clone(),
|
||||||
|
item_id: None,
|
||||||
|
payload: serde_json::json!({ "status": status }),
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
match status {
|
match status {
|
||||||
@@ -3960,8 +3944,8 @@ async fn read_game_creator_codex_app_server_stdout(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let event = if let Some(kind) = direct_codex_resolution_event_type(method) {
|
let event = if let Some(event_type) = direct_codex_resolution_event_type(method) {
|
||||||
CodexTurnEvent::Request { kind, params }
|
CodexTurnEvent::Request { event_type, params }
|
||||||
} else if let Some(activity) = safe_activity {
|
} else if let Some(activity) = safe_activity {
|
||||||
// Preparing notifications may carry private plan/reasoning text;
|
// Preparing notifications may carry private plan/reasoning text;
|
||||||
// expose only the safe activity category. Other categories may
|
// expose only the safe activity category. Other categories may
|
||||||
@@ -4013,8 +3997,8 @@ async fn read_game_creator_codex_app_server_stdout(
|
|||||||
),
|
),
|
||||||
method if direct_codex_request_event_type(method).is_some() => {
|
method if direct_codex_request_event_type(method).is_some() => {
|
||||||
CodexTurnEvent::Request {
|
CodexTurnEvent::Request {
|
||||||
kind: direct_codex_request_event_type(method)
|
event_type: direct_codex_request_event_type(method)
|
||||||
.expect("request kind checked above"),
|
.expect("request event type checked above"),
|
||||||
params,
|
params,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4525,29 +4509,11 @@ mod tests {
|
|||||||
"arguments": { "path": "game/index.html", "token": "secret" },
|
"arguments": { "path": "game/index.html", "token": "secret" },
|
||||||
"result": { "content": "large output" }
|
"result": { "content": "large output" }
|
||||||
});
|
});
|
||||||
// 运行态事件必须自足:载荷是脱敏原始条目,前端不需要再按 itemId 取快照。
|
assert_eq!(direct_thread_item_id(&item).as_deref(), Some("item-1"));
|
||||||
let projected = direct_thread_event_item(std::path::Path::new("."), &item).expect("item");
|
|
||||||
assert_eq!(projected.item_id(), "item-1");
|
|
||||||
let payload = serde_json::to_value(&projected).expect("payload");
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
payload.get("itemType").and_then(serde_json::Value::as_str),
|
direct_thread_item_started_payload(&item),
|
||||||
Some("mcpToolCall")
|
serde_json::json!({ "itemType": "mcpToolCall" })
|
||||||
);
|
);
|
||||||
assert_eq!(
|
|
||||||
payload.get("itemId").and_then(serde_json::Value::as_str),
|
|
||||||
Some("item-1")
|
|
||||||
);
|
|
||||||
// 卡片标题 / 折叠摘要 / kind 属于前端投影:载荷里不得出现这些 UI 语义。
|
|
||||||
assert!(payload.get("toolCall").is_none(), "{payload}");
|
|
||||||
assert!(payload.get("title").is_none(), "{payload}");
|
|
||||||
assert!(payload.get("summary").is_none(), "{payload}");
|
|
||||||
assert!(payload.get("kind").is_none(), "{payload}");
|
|
||||||
// 参数里的密钥不得随载荷下发(脱敏占位符可以保留,明文不行)。
|
|
||||||
let arguments = payload
|
|
||||||
.get("arguments")
|
|
||||||
.and_then(serde_json::Value::as_str)
|
|
||||||
.unwrap_or_default();
|
|
||||||
assert!(!arguments.contains("\"secret\""), "{payload}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -5,8 +5,9 @@ mod validation;
|
|||||||
mod wire;
|
mod wire;
|
||||||
|
|
||||||
pub(crate) use model::{
|
pub(crate) use model::{
|
||||||
DirectCodexUserContentPart, DirectCodexUserItem, DirectCodexUserMessageEnvelope,
|
DirectCodexUserAttachmentReferencePart, DirectCodexUserContentPart, DirectCodexUserItem,
|
||||||
DirectCodexUserMessageItem, DirectCodexUserRole, DirectCodexUserRuntimeRegionPart,
|
DirectCodexUserMessageEnvelope, DirectCodexUserMessageItem, DirectCodexUserRole,
|
||||||
|
DirectCodexUserRuntimeRegionPart,
|
||||||
};
|
};
|
||||||
pub(crate) use validation::validate_direct_codex_user_item;
|
pub(crate) use validation::validate_direct_codex_user_item;
|
||||||
pub(crate) use wire::{
|
pub(crate) use wire::{
|
||||||
|
|||||||
@@ -36,6 +36,21 @@ pub(crate) enum DirectCodexUserContentPart {
|
|||||||
AgcResourceReference { resource_id: String },
|
AgcResourceReference { resource_id: String },
|
||||||
#[serde(rename = "agc_runtime_region_reference")]
|
#[serde(rename = "agc_runtime_region_reference")]
|
||||||
AgcRuntimeRegionReference(DirectCodexUserRuntimeRegionPart),
|
AgcRuntimeRegionReference(DirectCodexUserRuntimeRegionPart),
|
||||||
|
/// Uploaded project attachment kept inline in canonical content.
|
||||||
|
#[serde(rename = "agc_attachment_reference")]
|
||||||
|
AgcAttachmentReference(DirectCodexUserAttachmentReferencePart),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/features/project-workspace/generated/"))]
|
||||||
|
pub(crate) struct DirectCodexUserAttachmentReferencePart {
|
||||||
|
pub(crate) name: String,
|
||||||
|
pub(crate) media_type: String,
|
||||||
|
#[ts(type = "number")]
|
||||||
|
pub(crate) size: u64,
|
||||||
|
pub(crate) local_path: String,
|
||||||
|
pub(crate) status: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
|
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
|
||||||
|
|||||||
@@ -40,6 +40,18 @@ pub(crate) fn validate_direct_codex_user_item(
|
|||||||
reference_count = reference_count.saturating_add(1);
|
reference_count = reference_count.saturating_add(1);
|
||||||
validate_runtime_region_reference(&manifest, reference)?;
|
validate_runtime_region_reference(&manifest, reference)?;
|
||||||
}
|
}
|
||||||
|
DirectCodexUserContentPart::AgcAttachmentReference(reference) => {
|
||||||
|
if reference.name.trim().is_empty() {
|
||||||
|
return Err("附件缺少文件名".to_string());
|
||||||
|
}
|
||||||
|
if !reference.local_path.trim().is_empty() {
|
||||||
|
sanitize_attachment_local_path(&reference.local_path)
|
||||||
|
.ok_or_else(|| "附件项目路径无效".to_string())?;
|
||||||
|
}
|
||||||
|
if !matches!(reference.status.trim(), "imported" | "failed") {
|
||||||
|
return Err("附件状态无效".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if reference_count > MAX_DIRECT_CODEX_REFERENCES {
|
if reference_count > MAX_DIRECT_CODEX_REFERENCES {
|
||||||
|
|||||||
@@ -100,6 +100,20 @@ pub(crate) fn direct_codex_user_item_to_wire_input(
|
|||||||
summary.push(']');
|
summary.push(']');
|
||||||
summary
|
summary
|
||||||
}
|
}
|
||||||
|
DirectCodexUserContentPart::AgcAttachmentReference(reference) => {
|
||||||
|
let mut summary = format!(
|
||||||
|
"[附件:名称={};类型={};大小={} 字节",
|
||||||
|
reference.name.trim(),
|
||||||
|
reference.media_type.trim(),
|
||||||
|
reference.size
|
||||||
|
);
|
||||||
|
if !reference.local_path.trim().is_empty() {
|
||||||
|
summary.push_str(&format!(";项目路径={}", reference.local_path.trim()));
|
||||||
|
}
|
||||||
|
summary.push_str(&format!(";状态={}", reference.status.trim()));
|
||||||
|
summary.push(']');
|
||||||
|
summary
|
||||||
|
}
|
||||||
};
|
};
|
||||||
input.push(serde_json::json!({ "type": "text", "text": text }));
|
input.push(serde_json::json!({ "type": "text", "text": text }));
|
||||||
}
|
}
|
||||||
@@ -174,4 +188,26 @@ mod tests {
|
|||||||
.expect_err("history item without type must fail");
|
.expect_err("history item without type must fail");
|
||||||
assert!(error.contains("缺少 type"), "{error}");
|
assert!(error.contains("缺少 type"), "{error}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn attachment_parts_remain_in_canonical_order_when_projected() {
|
||||||
|
let root = tempfile::tempdir().expect("temp project");
|
||||||
|
crate::init_local_game_project_at(root.path(), "wire-test", "wire 投影测试")
|
||||||
|
.expect("init project");
|
||||||
|
let item = json!({
|
||||||
|
"type": "message",
|
||||||
|
"role": "user",
|
||||||
|
"id": "turn-1:user",
|
||||||
|
"content": [
|
||||||
|
{"type": "input_text", "text": "先看"},
|
||||||
|
{"type": "agc_attachment_reference", "name": "notes.txt", "mediaType": "text/plain", "size": 4, "localPath": "assets/notes.txt", "status": "imported"}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
let projected = direct_codex_user_item_to_response_item(root.path(), &item)
|
||||||
|
.expect("user response item should project");
|
||||||
|
let content = projected["content"].as_array().expect("content array");
|
||||||
|
assert_eq!(content.len(), 2);
|
||||||
|
assert!(content[0]["text"].as_str().unwrap().contains("先看"));
|
||||||
|
assert!(content[1]["text"].as_str().unwrap().contains("notes.txt"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,10 +31,9 @@ pub(crate) fn normalize_direct_client_turn_id(
|
|||||||
pub(crate) async fn chat_with_game_creator_direct_codex(
|
pub(crate) async fn chat_with_game_creator_direct_codex(
|
||||||
project_path: String,
|
project_path: String,
|
||||||
prompt: String,
|
prompt: String,
|
||||||
mut user_item: DirectCodexUserItem,
|
user_item: DirectCodexUserItem,
|
||||||
creation_type: Option<String>,
|
creation_type: Option<String>,
|
||||||
client_turn_id: Option<String>,
|
client_turn_id: Option<String>,
|
||||||
attachments: Option<Vec<DirectCodexTurnAttachment>>,
|
|
||||||
) -> Result<String, String> {
|
) -> Result<String, String> {
|
||||||
let root = Path::new(project_path.trim());
|
let root = Path::new(project_path.trim());
|
||||||
let turn_id = normalize_direct_client_turn_id(client_turn_id.as_deref())?;
|
let turn_id = normalize_direct_client_turn_id(client_turn_id.as_deref())?;
|
||||||
@@ -43,24 +42,7 @@ pub(crate) async fn chat_with_game_creator_direct_codex(
|
|||||||
redact_agent_runtime_error(root, &format!("恢复上一轮陶泥儿整包事务失败:{error}"), 500)
|
redact_agent_runtime_error(root, &format!("恢复上一轮陶泥儿整包事务失败:{error}"), 500)
|
||||||
})?;
|
})?;
|
||||||
let turn_emitter = DirectGameCreatorTurnUpdateEmitter::new(root, turn_id.clone());
|
let turn_emitter = DirectGameCreatorTurnUpdateEmitter::new(root, turn_id.clone());
|
||||||
let mut audit = DirectCodexTurnAudit::start(
|
let mut audit = DirectCodexTurnAudit::start(root, &turn_id, &prompt, &[]);
|
||||||
root,
|
|
||||||
&turn_id,
|
|
||||||
&prompt,
|
|
||||||
attachments.as_deref().unwrap_or_default(),
|
|
||||||
);
|
|
||||||
let attachments = attachments.unwrap_or_default();
|
|
||||||
if !attachments.is_empty() {
|
|
||||||
let attachment_context =
|
|
||||||
render_direct_codex_user_prompt("", &attachments).map_err(|error| {
|
|
||||||
audit.finish(false);
|
|
||||||
error
|
|
||||||
})?;
|
|
||||||
let DirectCodexUserItem::Message(message) = &mut user_item;
|
|
||||||
message.content.push(DirectCodexUserContentPart::InputText {
|
|
||||||
text: attachment_context,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
validate_direct_codex_user_item(root, &user_item).map_err(|error| {
|
validate_direct_codex_user_item(root, &user_item).map_err(|error| {
|
||||||
audit.finish(false);
|
audit.finish(false);
|
||||||
error
|
error
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -8,9 +8,11 @@
|
|||||||
//! 为什么不复用 `project.jsonl`:那条链路的回读只投影 `role ∈ {user, assistant}` 的
|
//! 为什么不复用 `project.jsonl`:那条链路的回读只投影 `role ∈ {user, assistant}` 的
|
||||||
//! 文本条目,而且会被注入 Codex 上下文。往里面塞新形状既装不下,又有污染模型上下文的风险。
|
//! 文本条目,而且会被注入 Codex 上下文。往里面塞新形状既装不下,又有污染模型上下文的风险。
|
||||||
|
|
||||||
use super::direct_thread_wire::sanitize_detail_text;
|
use crate::agent::redact_secret_tokens;
|
||||||
|
use crate::agent::sanitize_error_context;
|
||||||
use crate::config::{prepare_game_creator_private_path_for_read, write_game_creator_private_file};
|
use crate::config::{prepare_game_creator_private_path_for_read, write_game_creator_private_file};
|
||||||
use crate::project::{enforce_project_permission_policy, project_append_lock_for};
|
use crate::project::{enforce_project_permission_policy, project_append_lock_for};
|
||||||
|
use crate::redact_absolute_path_tokens;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
@@ -84,6 +86,134 @@ fn tool_calls_path(root: &Path) -> PathBuf {
|
|||||||
root.join(".agent/conversations/tool-calls.jsonl")
|
root.join(".agent/conversations/tool-calls.jsonl")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 项目根目录之后的路径 token:分隔符统一成 `/`,返回 `(消费到的下标, 项目相对路径)`。
|
||||||
|
fn project_relative_path_segment(value: &str, start: usize) -> (usize, String) {
|
||||||
|
let mut index = start;
|
||||||
|
let mut relative = String::new();
|
||||||
|
while index < value.len() {
|
||||||
|
let character = value[index..].chars().next().unwrap_or_default();
|
||||||
|
if matches!(character, '/' | '\\') {
|
||||||
|
if !relative.is_empty() {
|
||||||
|
relative.push('/');
|
||||||
|
}
|
||||||
|
index += character.len_utf8();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if character.is_whitespace()
|
||||||
|
|| matches!(
|
||||||
|
character,
|
||||||
|
'\'' | '"'
|
||||||
|
| '`'
|
||||||
|
| ','
|
||||||
|
| ';'
|
||||||
|
| '|'
|
||||||
|
| '&'
|
||||||
|
| '('
|
||||||
|
| ')'
|
||||||
|
| '['
|
||||||
|
| ']'
|
||||||
|
| '{'
|
||||||
|
| '}'
|
||||||
|
| '<'
|
||||||
|
| '>'
|
||||||
|
| ':'
|
||||||
|
)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
relative.push(character);
|
||||||
|
index += character.len_utf8();
|
||||||
|
}
|
||||||
|
while relative.ends_with('/') {
|
||||||
|
relative.pop();
|
||||||
|
}
|
||||||
|
(index, relative)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 把项目根目录前缀换成**项目相对路径**(`<root>/game/src/x.ts` → `game/src/x.ts`)。
|
||||||
|
///
|
||||||
|
/// 必须排在 `redact_absolute_path_tokens` 之前:后者会把整个绝对路径抹成
|
||||||
|
/// `<absolute-path>`,之后就再也认不出哪些路径在项目内了。
|
||||||
|
/// Windows 上同时匹配 `\` 与 `/` 两种分隔符写法,并按大小写不敏感比较(盘符大小写会变)。
|
||||||
|
fn relativize_project_root_paths(root: &Path, value: &str) -> String {
|
||||||
|
let root_text = root.to_string_lossy();
|
||||||
|
let root_text = root_text.trim_end_matches(['/', '\\']);
|
||||||
|
if root_text.is_empty() {
|
||||||
|
return value.to_string();
|
||||||
|
}
|
||||||
|
let mut needles = [
|
||||||
|
root_text.to_string(),
|
||||||
|
root_text.replace('\\', "/"),
|
||||||
|
root_text.replace('/', "\\"),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|needle| needle.to_ascii_lowercase())
|
||||||
|
.filter(|needle| !needle.is_empty())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
needles.sort();
|
||||||
|
needles.dedup();
|
||||||
|
let lower = value.to_ascii_lowercase();
|
||||||
|
|
||||||
|
let mut output = String::with_capacity(value.len());
|
||||||
|
let mut cursor = 0usize;
|
||||||
|
while cursor < value.len() {
|
||||||
|
let mut hit: Option<(usize, usize)> = None;
|
||||||
|
for needle in &needles {
|
||||||
|
let mut search = cursor;
|
||||||
|
while let Some(relative) = lower[search..].find(needle.as_str()) {
|
||||||
|
let start = search + relative;
|
||||||
|
let end = start + needle.len();
|
||||||
|
let left_is_boundary = start == 0
|
||||||
|
|| lower[..start].chars().next_back().is_some_and(|character| {
|
||||||
|
!character.is_alphanumeric() && character != '_' && character != '-'
|
||||||
|
});
|
||||||
|
if left_is_boundary && value[end..].starts_with(['/', '\\']) {
|
||||||
|
if hit.is_none_or(|(best_start, _)| start < best_start) {
|
||||||
|
hit = Some((start, end));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
search = end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some((start, end)) = hit else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
output.push_str(&value[cursor..start]);
|
||||||
|
let (consumed, relative) = project_relative_path_segment(value, end);
|
||||||
|
if relative.is_empty() {
|
||||||
|
// 只写了项目根目录本身(没有后续路径段):按占位形状处理。
|
||||||
|
output.push_str("<absolute-path>");
|
||||||
|
} else {
|
||||||
|
output.push_str(&relative);
|
||||||
|
}
|
||||||
|
cursor = consumed;
|
||||||
|
}
|
||||||
|
output.push_str(&value[cursor..]);
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 脱敏:项目内绝对路径先归一化成项目相对路径,再依次做绝对路径、密钥前缀与
|
||||||
|
/// 错误上下文脱敏。
|
||||||
|
///
|
||||||
|
/// 顺序不能反:先抹密钥会把 `sk-…` 之类的 token 换成占位符,但绝对路径里的用户名目录
|
||||||
|
/// 仍然会留下;这里先归一化路径 token,再处理密钥。
|
||||||
|
///
|
||||||
|
/// 复用既有 `agent/generation/prompt_context.rs` 的脱敏组合:`sanitize_error_context`
|
||||||
|
/// 就是 `redact_secret_tokens` + `redact_error_sensitive_assignments` +
|
||||||
|
/// `redact_error_bearer_values` + `redact_error_config_names` 的既有组合用法,覆盖
|
||||||
|
/// `Authorization: Bearer …`、`Cookie: …`、`api_key=…`、`client_secret=…` 这类键值凭据;
|
||||||
|
/// 含 `--password` / `--token` / `--secret` 这类敏感 CLI 标志的行按既有 fail-closed
|
||||||
|
/// 约定整行替换成 `[redacted sensitive context]`(与 `sanitize_agent_runtime_text` 一致)。
|
||||||
|
///
|
||||||
|
/// `pub(crate)`:回合流(`direct_turn_stream`)的文本段复用同一套脱敏,避免两处口径分叉。
|
||||||
|
pub(crate) fn sanitize_detail_text(root: &Path, value: &str) -> String {
|
||||||
|
let without_project_root = relativize_project_root_paths(root, value);
|
||||||
|
let without_absolute = redact_absolute_path_tokens(&without_project_root);
|
||||||
|
let without_secret = redact_secret_tokens(&without_absolute);
|
||||||
|
sanitize_error_context(&without_secret)
|
||||||
|
}
|
||||||
|
|
||||||
/// 按字符数截断(不切坏 UTF-8),并在真正截断时补省略号。
|
/// 按字符数截断(不切坏 UTF-8),并在真正截断时补省略号。
|
||||||
fn bounded_chars(value: &str, max_chars: usize) -> String {
|
fn bounded_chars(value: &str, max_chars: usize) -> String {
|
||||||
if value.chars().count() <= max_chars {
|
if value.chars().count() <= max_chars {
|
||||||
|
|||||||
@@ -5383,21 +5383,10 @@ pub(crate) async fn read_direct_project_history_slice(
|
|||||||
before_item_id.as_deref(),
|
before_item_id.as_deref(),
|
||||||
limit.unwrap_or(20),
|
limit.unwrap_or(20),
|
||||||
)?;
|
)?;
|
||||||
let first_item_id = items
|
|
||||||
.first()
|
|
||||||
.and_then(|item| item.get("id"))
|
|
||||||
.and_then(serde_json::Value::as_str)
|
|
||||||
.map(str::to_string);
|
|
||||||
let items = direct_thread_items_from_history(root, &items, |item| {
|
|
||||||
item.get("id")
|
|
||||||
.and_then(serde_json::Value::as_str)
|
|
||||||
.and_then(|id| item_timestamps.get(id).copied())
|
|
||||||
.unwrap_or_default()
|
|
||||||
});
|
|
||||||
Ok(DirectThreadHistorySlice {
|
Ok(DirectThreadHistorySlice {
|
||||||
items,
|
items,
|
||||||
has_more,
|
has_more,
|
||||||
first_item_id,
|
item_timestamps,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,102 @@
|
|||||||
|
import { LexicalComposer } from '@lexical/react/LexicalComposer';
|
||||||
|
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
|
||||||
|
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
|
||||||
|
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
|
||||||
|
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
|
||||||
|
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
|
||||||
|
import {
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
type EditorState,
|
||||||
|
KEY_ENTER_COMMAND,
|
||||||
|
type Klass,
|
||||||
|
type LexicalNode,
|
||||||
|
} from 'lexical';
|
||||||
|
import type { ReactElement, ReactNode, Ref } from 'react';
|
||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
type RichTextInputProps = {
|
||||||
|
namespace: string;
|
||||||
|
nodes: Klass<LexicalNode>[];
|
||||||
|
initialEditorState?: EditorState | null;
|
||||||
|
contentEditable?: ReactElement<typeof ContentEditable>;
|
||||||
|
placeholder?: ReactElement;
|
||||||
|
containerClassName?: string;
|
||||||
|
containerRef?: Ref<HTMLDivElement>;
|
||||||
|
disabled?: boolean;
|
||||||
|
onChange?: (editorState: EditorState) => void;
|
||||||
|
onEnter?: () => void;
|
||||||
|
children?: ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
function SubmitOnEnter({ onEnter }: { onEnter?: () => void }) {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!onEnter) return undefined;
|
||||||
|
return editor.registerCommand(
|
||||||
|
KEY_ENTER_COMMAND,
|
||||||
|
(event) => {
|
||||||
|
if (!event || event.shiftKey || event.isComposing) return false;
|
||||||
|
event.preventDefault();
|
||||||
|
onEnter();
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
COMMAND_PRIORITY_HIGH,
|
||||||
|
);
|
||||||
|
}, [editor, onEnter]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SetEditorEditable({ disabled }: { disabled: boolean }) {
|
||||||
|
const [editor] = useLexicalComposerContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
editor.setEditable(!disabled);
|
||||||
|
}, [disabled, editor]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function RichTextInput({
|
||||||
|
namespace,
|
||||||
|
nodes,
|
||||||
|
initialEditorState,
|
||||||
|
contentEditable = <ContentEditable />,
|
||||||
|
placeholder,
|
||||||
|
containerClassName,
|
||||||
|
containerRef,
|
||||||
|
disabled = false,
|
||||||
|
onChange,
|
||||||
|
onEnter,
|
||||||
|
children,
|
||||||
|
}: RichTextInputProps) {
|
||||||
|
return (
|
||||||
|
<LexicalComposer
|
||||||
|
initialConfig={{
|
||||||
|
namespace,
|
||||||
|
nodes,
|
||||||
|
editorState: initialEditorState ?? undefined,
|
||||||
|
onError: (error) => {
|
||||||
|
throw error;
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
className={containerClassName}
|
||||||
|
data-disabled={disabled ? 'true' : undefined}
|
||||||
|
>
|
||||||
|
<RichTextPlugin
|
||||||
|
contentEditable={contentEditable}
|
||||||
|
placeholder={placeholder}
|
||||||
|
ErrorBoundary={LexicalErrorBoundary}
|
||||||
|
/>
|
||||||
|
{children}
|
||||||
|
<SetEditorEditable disabled={disabled} />
|
||||||
|
<SubmitOnEnter onEnter={onEnter} />
|
||||||
|
{onChange ? <OnChangePlugin onChange={onChange} /> : null}
|
||||||
|
</div>
|
||||||
|
</LexicalComposer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -79,7 +79,7 @@ import {
|
|||||||
ResourceReferenceInput,
|
ResourceReferenceInput,
|
||||||
type ResourceReferenceInputHandle,
|
type ResourceReferenceInputHandle,
|
||||||
} from './ResourceReferenceInput';
|
} from './ResourceReferenceInput';
|
||||||
import type { ChatComposerDraft, ChatReference } from './resourceReferences';
|
import type { ChatComposerDraft } from './resourceReferences';
|
||||||
import { ToolCallGroup } from './ToolCallGroup';
|
import { ToolCallGroup } from './ToolCallGroup';
|
||||||
import {
|
import {
|
||||||
formatClockTime,
|
formatClockTime,
|
||||||
@@ -242,8 +242,6 @@ type ProjectSupervisorViewProps = RuntimePanelProps & {
|
|||||||
attachments?: DirectCodexTurnAttachment[];
|
attachments?: DirectCodexTurnAttachment[];
|
||||||
/** 上传/校验附件的提示文案(失败与成功都用它,空串不渲染)。 */
|
/** 上传/校验附件的提示文案(失败与成功都用它,空串不渲染)。 */
|
||||||
attachmentNotice?: string;
|
attachmentNotice?: string;
|
||||||
chatInput: string;
|
|
||||||
chatReferences: ChatReference[];
|
|
||||||
chatProjectAssets: import('../../../../../packages/shared/src/contracts/gameCreationApp').GameCreationAppAssetManifestEntry[];
|
chatProjectAssets: import('../../../../../packages/shared/src/contracts/gameCreationApp').GameCreationAppAssetManifestEntry[];
|
||||||
composerRef?: RefObject<ResourceReferenceInputHandle | null>;
|
composerRef?: RefObject<ResourceReferenceInputHandle | null>;
|
||||||
directCodex?: boolean;
|
directCodex?: boolean;
|
||||||
@@ -327,8 +325,6 @@ export function ProjectSupervisorView({
|
|||||||
activeVersionId = null,
|
activeVersionId = null,
|
||||||
attachments = [],
|
attachments = [],
|
||||||
attachmentNotice = '',
|
attachmentNotice = '',
|
||||||
chatInput,
|
|
||||||
chatReferences,
|
|
||||||
chatProjectAssets,
|
chatProjectAssets,
|
||||||
composerRef,
|
composerRef,
|
||||||
directCodex = false,
|
directCodex = false,
|
||||||
@@ -916,8 +912,6 @@ export function ProjectSupervisorView({
|
|||||||
Boolean(designView?.session.pendingClarification)
|
Boolean(designView?.session.pendingClarification)
|
||||||
}
|
}
|
||||||
rows={3}
|
rows={3}
|
||||||
value={chatInput}
|
|
||||||
references={chatReferences}
|
|
||||||
showTriggerButton={!directCodex}
|
showTriggerButton={!directCodex}
|
||||||
placeholder={
|
placeholder={
|
||||||
directCodex
|
directCodex
|
||||||
|
|||||||
+1
-7
@@ -55,7 +55,7 @@ import {
|
|||||||
ResourceReferenceInput,
|
ResourceReferenceInput,
|
||||||
type ResourceReferenceInputHandle,
|
type ResourceReferenceInputHandle,
|
||||||
} from './ResourceReferenceInput';
|
} from './ResourceReferenceInput';
|
||||||
import type { ChatComposerDraft, ChatReference } from './resourceReferences';
|
import type { ChatComposerDraft } from './resourceReferences';
|
||||||
|
|
||||||
type ProjectWorkspaceChatPaneProps = {
|
type ProjectWorkspaceChatPaneProps = {
|
||||||
activeVersionId?: string | null;
|
activeVersionId?: string | null;
|
||||||
@@ -65,8 +65,6 @@ type ProjectWorkspaceChatPaneProps = {
|
|||||||
cancelProjectCreateInNonEmptyFolder: () => void;
|
cancelProjectCreateInNonEmptyFolder: () => void;
|
||||||
cancelUiCommandConfirmation: () => void;
|
cancelUiCommandConfirmation: () => void;
|
||||||
chatAgentBusy: boolean;
|
chatAgentBusy: boolean;
|
||||||
chatInput: string;
|
|
||||||
chatReferences: ChatReference[];
|
|
||||||
chatProjectAssets: GameCreationAppAssetManifestEntry[];
|
chatProjectAssets: GameCreationAppAssetManifestEntry[];
|
||||||
composerRef?: Ref<ResourceReferenceInputHandle>;
|
composerRef?: Ref<ResourceReferenceInputHandle>;
|
||||||
chatInputRef: RefObject<HTMLDivElement | null>;
|
chatInputRef: RefObject<HTMLDivElement | null>;
|
||||||
@@ -215,8 +213,6 @@ export function ProjectWorkspaceChatPane({
|
|||||||
cancelProjectCreateInNonEmptyFolder,
|
cancelProjectCreateInNonEmptyFolder,
|
||||||
cancelUiCommandConfirmation,
|
cancelUiCommandConfirmation,
|
||||||
chatAgentBusy,
|
chatAgentBusy,
|
||||||
chatInput,
|
|
||||||
chatReferences,
|
|
||||||
chatProjectAssets,
|
chatProjectAssets,
|
||||||
composerRef,
|
composerRef,
|
||||||
chatInputRef,
|
chatInputRef,
|
||||||
@@ -962,8 +958,6 @@ export function ProjectWorkspaceChatPane({
|
|||||||
projectPath={projectPath}
|
projectPath={projectPath}
|
||||||
disabled={chatAgentBusy || projectSupervisorNeedsUserInput}
|
disabled={chatAgentBusy || projectSupervisorNeedsUserInput}
|
||||||
multiline={false}
|
multiline={false}
|
||||||
value={chatInput}
|
|
||||||
references={chatReferences}
|
|
||||||
placeholder="例如:像素风横版动作小游戏,或输入 @ 选择资源"
|
placeholder="例如:像素风横版动作小游戏,或输入 @ 选择资源"
|
||||||
onChange={onChatComposerChange}
|
onChange={onChatComposerChange}
|
||||||
/>
|
/>
|
||||||
|
|||||||
+210
-150
File diff suppressed because it is too large
Load Diff
+1
-7
@@ -33,7 +33,7 @@ import {
|
|||||||
ResourceReferenceInput,
|
ResourceReferenceInput,
|
||||||
type ResourceReferenceInputHandle,
|
type ResourceReferenceInputHandle,
|
||||||
} from './ResourceReferenceInput';
|
} from './ResourceReferenceInput';
|
||||||
import type { ChatComposerDraft, ChatReference } from './resourceReferences';
|
import type { ChatComposerDraft } from './resourceReferences';
|
||||||
|
|
||||||
type RuntimeControlProps = ComponentProps<
|
type RuntimeControlProps = ComponentProps<
|
||||||
typeof ProjectSupervisorRuntimeControls
|
typeof ProjectSupervisorRuntimeControls
|
||||||
@@ -44,8 +44,6 @@ const CHAT_SCROLL_BOTTOM_THRESHOLD = 24;
|
|||||||
type SupervisorChatOnlyViewProps = {
|
type SupervisorChatOnlyViewProps = {
|
||||||
activeVersionId?: string | null;
|
activeVersionId?: string | null;
|
||||||
chatAgentBusy: boolean;
|
chatAgentBusy: boolean;
|
||||||
chatInput: string;
|
|
||||||
chatReferences: ChatReference[];
|
|
||||||
chatProjectAssets: import('../../../../../packages/shared/src/contracts/gameCreationApp').GameCreationAppAssetManifestEntry[];
|
chatProjectAssets: import('../../../../../packages/shared/src/contracts/gameCreationApp').GameCreationAppAssetManifestEntry[];
|
||||||
composerRef?: Ref<ResourceReferenceInputHandle>;
|
composerRef?: Ref<ResourceReferenceInputHandle>;
|
||||||
directCodex?: boolean;
|
directCodex?: boolean;
|
||||||
@@ -82,8 +80,6 @@ type SupervisorChatOnlyViewProps = {
|
|||||||
export function SupervisorChatOnlyView({
|
export function SupervisorChatOnlyView({
|
||||||
activeVersionId = null,
|
activeVersionId = null,
|
||||||
chatAgentBusy,
|
chatAgentBusy,
|
||||||
chatInput,
|
|
||||||
chatReferences,
|
|
||||||
chatProjectAssets,
|
chatProjectAssets,
|
||||||
composerRef,
|
composerRef,
|
||||||
directCodex = false,
|
directCodex = false,
|
||||||
@@ -328,8 +324,6 @@ export function SupervisorChatOnlyView({
|
|||||||
projectPath={projectPath}
|
projectPath={projectPath}
|
||||||
disabled={chatAgentBusy || needsUserInput}
|
disabled={chatAgentBusy || needsUserInput}
|
||||||
rows={3}
|
rows={3}
|
||||||
value={chatInput}
|
|
||||||
references={chatReferences}
|
|
||||||
placeholder={
|
placeholder={
|
||||||
directCodex ? '描述你的想法' : '给项目总控 Agent 发消息'
|
directCodex ? '描述你的想法' : '给项目总控 Agent 发消息'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
import { useEffect, useId, useState } from 'react';
|
import { useEffect, useId, useState } from 'react';
|
||||||
|
|
||||||
import { AgentMessageContent } from '../../../../../packages/shared/src/components/AgentMessageContent';
|
import { AgentMessageContent } from '../../../../../packages/shared/src/components/AgentMessageContent';
|
||||||
import type { DirectChatToolCard } from './directThreadChat';
|
import type { GameCreatorDirectToolCall } from '../../app/types';
|
||||||
import {
|
import {
|
||||||
formatToolCallDuration,
|
formatToolCallDuration,
|
||||||
formatTurnDuration,
|
formatTurnDuration,
|
||||||
@@ -38,7 +38,7 @@ export function ToolCallGroup({
|
|||||||
active = false,
|
active = false,
|
||||||
className,
|
className,
|
||||||
}: {
|
}: {
|
||||||
calls: DirectChatToolCard[];
|
calls: GameCreatorDirectToolCall[];
|
||||||
/** 同一回合用户消息的 `updatedAt`;拿不到就传 0,只显示结束时间。 */
|
/** 同一回合用户消息的 `updatedAt`;拿不到就传 0,只显示结束时间。 */
|
||||||
userSentAt?: number | null;
|
userSentAt?: number | null;
|
||||||
/**
|
/**
|
||||||
@@ -169,7 +169,7 @@ function ToolCallRow({
|
|||||||
call,
|
call,
|
||||||
active,
|
active,
|
||||||
}: {
|
}: {
|
||||||
call: DirectChatToolCard;
|
call: GameCreatorDirectToolCall;
|
||||||
active: boolean;
|
active: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [expanded, setExpanded] = useState(false);
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
|||||||
@@ -4,36 +4,32 @@
|
|||||||
* 回合运行中用户再次发送时,消息进入 FIFO 队列而不是被丢弃;当前回合结束后按入队顺序
|
* 回合运行中用户再次发送时,消息进入 FIFO 队列而不是被丢弃;当前回合结束后按入队顺序
|
||||||
* 依次发出。队列项能在输入盒上方单独取消。这里只放与 React 无关的纯逻辑,便于单测。
|
* 依次发出。队列项能在输入盒上方单独取消。这里只放与 React 无关的纯逻辑,便于单测。
|
||||||
*/
|
*/
|
||||||
import type { DirectCodexTurnAttachment } from '../app-shell/directCodexTurnAttachments';
|
import type { DirectCodexUserItem } from './generated';
|
||||||
import type { DirectCodexUserContentPart } from './generated';
|
import { directCodexContentToPromptText } from './resourceReferences';
|
||||||
import type { ChatReference } from './resourceReferences';
|
|
||||||
|
|
||||||
/** 队列上限:满了以后拒绝入队并给出可读提示,而不是静默丢消息。 */
|
/** 队列上限:满了以后拒绝入队并给出可读提示,而不是静默丢消息。 */
|
||||||
export const MAX_QUEUED_CHAT_TURNS = 5;
|
export const MAX_QUEUED_CHAT_TURNS = 5;
|
||||||
|
|
||||||
export type QueuedChatTurn = {
|
export type QueuedChatTurn = {
|
||||||
id: string;
|
id: string;
|
||||||
prompt: string;
|
clientTurnId: string;
|
||||||
attachments: DirectCodexTurnAttachment[];
|
userItem: DirectCodexUserItem;
|
||||||
references: ChatReference[];
|
|
||||||
content?: DirectCodexUserContentPart[];
|
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createQueuedChatTurn(input: {
|
export function createQueuedChatTurn(input: {
|
||||||
id: string;
|
id: string;
|
||||||
prompt: string;
|
clientTurnId: string;
|
||||||
attachments?: readonly DirectCodexTurnAttachment[];
|
userItem: DirectCodexUserItem;
|
||||||
references?: readonly ChatReference[];
|
|
||||||
content?: readonly DirectCodexUserContentPart[];
|
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
}): QueuedChatTurn {
|
}): QueuedChatTurn {
|
||||||
return {
|
return {
|
||||||
id: input.id,
|
id: input.id,
|
||||||
prompt: input.prompt,
|
clientTurnId: input.clientTurnId,
|
||||||
attachments: [...(input.attachments ?? [])],
|
userItem: {
|
||||||
references: [...(input.references ?? [])],
|
...input.userItem,
|
||||||
content: [...(input.content ?? [])],
|
content: [...input.userItem.content],
|
||||||
|
},
|
||||||
createdAt: input.createdAt,
|
createdAt: input.createdAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -79,14 +75,19 @@ export function chatQueueFullNotice(): string {
|
|||||||
|
|
||||||
/** 队列 chip 上显示的文字:单行、有长度上限。 */
|
/** 队列 chip 上显示的文字:单行、有长度上限。 */
|
||||||
export function queuedChatTurnLabel(turn: QueuedChatTurn): string {
|
export function queuedChatTurnLabel(turn: QueuedChatTurn): string {
|
||||||
const text = turn.prompt.trim().replace(/\s+/gu, ' ');
|
const text = directCodexContentToPromptText(turn.userItem.content)
|
||||||
|
.trim()
|
||||||
|
.replace(/\s+/gu, ' ');
|
||||||
if (text) {
|
if (text) {
|
||||||
return text.length > 24 ? `${text.slice(0, 24)}…` : text;
|
return text.length > 24 ? `${text.slice(0, 24)}…` : text;
|
||||||
}
|
}
|
||||||
if (turn.attachments.length > 0) {
|
const attachment = turn.userItem.content.find(
|
||||||
return `附件 · ${turn.attachments[0]?.name ?? '未命名'}`;
|
(part) => part.type === 'agc_attachment_reference',
|
||||||
|
);
|
||||||
|
if (attachment?.type === 'agc_attachment_reference') {
|
||||||
|
return `附件 · ${attachment.name || '未命名'}`;
|
||||||
}
|
}
|
||||||
if (turn.references.length > 0) {
|
if (turn.userItem.content.some((part) => part.type !== 'input_text')) {
|
||||||
return '素材引用';
|
return '素材引用';
|
||||||
}
|
}
|
||||||
return '未命名消息';
|
return '未命名消息';
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { resolveTauriInvoke } from '../../app/tauri';
|
import { resolveTauriInvoke } from '../../app/tauri';
|
||||||
import {
|
import type { DirectCodexUserContentPart } from './generated';
|
||||||
type ChatComposerDraft,
|
|
||||||
chatReferenceListKey,
|
|
||||||
} from './resourceReferences';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 「不再提醒」偏好存本机 localStorage,不进 manifest、不进后端。
|
* 「不再提醒」偏好存本机 localStorage,不进 manifest、不进后端。
|
||||||
@@ -61,8 +58,10 @@ export function writeChatPromptPolishReminderDisabled(disabled: boolean) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 草稿指纹:用于判断「本轮草稿」是否已经被润色或确认过。 */
|
/** 草稿指纹:用于判断「本轮草稿」是否已经被润色或确认过。 */
|
||||||
export function chatPromptDraftKey(draft: ChatComposerDraft) {
|
export function chatPromptDraftKey(
|
||||||
return `${draft.text}\u0000${chatReferenceListKey(draft.references)}`;
|
content: readonly DirectCodexUserContentPart[],
|
||||||
|
) {
|
||||||
|
return JSON.stringify(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -73,25 +72,27 @@ export function chatPromptDraftKey(draft: ChatComposerDraft) {
|
|||||||
* 4. 草稿不是以 `/` 开头的命令 —— 命令走直通路径,不参与提醒。
|
* 4. 草稿不是以 `/` 开头的命令 —— 命令走直通路径,不参与提醒。
|
||||||
*/
|
*/
|
||||||
export function shouldRemindChatPromptPolish({
|
export function shouldRemindChatPromptPolish({
|
||||||
draft,
|
content,
|
||||||
|
prompt,
|
||||||
acknowledgedDraftKey,
|
acknowledgedDraftKey,
|
||||||
reminderDisabled,
|
reminderDisabled,
|
||||||
}: {
|
}: {
|
||||||
draft: ChatComposerDraft;
|
content: readonly DirectCodexUserContentPart[];
|
||||||
|
prompt: string;
|
||||||
acknowledgedDraftKey: string | null;
|
acknowledgedDraftKey: string | null;
|
||||||
reminderDisabled: boolean;
|
reminderDisabled: boolean;
|
||||||
}) {
|
}) {
|
||||||
if (reminderDisabled) {
|
if (reminderDisabled) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const text = draft.text.trim();
|
const text = prompt.trim();
|
||||||
if (text.length < CHAT_PROMPT_POLISH_REMINDER_MIN_TEXT_LENGTH) {
|
if (text.length < CHAT_PROMPT_POLISH_REMINDER_MIN_TEXT_LENGTH) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (text.startsWith('/')) {
|
if (text.startsWith('/')) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return chatPromptDraftKey(draft) !== acknowledgedDraftKey;
|
return chatPromptDraftKey(content) !== acknowledgedDraftKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,271 +0,0 @@
|
|||||||
/**
|
|
||||||
* DirectProject 聊天 reducer:把运行态事件与历史切片归并成同一份聊天条目。
|
|
||||||
*
|
|
||||||
* 事实源只有一个——项目对话历史;运行态事件只负责"当前回合"。顺序 = 历史文件顺序 +
|
|
||||||
* 运行态独有条目。这里不做可见性判断(那是投影的事),也不认任何回合身份:DirectProject
|
|
||||||
* 同一时刻只有一个回合在跑,`turn.started` / `turn.completed` 只切换"是否还在跑"这一个布尔。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { GameCreatorDirectToolCall } from '../../app/types';
|
|
||||||
import type {
|
|
||||||
DirectThreadConsumeResult,
|
|
||||||
DirectThreadEvent,
|
|
||||||
DirectThreadHistorySlice,
|
|
||||||
DirectThreadItem,
|
|
||||||
DirectThreadSubscriptionBootstrap,
|
|
||||||
} from './directThreadEvents';
|
|
||||||
import { projectDirectThreadItem } from './directThreadItemProjection';
|
|
||||||
|
|
||||||
export type DirectChatEntryKind = 'message' | 'reasoning' | 'tool';
|
|
||||||
|
|
||||||
/** 聊天卡片里的工具形状:持久化卡片去掉回合身份(Rust 侧已经不下发 turn id)。 */
|
|
||||||
export type DirectChatToolCard = Omit<GameCreatorDirectToolCall, 'turnId'>;
|
|
||||||
|
|
||||||
/** 聊天视图里的一条条目;运行态事件与历史切片共用的唯一形状。 */
|
|
||||||
export type DirectChatEntry = {
|
|
||||||
itemId: string;
|
|
||||||
kind: DirectChatEntryKind;
|
|
||||||
role?: 'user' | 'assistant' | null;
|
|
||||||
text?: string | null;
|
|
||||||
toolCall?: DirectChatToolCard | null;
|
|
||||||
at?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type DirectThreadChatState = {
|
|
||||||
subscriptionId: string | null;
|
|
||||||
/** 首屏历史锚点:`subscribe` 给出的最后一条完成条目 id。 */
|
|
||||||
lastCompletedItemId: string | null;
|
|
||||||
/** 最新回合是否还在跑;只由生命周期事件的先后决定。 */
|
|
||||||
turnRunning: boolean;
|
|
||||||
/** 历史切片条目,保持文件顺序。 */
|
|
||||||
history: DirectChatEntry[];
|
|
||||||
/** 当前回合的运行态条目,保持到达顺序;回合结束即并入历史并清空。 */
|
|
||||||
live: DirectChatEntry[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export function emptyDirectThreadChatState(): DirectThreadChatState {
|
|
||||||
return {
|
|
||||||
subscriptionId: null,
|
|
||||||
lastCompletedItemId: null,
|
|
||||||
turnRunning: false,
|
|
||||||
history: [],
|
|
||||||
live: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function longerText(
|
|
||||||
left: string | null | undefined,
|
|
||||||
right: string | null | undefined,
|
|
||||||
): string | null {
|
|
||||||
const a = typeof left === 'string' ? left : '';
|
|
||||||
const b = typeof right === 'string' ? right : '';
|
|
||||||
// 正文只增不减:增量往同一段落追加,完成快照可能比累计更长(漏过几条 delta)。
|
|
||||||
return b.length > a.length ? b : a;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeToolStatus(
|
|
||||||
left: DirectChatToolCard['status'] | null | undefined,
|
|
||||||
right: DirectChatToolCard['status'] | null | undefined,
|
|
||||||
): DirectChatToolCard['status'] {
|
|
||||||
// 只有终态才算数:先到的 `running` 允许被后到的完成 / 失败覆盖,反过来不行。
|
|
||||||
if (left === 'running' || !left) return right ?? left ?? 'running';
|
|
||||||
return left;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeToolCard(
|
|
||||||
left: DirectChatToolCard | null,
|
|
||||||
right: DirectChatToolCard | null,
|
|
||||||
): DirectChatToolCard | null {
|
|
||||||
if (!left) return right;
|
|
||||||
if (!right) return left;
|
|
||||||
return {
|
|
||||||
...left,
|
|
||||||
kind: left.kind && left.kind !== 'other' ? left.kind : right.kind,
|
|
||||||
title: left.title?.trim() ? left.title : right.title,
|
|
||||||
summary: left.summary?.trim() ? left.summary : right.summary,
|
|
||||||
status: mergeToolStatus(left.status, right.status),
|
|
||||||
detail: {
|
|
||||||
command: left.detail.command ?? right.detail.command,
|
|
||||||
output: left.detail.output ?? right.detail.output,
|
|
||||||
changes: left.detail.changes?.length
|
|
||||||
? left.detail.changes
|
|
||||||
: right.detail.changes,
|
|
||||||
},
|
|
||||||
startedAt: left.startedAt > 0 ? left.startedAt : right.startedAt,
|
|
||||||
updatedAt: Math.max(left.updatedAt, right.updatedAt),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 先到的快照赢,后到的只补空字段。
|
|
||||||
*
|
|
||||||
* 三个例外只有"后到信息一定更全"时才成立:正文取更长的一份、工具状态允许从 `running`
|
|
||||||
* 升级到终态、`updatedAt` 取较新的时间。其余字段一律先到先用,后到的空值不得抹掉它。
|
|
||||||
*/
|
|
||||||
export function mergeDirectChatEntry(
|
|
||||||
existing: DirectChatEntry,
|
|
||||||
incoming: DirectChatEntry,
|
|
||||||
): DirectChatEntry {
|
|
||||||
return {
|
|
||||||
itemId: existing.itemId || incoming.itemId,
|
|
||||||
kind:
|
|
||||||
existing.kind === 'tool' || incoming.kind === 'tool'
|
|
||||||
? 'tool'
|
|
||||||
: existing.kind,
|
|
||||||
role: existing.role ?? incoming.role ?? null,
|
|
||||||
text: longerText(existing.text, incoming.text),
|
|
||||||
toolCall: mergeToolCard(
|
|
||||||
existing.toolCall ?? null,
|
|
||||||
incoming.toolCall ?? null,
|
|
||||||
),
|
|
||||||
at: existing.at || incoming.at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function upsertLiveEntry(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
entry: DirectChatEntry,
|
|
||||||
): DirectThreadChatState {
|
|
||||||
const index = state.live.findIndex(
|
|
||||||
(existing) => existing.itemId === entry.itemId,
|
|
||||||
);
|
|
||||||
if (index < 0) {
|
|
||||||
return { ...state, live: [...state.live, entry] };
|
|
||||||
}
|
|
||||||
const existing = state.live[index];
|
|
||||||
if (!existing) {
|
|
||||||
return { ...state, live: [...state.live, entry] };
|
|
||||||
}
|
|
||||||
const live = [...state.live];
|
|
||||||
live[index] = mergeDirectChatEntry(existing, entry);
|
|
||||||
return { ...state, live };
|
|
||||||
}
|
|
||||||
|
|
||||||
function appendLiveText(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
event: Extract<DirectThreadEvent, { type: 'item.delta' }>,
|
|
||||||
): DirectThreadChatState {
|
|
||||||
const itemId = event.itemId.trim();
|
|
||||||
if (!itemId || !event.delta) return state;
|
|
||||||
const reasoning = event.kind === 'reasoning';
|
|
||||||
const existing = state.live.find((entry) => entry.itemId === itemId);
|
|
||||||
return upsertLiveEntry(state, {
|
|
||||||
itemId,
|
|
||||||
kind: reasoning ? 'reasoning' : 'message',
|
|
||||||
role: reasoning ? null : 'assistant',
|
|
||||||
text: `${existing?.text ?? ''}${event.delta}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export function reduceDirectThreadEvent(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
event: DirectThreadEvent,
|
|
||||||
): DirectThreadChatState {
|
|
||||||
switch (event.type) {
|
|
||||||
case 'turn.started':
|
|
||||||
return { ...state, turnRunning: true };
|
|
||||||
case 'turn.completed':
|
|
||||||
// 回合结束:条目已经落盘,运行态并入历史后清空,避免同一条目渲染两次。
|
|
||||||
return {
|
|
||||||
...state,
|
|
||||||
turnRunning: false,
|
|
||||||
history: mergeHistoryEntries(state.history, state.live),
|
|
||||||
live: [],
|
|
||||||
};
|
|
||||||
case 'item.delta':
|
|
||||||
return appendLiveText(state, event);
|
|
||||||
case 'item.started':
|
|
||||||
case 'item.completed': {
|
|
||||||
const entry = projectDirectThreadItem(event.item);
|
|
||||||
return entry ? upsertLiveEntry(state, entry) : state;
|
|
||||||
}
|
|
||||||
case 'request':
|
|
||||||
// 审批 / 提问只影响面板交互,不并入聊天条目。
|
|
||||||
return state;
|
|
||||||
default:
|
|
||||||
return state;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function reduceDirectThreadEvents(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
events: readonly DirectThreadEvent[],
|
|
||||||
): DirectThreadChatState {
|
|
||||||
return events.reduce(reduceDirectThreadEvent, state);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* bootstrap 是运行态的唯一权威:游标已在队尾,返回的事件就是此刻要处理的事件。
|
|
||||||
*
|
|
||||||
* 历史窗口保留:bootstrap 不重新回读历史切片,那是 `lastCompletedItemId` 的职责。
|
|
||||||
*/
|
|
||||||
export function resolveDirectThreadBootstrap(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
bootstrap: DirectThreadSubscriptionBootstrap,
|
|
||||||
): DirectThreadChatState {
|
|
||||||
return reduceDirectThreadEvents(
|
|
||||||
{
|
|
||||||
...state,
|
|
||||||
subscriptionId: bootstrap.subscriptionId,
|
|
||||||
lastCompletedItemId: bootstrap.lastCompletedItemId ?? null,
|
|
||||||
},
|
|
||||||
bootstrap.events,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 事件顺序 = 游标顺序;调用方只需要把 `consume` 的结果喂进来。 */
|
|
||||||
export function applyDirectThreadConsumeResult(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
result: DirectThreadConsumeResult,
|
|
||||||
): DirectThreadChatState {
|
|
||||||
return reduceDirectThreadEvents(state, result.events);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 同一身份的条目合并,先到者在前:历史在前、运行态在后,运行态只补空。 */
|
|
||||||
export function mergeHistoryEntries(
|
|
||||||
leading: readonly DirectChatEntry[],
|
|
||||||
trailing: readonly DirectChatEntry[],
|
|
||||||
): DirectChatEntry[] {
|
|
||||||
const byId = new Map<string, number>();
|
|
||||||
const entries: DirectChatEntry[] = [];
|
|
||||||
for (const entry of [...leading, ...trailing]) {
|
|
||||||
const index = byId.get(entry.itemId);
|
|
||||||
if (index === undefined) {
|
|
||||||
byId.set(entry.itemId, entries.length);
|
|
||||||
entries.push(entry);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const existing = entries[index];
|
|
||||||
if (existing) entries[index] = mergeDirectChatEntry(existing, entry);
|
|
||||||
}
|
|
||||||
return entries;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 历史切片并入:切片是脱敏原始条目,投影规则与运行态完全同一份。
|
|
||||||
*
|
|
||||||
* 同一调用的调用与输出在这里按身份合并成一张卡片,而不是在 Rust 侧合并。
|
|
||||||
*/
|
|
||||||
export function mergeDirectHistoryItems(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
items: readonly DirectThreadItem[],
|
|
||||||
): DirectThreadChatState {
|
|
||||||
const entries = items
|
|
||||||
.map((item) => projectDirectThreadItem(item))
|
|
||||||
.filter((entry): entry is DirectChatEntry => Boolean(entry));
|
|
||||||
return { ...state, history: mergeHistoryEntries(entries, state.history) };
|
|
||||||
}
|
|
||||||
|
|
||||||
export function mergeDirectThreadHistorySlice(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
slice: DirectThreadHistorySlice,
|
|
||||||
): DirectThreadChatState {
|
|
||||||
return mergeDirectHistoryItems(state, slice.items);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 聊天投影输入:历史顺序 + 运行态覆盖;运行态独有条目排在最后。 */
|
|
||||||
export function selectDirectChatEntries(
|
|
||||||
state: DirectThreadChatState,
|
|
||||||
): DirectChatEntry[] {
|
|
||||||
return mergeHistoryEntries(state.history, state.live);
|
|
||||||
}
|
|
||||||
@@ -1,45 +1,59 @@
|
|||||||
/**
|
|
||||||
* DirectProject 运行态事件的线上类型。
|
|
||||||
*
|
|
||||||
* 类型由 Rust 侧 ts-rs 导出(改完 Rust 模型后跑 `cargo test export_bindings`),这里只做
|
|
||||||
* 入口转发:前端不再自己抄一份形状,字段增删必须改 Rust。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type { LocalConversationMessageRecord } from '../../app/types';
|
import type { LocalConversationMessageRecord } from '../../app/types';
|
||||||
import type { DirectThreadItem } from './generated';
|
|
||||||
|
|
||||||
export type {
|
export type DirectThreadRawEvent = {
|
||||||
DirectThreadConsumeResult,
|
seq: number;
|
||||||
DirectThreadDeltaKind,
|
type: string;
|
||||||
DirectThreadEvent,
|
turnId: string;
|
||||||
DirectThreadFileChange,
|
itemId?: string;
|
||||||
DirectThreadHistorySlice,
|
payload: Record<string, unknown>;
|
||||||
DirectThreadItem,
|
};
|
||||||
DirectThreadRequestKind,
|
|
||||||
DirectThreadSubscriptionBootstrap,
|
export type DirectThreadSubscriptionBootstrap = {
|
||||||
} from './generated';
|
subscriptionId: string;
|
||||||
|
lastCompletedItemId: string | null;
|
||||||
|
events: DirectThreadRawEvent[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DirectThreadConsumeResult = {
|
||||||
|
events: DirectThreadRawEvent[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type DirectThreadHistorySlice = {
|
||||||
|
items: unknown[];
|
||||||
|
hasMore: boolean;
|
||||||
|
itemTimestamps?: Record<string, number>;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* 历史条目转聊天消息。
|
|
||||||
*
|
|
||||||
* 过渡函数:`App.tsx` 仍按 `LocalConversationMessageRecord` 渲染,切换成 reducer 之后删除。
|
|
||||||
* 只保留 `role ∈ {user, assistant}` 且有正文的条目;工具卡片与交替顺序由 reducer 投影。
|
|
||||||
*/
|
|
||||||
export function directThreadHistoryItemsToMessages(
|
export function directThreadHistoryItemsToMessages(
|
||||||
items: readonly DirectThreadItem[],
|
items: unknown[],
|
||||||
|
itemTimestamps: Readonly<Record<string, number>> = {},
|
||||||
): LocalConversationMessageRecord[] {
|
): LocalConversationMessageRecord[] {
|
||||||
return items.flatMap((item) => {
|
return items.flatMap((raw) => {
|
||||||
if (item.itemType !== 'message') return [];
|
if (!raw || typeof raw !== 'object') return [];
|
||||||
if (item.role !== 'user' && item.role !== 'assistant') return [];
|
const item = raw as Record<string, unknown>;
|
||||||
if (!item.text) return [];
|
const role = item.role;
|
||||||
|
if (role !== 'user' && role !== 'assistant') return [];
|
||||||
|
const messageRole = role as 'user' | 'assistant';
|
||||||
|
const content = Array.isArray(item.content)
|
||||||
|
? item.content
|
||||||
|
.map((part) =>
|
||||||
|
part && typeof part === 'object' && 'text' in part
|
||||||
|
? (part as { text?: unknown }).text
|
||||||
|
: null,
|
||||||
|
)
|
||||||
|
.filter((text): text is string => typeof text === 'string')
|
||||||
|
.join('')
|
||||||
|
: '';
|
||||||
|
if (!content) return [];
|
||||||
|
const messageId = typeof item.id === 'string' ? item.id : undefined;
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
schemaVersion: 'agc-direct-project-context.v1',
|
schemaVersion: 'agc-direct-project-context.v1',
|
||||||
role: item.role,
|
role: messageRole,
|
||||||
content: item.text,
|
content,
|
||||||
agentId: null,
|
agentId: null,
|
||||||
messageId: item.itemId,
|
messageId,
|
||||||
updatedAt: item.at ?? 0,
|
updatedAt: messageId ? (itemTimestamps[messageId] ?? 0) : 0,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|||||||
-268
@@ -1,268 +0,0 @@
|
|||||||
/**
|
|
||||||
* DirectProject「原始条目 → 聊天条目」投影。
|
|
||||||
*
|
|
||||||
* 输入是 Rust 侧 ts-rs 导出的 `DirectThreadItem`(脱敏后的 Codex 原始条目),工具卡片的
|
|
||||||
* `kind`、标题、折叠摘要、状态判定和可见性全部在这里完成。运行态事件与历史切片走同一个
|
|
||||||
* 函数,因此实时与回读不可能出现两套口径。
|
|
||||||
*/
|
|
||||||
|
|
||||||
import type {
|
|
||||||
GameCreatorDirectToolCallChange,
|
|
||||||
GameCreatorDirectToolCallDetail,
|
|
||||||
GameCreatorDirectToolCallKind,
|
|
||||||
GameCreatorDirectToolCallStatus,
|
|
||||||
} from '../../app/types';
|
|
||||||
import type { DirectChatEntry, DirectChatToolCard } from './directThreadChat';
|
|
||||||
import type { DirectThreadItem } from './directThreadEvents';
|
|
||||||
|
|
||||||
/** 折叠态摘要上限,与卡片契约一致。 */
|
|
||||||
const TOOL_SUMMARY_MAX_CHARS = 120;
|
|
||||||
|
|
||||||
const FAILED_ITEM_STATUS = new Set([
|
|
||||||
'failed',
|
|
||||||
'declined',
|
|
||||||
'cancelled',
|
|
||||||
'canceled',
|
|
||||||
'aborted',
|
|
||||||
]);
|
|
||||||
|
|
||||||
function firstLine(value: string): string {
|
|
||||||
const [line = ''] = value.split('\n');
|
|
||||||
const trimmed = line.trim();
|
|
||||||
return trimmed.length > TOOL_SUMMARY_MAX_CHARS
|
|
||||||
? `${trimmed.slice(0, TOOL_SUMMARY_MAX_CHARS)}…`
|
|
||||||
: trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toolKindFromFunctionName(name: string): GameCreatorDirectToolCallKind {
|
|
||||||
switch (name) {
|
|
||||||
case 'exec_command':
|
|
||||||
case 'shell':
|
|
||||||
case 'exec':
|
|
||||||
return 'command';
|
|
||||||
case 'apply_patch':
|
|
||||||
case 'write_file':
|
|
||||||
case 'edit_file':
|
|
||||||
case 'create_file':
|
|
||||||
return 'file_change';
|
|
||||||
case 'web_search':
|
|
||||||
case 'web_search_preview':
|
|
||||||
return 'web_search';
|
|
||||||
default:
|
|
||||||
return 'mcp_tool';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function toolStatus(
|
|
||||||
status: string | null,
|
|
||||||
exitCode: number | null,
|
|
||||||
): GameCreatorDirectToolCallStatus {
|
|
||||||
if (status === 'completed') return 'completed';
|
|
||||||
if (status && FAILED_ITEM_STATUS.has(status)) return 'failed';
|
|
||||||
// Codex 的退出码约定:非 0 即失败;缺席时按「已完成」处理。
|
|
||||||
if (typeof exitCode === 'number') {
|
|
||||||
return exitCode === 0 ? 'completed' : 'failed';
|
|
||||||
}
|
|
||||||
return status ? 'running' : 'completed';
|
|
||||||
}
|
|
||||||
|
|
||||||
function toolTitle(
|
|
||||||
kind: GameCreatorDirectToolCallKind,
|
|
||||||
changes: readonly GameCreatorDirectToolCallChange[],
|
|
||||||
): string {
|
|
||||||
switch (kind) {
|
|
||||||
case 'command':
|
|
||||||
return '执行命令';
|
|
||||||
case 'file_change': {
|
|
||||||
const paths = new Set(changes.map((change) => change.path));
|
|
||||||
return paths.size > 0 ? `编辑 ${paths.size} 个文件` : '编辑文件';
|
|
||||||
}
|
|
||||||
case 'web_search':
|
|
||||||
return '联网检索';
|
|
||||||
case 'context_compaction':
|
|
||||||
return '整理上下文';
|
|
||||||
default:
|
|
||||||
return '调用工具';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function fileChanges(
|
|
||||||
item: Extract<DirectThreadItem, { itemType: 'fileChange' }>,
|
|
||||||
): GameCreatorDirectToolCallChange[] {
|
|
||||||
return item.changes
|
|
||||||
.filter((change) => change.path.trim().length > 0)
|
|
||||||
.map((change) => ({
|
|
||||||
path: change.path,
|
|
||||||
kind: change.kind || 'update',
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
type ToolCardInput = {
|
|
||||||
itemId: string;
|
|
||||||
at: number;
|
|
||||||
kind: GameCreatorDirectToolCallKind;
|
|
||||||
/** 输出条目只带输出:标题与摘要留空,交给先到的调用快照。 */
|
|
||||||
outputOnly?: boolean;
|
|
||||||
tool?: string;
|
|
||||||
command?: string;
|
|
||||||
output?: string;
|
|
||||||
status: GameCreatorDirectToolCallStatus;
|
|
||||||
changes?: GameCreatorDirectToolCallChange[];
|
|
||||||
};
|
|
||||||
|
|
||||||
function buildToolCard(input: ToolCardInput): DirectChatToolCard | null {
|
|
||||||
const changes = input.changes ?? [];
|
|
||||||
const detail: GameCreatorDirectToolCallDetail = {};
|
|
||||||
if (input.command && !input.outputOnly) detail.command = input.command;
|
|
||||||
if (input.output) detail.output = input.output;
|
|
||||||
if (changes.length > 0) detail.changes = changes;
|
|
||||||
// 没有命令 / 输出 / 文件明细的条目不渲染成卡片:一张空卡片对用户没有信息量。
|
|
||||||
if (!detail.command && !detail.output && !detail.changes?.length) return null;
|
|
||||||
|
|
||||||
const summarySource =
|
|
||||||
(input.kind === 'mcp_tool' ? (input.tool ?? '') : '') ||
|
|
||||||
detail.command ||
|
|
||||||
changes[0]?.path ||
|
|
||||||
input.tool ||
|
|
||||||
'';
|
|
||||||
return {
|
|
||||||
schemaVersion: 'agc-tool-call.v1',
|
|
||||||
id: input.itemId,
|
|
||||||
kind: input.kind,
|
|
||||||
title: input.outputOnly ? '' : toolTitle(input.kind, changes),
|
|
||||||
summary: input.outputOnly ? '' : firstLine(summarySource),
|
|
||||||
status: input.status,
|
|
||||||
detail,
|
|
||||||
startedAt: input.at,
|
|
||||||
updatedAt: input.at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function toolCardFromItem(item: DirectThreadItem): DirectChatToolCard | null {
|
|
||||||
switch (item.itemType) {
|
|
||||||
case 'function_call':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: toolKindFromFunctionName(item.name),
|
|
||||||
tool: item.name,
|
|
||||||
command: item.arguments,
|
|
||||||
status: 'running',
|
|
||||||
});
|
|
||||||
case 'function_call_output':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: 'other',
|
|
||||||
outputOnly: true,
|
|
||||||
output: item.output,
|
|
||||||
status: 'completed',
|
|
||||||
});
|
|
||||||
case 'commandExecution':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: 'command',
|
|
||||||
command: item.command,
|
|
||||||
output: item.output ?? '',
|
|
||||||
status: toolStatus(item.status, item.exitCode),
|
|
||||||
});
|
|
||||||
case 'fileChange':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: 'file_change',
|
|
||||||
changes: fileChanges(item),
|
|
||||||
status: 'completed',
|
|
||||||
});
|
|
||||||
case 'mcpToolCall':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: 'mcp_tool',
|
|
||||||
tool: item.tool,
|
|
||||||
command: item.arguments,
|
|
||||||
output: item.output ?? '',
|
|
||||||
status: toolStatus(item.status, null),
|
|
||||||
});
|
|
||||||
case 'webSearch':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: 'web_search',
|
|
||||||
command: item.query ?? '',
|
|
||||||
output: item.output ?? '',
|
|
||||||
status: 'completed',
|
|
||||||
});
|
|
||||||
case 'contextCompaction':
|
|
||||||
return buildToolCard({
|
|
||||||
itemId: item.itemId,
|
|
||||||
at: item.at,
|
|
||||||
kind: 'context_compaction',
|
|
||||||
command: '整理上下文',
|
|
||||||
status: 'completed',
|
|
||||||
});
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 原始条目投影成聊天条目;不属于聊天内容的条目返回 `null`。
|
|
||||||
*
|
|
||||||
* 可见性判定只在这里:系统 / 开发者 message、无正文的空条目、未识别的 item 类型都不进
|
|
||||||
* 聊天视图。`other` 是 Rust 原样透传的未知类型,要不要显示属于前端可见性决策,当前不显示。
|
|
||||||
*/
|
|
||||||
export function projectDirectThreadItem(
|
|
||||||
item: DirectThreadItem | null | undefined,
|
|
||||||
): DirectChatEntry | null {
|
|
||||||
if (!item) return null;
|
|
||||||
const itemId = item.itemId.trim();
|
|
||||||
if (!itemId) return null;
|
|
||||||
|
|
||||||
switch (item.itemType) {
|
|
||||||
case 'message': {
|
|
||||||
const role =
|
|
||||||
item.role === 'user'
|
|
||||||
? 'user'
|
|
||||||
: item.role === 'assistant'
|
|
||||||
? 'assistant'
|
|
||||||
: null;
|
|
||||||
if (!role || !item.text.trim()) return null;
|
|
||||||
return {
|
|
||||||
itemId,
|
|
||||||
kind: 'message',
|
|
||||||
role,
|
|
||||||
text: item.text,
|
|
||||||
toolCall: null,
|
|
||||||
at: item.at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
case 'reasoning': {
|
|
||||||
if (!item.text.trim()) return null;
|
|
||||||
return {
|
|
||||||
itemId,
|
|
||||||
kind: 'reasoning',
|
|
||||||
role: null,
|
|
||||||
text: item.text,
|
|
||||||
toolCall: null,
|
|
||||||
at: item.at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
case 'other':
|
|
||||||
// TODO(direct-thread): 未识别类型目前不显示;要让它们出现只改这里,别回 Rust 加白名单。
|
|
||||||
return null;
|
|
||||||
default: {
|
|
||||||
const toolCall = toolCardFromItem(item);
|
|
||||||
if (!toolCall) return null;
|
|
||||||
return {
|
|
||||||
itemId,
|
|
||||||
kind: 'tool',
|
|
||||||
role: null,
|
|
||||||
text: null,
|
|
||||||
toolCall,
|
|
||||||
at: item.at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||||
|
|
||||||
|
export type DirectCodexUserAttachmentReferencePart = {
|
||||||
|
name: string;
|
||||||
|
mediaType: string;
|
||||||
|
size: number;
|
||||||
|
localPath: string;
|
||||||
|
status: string;
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user