Compare commits

..

3 Commits

Author SHA1 Message Date
k88936 053e0bd932 Thread Manager:待发消息队列的入队 / 取消 / 放行认领
Project CI / AI game creator shell Rust crates (pull_request) Successful in 1m12s
Project CI / AI game creator shell Rust smoke (pull_request) Successful in 1m31s
Project CI / Backend tests (pull_request) Successful in 4m1s
Project CI / Frontend tests (pull_request) Successful in 2m5s
Project CI / Native shell tests (pull_request) Successful in 6m7s
Project CI / AI game creator shell Rust lane 1/2 (pull_request) Successful in 10m0s
Project CI / AI game creator shell Rust lane 2/2 (pull_request) Successful in 10m3s
Project CI / AI game creator shell web tests (pull_request) Successful in 1m52s
Project CI / Repository checks (pull_request) Successful in 2m17s
- `StoredEvent` 增加非序列化的 `pending` 产物字段:它的有无就是队列成员身份,队列的先后就是事件先后,不另建队列表
- 新增 `enqueue_pending_turn`:按 `clientTurnId` 幂等(判重范围「在队 ∪ 正在跑的那一轮」),容量用 `queue_has_room` 挡在队条目
- 新增 `remove_pending_turn`:typed 结果 `Removed | AlreadyDispatched | NotFound`,在临界区里取走产物并追加 `queue.removed{cancelled}`
- 新增 `claim_pending_turn`:同一临界区取队首 → 登记占用 → 追加 `turn.started` 与 `queue.removed{dispatched}`,已有未收口回合或队列为空时返回 `None`
- `mark_queue_events_cleanable` 跳过仍挂着产物的条目,保证在队条目永远不会被回收
- 新增薄包装 `enqueue_direct_pending_turn` / `remove_direct_pending_turn` / `claim_direct_pending_turn`,并补 5 条单测覆盖 bootstrap 可见、幂等、容量、放行原子性与三种取消结果
2026-09-24 21:11:15 +08:00
k88936 faf85837bd 运行态事件:待发消息队列的入队/移除事件与队列条目规则
- 新增 `DirectThreadEvent::QueueEnqueued`(`queue.enqueued`,带 canonical 用户条目与可选 `creationType`,不带 prompt)与 `QueueRemoved`(`queue.removed`,`reason` 为 typed 枚举 `cancelled | dispatched`)
- 新增 typed 枚举 `DirectQueueRemovalReason` 与 `DirectQueueRemovalOutcome`,并重跑 ts-rs 绑定
- 新增 `agent/direct_thread_queue.rs`:`PendingDirectTurn`(入队时冻结 canonical 形状与 prompt)、上限 `MAX_PENDING_DIRECT_TURNS = 5`、`EnqueueOutcome` / `EnqueueRejection`
- Thread Manager 的 `observe_event` 认队列事件:在队期间的 `queue.enqueued` 不可回收,`queue.removed` 把它转成可回收,新订阅者的 bootstrap 因此天然看得见当前队列
- `DirectCodexUserItem` 及其子类型补 `PartialEq`,`DirectThreadEvent` 不再需要 `Eq`
2026-09-24 20:58:08 +08:00
k88936 1e7ea51368 文档:DirectProject 命令入队化与待发消息队列归宿主设计定稿
- 新增 ADR:命令=入队、放行归 Thread Manager、待发消息队列作为运行态事件归宿主
- 新增实施计划:五步落地顺序、标识符映射表、每步不变式与验收证据
- CONTEXT.md:接单/拒单词条替换为入队/入队失败/放行,新增待发消息队列与待发消息词条
- docs/README.md 补两条索引;decision-log.md 追加同日决策记录
2026-09-24 20:46:53 +08:00
272 changed files with 2249 additions and 23450 deletions
-9
View File
@@ -145,15 +145,6 @@ ELEVENLABS_BASE_URL="https://api.elevenlabs.io"
ELEVENLABS_API_KEY=""
ELEVENLABS_REQUEST_TIMEOUT_MS="180000"
# Tripo 3D 生成:地址与密钥必须显式给出,没有内置默认值。
# 缺任意一个,会提交或会执行 3D job 的进程(api / external-generation-worker / all)
# 在启动期直接拒绝启动——不会带着未知网关或空密钥把进程跑起来。
TRIPO_BASE_URL="https://openapi.tripo3d.com/v3"
TRIPO_API_KEY=""
# 两个运行旋钮可缺省(沿用内置值);显式给出时会校验,非法即拒绝启动。
TRIPO_REQUEST_TIMEOUT_MS="60000"
TRIPO_RETRIES="2"
# 阿里云 OSS 配置。
# Rust `server-rs` 的 `api-server` 会优先从 `.env` / `.env.local` 读取这些变量,
# 用于签发浏览器 PostObject 直传票据,并保持 `/generated-*` 旧路径习惯。
+21 -93
View File
@@ -67,90 +67,6 @@ _Avoid_: 每步一个 sidecar 状态机、把切分专用的 SeparationState 泛
## Language
### 3D Model Generation
**3D 模型生成操作**:
由文本提示或平台图片引用驱动、可异步查询并最终产生模型文件的 provider-neutral 操作;操作状态和产品资源结果分开建模。
_Avoid_: 直接把第三方 provider task 当作产品资源、把模型 URL 当作永久资源地址
**Provider task**:
第三方 3D 生成平台返回的任务引用与任务快照,只存在于 provider adapter 的 Rust 边界内;它不是 Genarrative 的内部操作 ID。
_Avoid_: 把 Tripo task ID 当作稳定产品 operationId、让 SDK 类型穿透 api-server
**临时 provider URL**:
第三方任务完成后返回的短时模型下载地址,必须通过显式下载流程转换为本地或持久化资源,不能直接当作长期资产地址。
_Avoid_: 永久 OSS URL、资源 ID
**模型 artifact**:
由 text-to-model、image-to-model 或 multiview-to-model 任务产生、待应用层登记和持久化的模型文件结果;provider adapter 只提供可下载结果,不负责生成 resourceId 或 assetId。
_Avoid_: 仅 UI 中展示的模型链接、没有来源任务的静态文件
**Tripo API facade**:
面向站内已认证调用方的全新 Tripo 3D 生成 API 上下文,负责把 API operation、用户归属、异步状态、产物持久化和正式资源引用连接起来;它独立于历史 Hyper3D adapter,不复用其路由、契约或实现。
_Avoid_: 把 Tripo API 当成 Hyper3D 的 provider 替换、让 Hyper3D 路由悄悄切换到 Tripo
**Tripo operation**:
Genarrative 为一次 Tripo 生成请求分配的内部异步操作标识;客户端只看到 operationId,Tripo provider task 只作为服务端 checkpoint 保存,二者不是同一个 ID。
_Avoid_: 将 Tripo taskId 直接当公开 operationId、把 SDK task 状态模型穿透到 API
**模型产物持久化**:
Tripo 任务完成后,服务端下载模型与预览、写入受控对象存储并登记资源元数据,成功后才把 Tripo operation 置为 completed;本期按完整字节写入,流式上传是后续目标。
_Avoid_: 返回临时签名 URL作为永久资源、在 API handler 中把完整模型读成 Vec<u8>
**3D provider 配置门禁**:
Tripo 网关与密钥的可用性在「会提交或会执行 3D job 的进程」(`api` / `external-generation-worker` / `all`)启动期判定:`TRIPO_BASE_URL` 与 `TRIPO_API_KEY` 没有内置默认值,缺失、空白或网关非法即拒绝启动;请求期返回 503 只是第二道防线,不承担发现部署缺失的职责。
_Avoid_: 内置默认网关、缺配置时静默沿用某个地址或兜底密钥、把「少配置」留到用户提交后才发现
**3D 生成底价**:
一次 3D 生成在指定端点和模型版本下、按是否带贴图区分的基准泥点价,不包含任何叠加项,也不随请求的其它参数变化。
_Avoid_: 把底价与加价项合并成一个档位价、把 provider 的 credit 数值当底价
**3D 生成加价项**:
叠加在底价之上、由请求参数判定的可选泥点加价;每个端点各自持有一份加价项价目,同一加价项在不同端点可以是不同价。
_Avoid_: 全局唯一一份加价项价目、按用途而不是按请求参数判定加价
**定价配置归一化**:
读取持久化定价时把它与当前契约对齐的过程:缺的键用受控默认值补齐,契约之外的遗留键剔除并告警;它只发生在读取方向,写入方向仍要求完整合法。
_Avoid_: 把「省略即沿用」当作保存语义、把归一化当成静默改价
**模型生成落点**:
3D 生成结果要进入的平台容器,调用方必须在工程资源与素材库资产之间显式二选一;工程分支可附带画布占位框回填,素材库分支必须给出目录与标签。
_Avoid_: 两个都不给就默认落素材库、把落点混进 provider 请求参数
**模型输入资源引用**:
image-to-model 请求对平台已有图片的明确 tagged 引用,可指向项目资源或素材库资产;服务端负责 owner 校验和 OSS 对象解析,不接受把多种来源塞进裸 `input` 字符串。
_Avoid_: 任意远程 URL、data URL、未区分语义的 resourceId/assetId 字符串
**3D 模型生成工具**:
图片画布工程里从底部工具栏打开、给出「文生 3D 模型」与「图生 3D 模型」两个子项的画布生成工具;提交后按画布既有生成链路的占位框、任务侧栏与失败退款口径推进,产物落成 **3D 模型资源**。
_Avoid_: 独立 3D 生成页、把 3D 生成做成玩法类型或作品、把 3D 生成接进画布 Agent 对话
**3D 生成定价**:
3D 模型生成工具在提交前展示的泥点价格,来自编辑器生成定价查询的 `model3d` 段;该段缺失即入口不可提交,前端不内置兜底数值。该段的权威事实源是 SpacetimeDB 定价表里的两段强类型列,公开读取时投影回迁移前的旧形状。
_Avoid_: 前端写死 3D 价格、借用图片模型的兜底定价配置、按 0 元放行、把内部两段结构直接暴露给画布
**定价版本(乐观锁)**:
后台读取完整模型定价时一并拿到的版本号(SpacetimeDB 行的更新时间微秒值),保存时必须原样回传;与服务端当前版本不一致即整笔拒绝并返回 409,提示重新读取,避免静默覆盖他人的改价。
_Avoid_: 在前端自造或缓存该版本、把版本不匹配当成可重试的普通失败、把「省略字段」当成「沿用当前值」
### 3D 模型资源预览
**3D 模型资源**:
类别为 `model3d` 的平台资源 / 素材,一个资源同时持有模型本体与模型预览图两个对象;客户端默认消费预览图,模型本体只在 3D 查看器里加载。
_Avoid_: 只有模型文件的资源、把模型本体当图片素材、为模型新增并列媒体类型
**模型预览图**:
3D 模型资源的静态代表图,落在资源投影的 `imageSrc` 与 `thumbnailSrc` 上,供画布卡片、素材缩略图、后台列表和精选卡片使用。
_Avoid_: 用模型本体充当预览、按需实时渲染缩略图、把预览图当模型真相
**模型本体**:
3D 模型资源里的可下载模型文件,只由资源的 `objectKey` 指向,格式以对象内容类型为准。
_Avoid_: 把模型本体当图片地址、用预览图字段承载模型文件、按文件扩展名推断格式
**3D 查看器预览**:
在资源上打开模态把模型本体交给 3D 查看器渲染的只读能力,不修改资源、不产出新资源,也不是画布图层本身的编辑操作。
_Avoid_: 在画布里内联渲染模型、把预览当编辑、为预览产出新资源
### Puzzle Clear
**拼消消**:
@@ -276,7 +192,7 @@ _Avoid_: mock 先行堆积、前后端各自发散、先做排行榜 UI
## 项目开发对话(DirectProject)
**DirectProject 专属聊天模块**:
AGC 普通项目聊天的独立容器,拥有 DirectProject 的聊天状态、运行态订阅、历史读取、发送队列、附件和中止交互,并把聊天投影交给专属表现层渲染;它不承接 Supervisor、Design Agent 或 Planning V2 的运行态。
AGC 普通项目聊天的独立容器,拥有 DirectProject 的聊天状态、运行态订阅、历史读取、待发消息队列的投影、附件和中止交互,并把聊天投影交给专属表现层渲染;它不承接 Supervisor、Design Agent 或 Planning V2 的运行态。
_Avoid_: 把 DirectProject 作为项目总控聊天的一个布尔分支、把四种 Agent 会话抽象成同一事实源
**项目工作台布局**:
@@ -292,20 +208,32 @@ Thread Manager 向订阅者推送的当前回合原始事件流,只服务运
_Avoid_: 进度通知、快照轮询、第二套历史
**逻辑回合**:
Thread Manager 拥有的一对回合边界(开始与结束),由接单动作开启、由这一轮的占用对象写出,不镜像 Codex 原生回合;界面忙碌态与回合结果只认它。
Thread Manager 拥有的一对回合边界(开始与结束),由放行动作开启、由这一轮的占用对象写出,不镜像 Codex 原生回合;界面忙碌态与回合结果只认它。
_Avoid_: Codex 原生回合、原生日志、进程生命周期
**接单**:
把一条用户消息交给宿主开始执行的动作,成立即表示这一轮已经存在;此后结果只由运行态事件回答。
_Avoid_: 发送成功、命令调用、接口返回
**待发消息队列**:
Thread Manager 按项目持有的待发用户消息序列,只支持按入队顺序追加与按身份移除,状态由运行态事件派生,不落盘、不构成第二份事实源。
_Avoid_: 前端本地队列、队列副本、待发消息的持久化记录
**拒单**:
接单成立之前拒绝这次请求(并发、权限、目录、参数、工程准备未就绪),只回一条可展示原因,不产生回合事件,也不写用户条目。
**待发消息**:
已经通过入队检查、等待被放行的用户消息;它在放行之前不是回合,不写用户条目、不产生回合事件。
_Avoid_: 回合、在途回合、草稿
**入队**:
把一条用户消息交给宿主的动作:宿主跑完入队检查后把它放进待发消息队列;入队成立只表示这条消息会按顺序被放行。
_Avoid_: 发送成功、已经开跑、回合成立
**入队失败**:
入队检查未通过(身份、形状、容量、权限、目录、参数、工程准备未就绪)时拒绝这次请求,只回一条可展示原因,不入队、不产生回合事件,也不写用户条目。
_Avoid_: 回合失败、执行失败、失败事件
**放行**:
Thread Manager 在一个回合收口之后把队首的待发消息送进回合:同一临界区里登记占用、落盘用户条目、发出逻辑回合开始事件并起整轮;放行之后的结果只由运行态事件回答。
_Avoid_: 前端放行、定时轮询、放行失败
**在途回合**:
界面本地已经把这条用户消息发出去、宿主还没有对应回合开始事件的那一小段状态。
_Avoid_: 运行中回合、乐观锁、发送队列
界面本地已经入队、宿主还没有对应回合开始事件的那一小段状态。
_Avoid_: 运行中回合、乐观锁、前端发送队列
**聊天投影**:
把项目对话历史条目与运行态事件转换成消息气泡和工具卡片的读取期转换;不持久化,也不构成事实源。
+1 -2
View File
@@ -60,7 +60,6 @@ import type {
AdminUpdateAccountResponse,
AdminUpdateAgcTemplateRequest,
AdminUploadedEditorShowcaseCampaignImage,
AdminUpsertEditorGenerationPricingRequest,
AdminUpsertEditorShowcaseCampaignRequest,
AdminUpsertFeatureGateConfigRequest,
AdminUpsertProfileInviteCodeRequest,
@@ -520,7 +519,7 @@ export function getAdminEditorGenerationPricing(token: string) {
export function upsertAdminEditorGenerationPricing(
token: string,
payload: AdminUpsertEditorGenerationPricingRequest,
payload: EditorGenerationPricingConfigPayload,
) {
return request<EditorGenerationPricingConfigPayload>(
'/admin/api/editor-generation-pricing',
-35
View File
@@ -431,43 +431,8 @@ export interface EditorGenerationModelPricingPayload {
prices?: Record<string, number>;
}
/** 某个 3D 模型版本在「无贴图 / 带贴图」两种形态下的泥点底价。 */
export interface EditorGenerationModel3dVersionPricePayload {
noTexture: number;
texture: number;
}
/**
* 单个 3D 生成端点的整套定价:模型版本底价 + 该端点自己的加价项价目。
*
* 键集合由后端契约决定,后台只改数值:模型版本键与加价项键都直接来自接口返回,
* 不在前端硬编码清单,也不能新增、删除或停用。
*/
export interface EditorGenerationModel3dEndpointPricingPayload {
versionPrices: Record<string, EditorGenerationModel3dVersionPricePayload>;
addOnPrices: Record<string, number>;
}
/** 3D 生成定价段:两个端点并列,各持自己的设置。 */
export interface EditorGenerationModel3dPricingPayload {
textToModelPricing: EditorGenerationModel3dEndpointPricingPayload;
imageToModelPricing: EditorGenerationModel3dEndpointPricingPayload;
}
export interface EditorGenerationPricingConfigPayload {
models: Record<string, EditorGenerationModelPricingPayload>;
/** 后端尚未配置 3D 段时缺省;缺失即 3D 生成不可提交,后台也不能新建整段。 */
model3d?: EditorGenerationModel3dPricingPayload | null;
}
/**
* 后台保存定价的请求体:`models` 与 3D 两段都必须显式给出。
*
* 不带定价版本:保存即整段覆盖,服务端不比对版本(后台同时只有一个管理员在操作)。
*/
export interface AdminUpsertEditorGenerationPricingRequest {
models: Record<string, EditorGenerationModelPricingPayload>;
model3d: EditorGenerationModel3dPricingPayload | null;
}
export interface AdminEditorAssetListQuery {
@@ -1,131 +0,0 @@
import type {
EditorGenerationModel3dPricingPayload,
EditorGenerationModel3dVersionPricePayload,
} from '../api/adminApiTypes';
import {
EDITOR_MODEL3D_ENDPOINT_SECTIONS,
editorModel3dAddOnLabel,
updateEditorModel3dEndpointPricing,
} from './adminEditorGenerationPricing';
import { parsePositiveInteger } from './pageUtils';
/**
* 一个模型版本的两个底价字段。两栏只有字段键与展示名不同,用描述表驱动渲染,
* 避免两段近乎相同的 JSX 各自演化。
*/
const VERSION_PRICE_FIELDS = [
{ key: 'noTexture', label: '无贴图' },
{ key: 'texture', label: '带贴图' },
] as const satisfies ReadonlyArray<{
key: keyof EditorGenerationModel3dVersionPricePayload;
label: string;
}>;
interface AdminEditorGenerationModel3dPricingSectionProps {
model3d: EditorGenerationModel3dPricingPayload;
onChange: (next: EditorGenerationModel3dPricingPayload) => void;
}
/**
* 3D 生成定价区块:按端点分成「文生 3D」与「图生 3D」两组,每组是该端点自己的
* 「模型版本 × {无贴图, 带贴图}」底价表与加价项单值输入。
*
* 键集合全部来自接口返回,后台只能改数值:不能新增、删除键,也不能停用整段。
*/
export function AdminEditorGenerationModel3dPricingSection({
model3d,
onChange,
}: AdminEditorGenerationModel3dPricingSectionProps) {
function updateEndpoint(
section: (typeof EDITOR_MODEL3D_ENDPOINT_SECTIONS)[number]['key'],
updater: Parameters<typeof updateEditorModel3dEndpointPricing>[2],
) {
onChange(updateEditorModel3dEndpointPricing(model3d, section, updater));
}
return (
<section className="admin-panel admin-pricing-model-card">
<div className="admin-pricing-model-heading">
<strong>3D 生成定价</strong>
<span className="admin-pricing-unit">按次</span>
</div>
<p className="admin-pricing-model3d-hint">
模型版本与加价项由后端契约给出,只能改数值;两段必须完整给出,缺失即 3D
生成不可提交。
</p>
<div className="admin-pricing-grid">
{EDITOR_MODEL3D_ENDPOINT_SECTIONS.map(({ key, label }) => (
<section className="admin-panel admin-pricing-model-card" key={key}>
<div className="admin-pricing-model-heading">
<strong>{label}</strong>
</div>
<div className="admin-pricing-model3d-list">
{Object.entries(model3d[key].versionPrices).map(
([version, price]) => (
<div className="admin-pricing-model3d-row" key={version}>
<span className="admin-pricing-model3d-row-label">
{version}
</span>
{VERSION_PRICE_FIELDS.map(
({ key: field, label: fieldLabel }) => (
<label className="admin-field" key={field}>
<span>{fieldLabel}</span>
<input
aria-label={`${label} ${version} ${fieldLabel}`}
min={1}
step={1}
type="number"
value={price[field]}
onChange={(event) =>
updateEndpoint(key, (current) => ({
...current,
versionPrices: {
...current.versionPrices,
[version]: {
...price,
[field]: parsePositiveInteger(
event.target.value,
),
},
},
}))
}
/>
</label>
),
)}
</div>
),
)}
</div>
<div className="admin-form-row">
{Object.entries(model3d[key].addOnPrices).map(
([addOn, price]) => (
<label className="admin-field" key={addOn}>
<span>{editorModel3dAddOnLabel(addOn)}</span>
<input
aria-label={`${label} ${editorModel3dAddOnLabel(addOn)}`}
min={1}
step={1}
type="number"
value={price}
onChange={(event) =>
updateEndpoint(key, (current) => ({
...current,
addOnPrices: {
...current.addOnPrices,
[addOn]: parsePositiveInteger(event.target.value),
},
}))
}
/>
</label>
),
)}
</div>
</section>
))}
</div>
</section>
);
}
@@ -11,16 +11,14 @@ import {
import type { EditorGenerationPricingConfigPayload } from '../api/adminApiTypes';
import { AdminEditorGenerationPricingPage } from './AdminEditorGenerationPricingPage';
vi.mock('../api/adminApiClient', async () => {
const actual = await vi.importActual<typeof import('../api/adminApiClient')>(
'../api/adminApiClient',
);
return {
...actual,
getAdminEditorGenerationPricing: vi.fn(),
upsertAdminEditorGenerationPricing: vi.fn(),
};
});
vi.mock('../api/adminApiClient', () => ({
formatAdminApiError: vi.fn((error: unknown) =>
error instanceof Error ? error.message : '请求失败',
),
getAdminEditorGenerationPricing: vi.fn(),
isAdminApiError: vi.fn(() => false),
upsertAdminEditorGenerationPricing: vi.fn(),
}));
const pricing: EditorGenerationPricingConfigPayload = {
models: {
@@ -43,78 +41,36 @@ const pricing: EditorGenerationPricingConfigPayload = {
'audio1.0': { unit: 'perGeneration', price: 5 },
'chirp-v5': { unit: 'perGeneration', price: 12 },
},
model3d: {
textToModelPricing: {
versionPrices: {
'v3.1-20260211': { noTexture: 8, texture: 16 },
'P2-20260801': { noTexture: 80, texture: 88 },
},
addOnPrices: {
hdTexture: 8,
ultraTexture: 16,
quadMesh: 4,
generateParts: 16,
},
},
imageToModelPricing: {
versionPrices: {
'v3.1-20260211': { noTexture: 16, texture: 24 },
'P2-20260801': { noTexture: 80, texture: 88 },
},
addOnPrices: {
hdTexture: 8,
ultraTexture: 16,
quadMesh: 4,
generateParts: 16,
},
},
},
};
function savedPricing(
overrides: Partial<EditorGenerationPricingConfigPayload> = {},
) {
return {
...pricing,
...overrides,
};
}
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getAdminEditorGenerationPricing).mockResolvedValue(pricing);
vi.mocked(upsertAdminEditorGenerationPricing).mockResolvedValue(
savedPricing({
models: {
...pricing.models,
'gpt-image-2': {
unit: 'perGeneration',
prices: { '1K': 20, '2K': 58 },
},
vi.mocked(upsertAdminEditorGenerationPricing).mockResolvedValue({
...pricing,
models: {
...pricing.models,
'gpt-image-2': {
unit: 'perGeneration',
prices: { '1K': 20, '2K': 58 },
},
}),
);
},
});
});
async function renderPage() {
test('模型定价后台按模型展示单位并保存尺寸定价', async () => {
const user = userEvent.setup();
render(
<AdminEditorGenerationPricingPage
token="admin-token"
onUnauthorized={vi.fn()}
/>,
);
await screen.findByText('3D 生成定价');
}
test('模型定价后台按模型展示单位并保存尺寸定价', async () => {
const user = userEvent.setup();
await renderPage();
expect((await screen.findAllByText('按次')).length).toBeGreaterThan(0);
expect(screen.getAllByText('按秒').length).toBeGreaterThan(0);
fireEvent.change(screen.getByLabelText('gpt-image-2 2K'), {
target: { value: '58' },
});
const gptImage2kInput = screen.getByLabelText('gpt-image-2 2K');
fireEvent.change(gptImage2kInput, { target: { value: '58' } });
await user.click(screen.getByRole('button', { name: '保存定价' }));
await user.click(screen.getByRole('button', { name: '确认' }));
@@ -134,82 +90,3 @@ test('模型定价后台按模型展示单位并保存尺寸定价', async () =>
);
});
});
test('3D 区块按端点渲染版本底价与加价项,并随保存回传整段与定价版本', async () => {
const user = userEvent.setup();
await renderPage();
expect(screen.getByText('文生 3D')).toBeTruthy();
expect(screen.getByText('图生 3D')).toBeTruthy();
expect(screen.getAllByText('高清贴图').length).toBeGreaterThan(0);
fireEvent.change(screen.getByLabelText('文生 3D v3.1-20260211 带贴图'), {
target: { value: '18' },
});
fireEvent.change(screen.getByLabelText('图生 3D P2-20260801 无贴图'), {
target: { value: '86' },
});
fireEvent.change(screen.getByLabelText('文生 3D 四边形网格'), {
target: { value: '6' },
});
await user.click(screen.getByRole('button', { name: '保存定价' }));
await user.click(screen.getByRole('button', { name: '确认' }));
await waitFor(() => {
expect(upsertAdminEditorGenerationPricing).toHaveBeenCalledWith(
'admin-token',
expect.objectContaining({
model3d: {
textToModelPricing: expect.objectContaining({
versionPrices: expect.objectContaining({
'v3.1-20260211': { noTexture: 8, texture: 18 },
}),
addOnPrices: expect.objectContaining({ quadMesh: 6 }),
}),
imageToModelPricing: expect.objectContaining({
versionPrices: expect.objectContaining({
'P2-20260801': { noTexture: 86, texture: 88 },
}),
}),
},
}),
);
});
});
test('数值小于 1 时禁用保存并给出中文提示', async () => {
const user = userEvent.setup();
await renderPage();
fireEvent.change(screen.getByLabelText('文生 3D 四边形网格'), {
target: { value: '0' },
});
expect(await screen.findByText(/以下价格必须是不小于 1 的整数/)).toBeTruthy();
const saveButton = screen.getByRole('button', {
name: '保存定价',
}) as HTMLButtonElement;
expect(saveButton.disabled).toBe(true);
await user.click(saveButton);
expect(upsertAdminEditorGenerationPricing).not.toHaveBeenCalled();
});
test('后端未配置 3D 段时给出提示并禁止保存', async () => {
vi.mocked(getAdminEditorGenerationPricing).mockResolvedValue({
...pricing,
model3d: null,
});
render(
<AdminEditorGenerationPricingPage
token="admin-token"
onUnauthorized={vi.fn()}
/>,
);
expect(await screen.findByText(/当前部署未配置 3D 定价段/)).toBeTruthy();
expect(
(screen.getByRole('button', { name: '保存定价' }) as HTMLButtonElement)
.disabled,
).toBe(true);
});
@@ -6,18 +6,12 @@ import {
upsertAdminEditorGenerationPricing,
} from '../api/adminApiClient';
import type {
EditorGenerationModel3dPricingPayload,
EditorGenerationModelPricingPayload,
EditorGenerationPricingConfigPayload,
EditorGenerationPricingUnitPayload,
} from '../api/adminApiTypes';
import { useAdminWriteConfirm } from '../components/useAdminWriteConfirm';
import { AdminEditorGenerationModel3dPricingSection } from './AdminEditorGenerationModel3dPricingSection';
import {
buildAdminEditorGenerationPricingRequest,
collectInvalidEditorGenerationPricingLabels,
} from './adminEditorGenerationPricing';
import { handlePageError, parsePositiveInteger } from './pageUtils';
import { handlePageError } from './pageUtils';
interface AdminEditorGenerationPricingPageProps {
token: string;
@@ -26,7 +20,6 @@ interface AdminEditorGenerationPricingPageProps {
const emptyPricing: EditorGenerationPricingConfigPayload = {
models: {},
model3d: null,
};
const unitLabels: Record<EditorGenerationPricingUnitPayload, string> = {
@@ -64,7 +57,7 @@ export function AdminEditorGenerationPricingPage({
async function handleSave(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (isSaving || !canSave) {
if (isSaving) {
return;
}
setErrorMessage('');
@@ -78,12 +71,7 @@ export function AdminEditorGenerationPricingPage({
setIsSaving(true);
try {
setPricing(
await upsertAdminEditorGenerationPricing(
token,
buildAdminEditorGenerationPricingRequest(pricing),
),
);
setPricing(await upsertAdminEditorGenerationPricing(token, pricing));
} catch (error: unknown) {
handlePageError(error, onUnauthorized, setErrorMessage);
} finally {
@@ -132,15 +120,6 @@ export function AdminEditorGenerationPricingPage({
});
}
function updateModel3dPrice(next: EditorGenerationModel3dPricingPayload) {
setPricing((current) => ({ ...current, model3d: next }));
}
const invalidPriceLabels =
collectInvalidEditorGenerationPricingLabels(pricing);
const isModel3dMissing = !pricing.model3d;
const canSave = invalidPriceLabels.length === 0 && !isModel3dMissing;
return (
<section className="admin-page admin-page-wide">
<div className="admin-page-heading">
@@ -165,20 +144,6 @@ export function AdminEditorGenerationPricingPage({
</div>
) : null}
{isModel3dMissing ? (
<div className="admin-alert" role="status">
当前部署未配置 3D 定价段(缺失即 3D
生成不可提交):需先由受控默认配置提供两段价格,
后台不在页面里新建或停用整段。
</div>
) : null}
{invalidPriceLabels.length > 0 ? (
<div className="admin-alert" role="status">
{`以下价格必须是不小于 1 的整数:${invalidPriceLabels.join('、')}`}
</div>
) : null}
<form className="admin-stack" onSubmit={handleSave}>
<div className="admin-pricing-model-list admin-pricing-model-list--single">
{Object.entries(pricing.models).map(([model, modelPricing]) =>
@@ -191,16 +156,9 @@ export function AdminEditorGenerationPricingPage({
)}
</div>
{pricing.model3d ? (
<AdminEditorGenerationModel3dPricingSection
model3d={pricing.model3d}
onChange={updateModel3dPrice}
/>
) : null}
<button
className="admin-primary-button"
disabled={isSaving || !canSave}
disabled={isSaving}
type="submit"
>
<Save size={17} aria-hidden="true" />
@@ -265,3 +223,8 @@ function renderModelPricingCard({
</section>
);
}
function parsePositiveInteger(value: string) {
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}
@@ -7,7 +7,7 @@ import {
} from '../api/adminApiClient';
import type { ProfileWalletConfigAdminResponse } from '../api/adminApiTypes';
import { useAdminWriteConfirm } from '../components/useAdminWriteConfirm';
import { handlePageError, parsePositiveInteger } from './pageUtils';
import { handlePageError } from './pageUtils';
interface AdminProfileWalletConfigPageProps {
token: string;
@@ -197,3 +197,8 @@ export function AdminProfileWalletConfigPage({
</section>
);
}
function parsePositiveInteger(value: string) {
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
}
@@ -11,7 +11,7 @@ import type {
ProfileRechargeProductKind,
} from '../api/adminApiTypes';
import { useAdminWriteConfirm } from '../components/useAdminWriteConfirm';
import { handlePageError, parsePositiveInteger } from './pageUtils';
import { handlePageError } from './pageUtils';
interface AdminRechargeProductPageProps {
token: string;
@@ -546,6 +546,11 @@ function formatPrice(priceCents: number) {
return `¥${(priceCents / 100).toFixed(2)}`;
}
function parsePositiveInteger(value: string) {
const parsed = parseInteger(value);
return parsed > 0 ? parsed : 0;
}
function parseNonNegativeInteger(value: string) {
const parsed = parseInteger(value);
return parsed > 0 ? parsed : 0;
@@ -12,7 +12,7 @@ import type {
ProfileRedeemCodeMode,
} from '../api/adminApiTypes';
import { useAdminWriteConfirm } from '../components/useAdminWriteConfirm';
import { handlePageError, parsePositiveInteger, splitLines } from './pageUtils';
import { handlePageError, splitLines } from './pageUtils';
interface AdminRedeemCodePageProps {
token: string;
@@ -422,6 +422,11 @@ export function AdminRedeemCodePage({
);
}
function parsePositiveInteger(value: string) {
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}
function redeemModeLabel(value: ProfileRedeemCodeMode) {
return redeemModes.find((item) => item.value === value)?.label ?? value;
}
@@ -19,7 +19,7 @@ import {
filterAdminTrackingEventKeyOptions,
findAdminTrackingEventDefinition,
} from '../config/trackingEventDefinitions';
import { handlePageError, parsePositiveInteger } from './pageUtils';
import { handlePageError } from './pageUtils';
interface AdminTaskConfigPageProps {
token: string;
@@ -571,6 +571,11 @@ export function AdminTaskConfigPage({
);
}
function parsePositiveInteger(value: string) {
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
}
function parseInteger(value: string) {
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) ? parsed : 0;
@@ -1,87 +0,0 @@
import { expect, test } from 'vitest';
import type { EditorGenerationPricingConfigPayload } from '../api/adminApiTypes';
import {
buildAdminEditorGenerationPricingRequest,
collectInvalidEditorGenerationPricingLabels,
editorModel3dAddOnLabel,
} from './adminEditorGenerationPricing';
import { parsePositiveInteger } from './pageUtils';
function pricingFixture(): EditorGenerationPricingConfigPayload {
return {
models: {
'gpt-image-2': { unit: 'perGeneration', prices: { '1K': 3, '2K': 5 } },
'audio1.0': { unit: 'perGeneration', price: 5 },
},
model3d: {
textToModelPricing: {
versionPrices: { 'v3.1-20260211': { noTexture: 8, texture: 16 } },
addOnPrices: { hdTexture: 8, unknownAddOn: 7 },
},
imageToModelPricing: {
versionPrices: { 'v3.1-20260211': { noTexture: 16, texture: 24 } },
addOnPrices: { hdTexture: 8 },
},
},
};
}
test('数值解析把空串、非数字、小数与 0 收敛成 0', () => {
expect(parsePositiveInteger('12')).toBe(12);
expect(parsePositiveInteger('')).toBe(0);
expect(parsePositiveInteger('abc')).toBe(0);
expect(parsePositiveInteger('12abc')).toBe(0);
expect(parsePositiveInteger('3.9')).toBe(0);
expect(parsePositiveInteger('0')).toBe(0);
expect(parsePositiveInteger('-3')).toBe(0);
});
test('未登记的 3D 加价项键回退显示原键名', () => {
expect(editorModel3dAddOnLabel('hdTexture')).toBe('高清贴图');
expect(editorModel3dAddOnLabel('unknownAddOn')).toBe('unknownAddOn');
});
test('校验覆盖模型档位与 3D 两段的全部数值', () => {
expect(collectInvalidEditorGenerationPricingLabels(pricingFixture())).toEqual(
[],
);
const invalid = pricingFixture();
const invalidImagePricing = invalid.models['gpt-image-2'];
const invalidTextEndpoint = invalid.model3d?.textToModelPricing;
const invalidImageEndpoint = invalid.model3d?.imageToModelPricing;
if (
!invalidImagePricing?.prices ||
!invalidTextEndpoint ||
!invalidImageEndpoint
) {
throw new Error('夹具必须包含图片档位与 3D 两段');
}
const imageVersionPrice = invalidImageEndpoint.versionPrices['v3.1-20260211'];
if (!imageVersionPrice) {
throw new Error('夹具必须包含图生 3D 的版本底价');
}
invalidImagePricing.prices['2K'] = 0;
invalidTextEndpoint.addOnPrices.hdTexture = 0;
imageVersionPrice.noTexture = 0;
expect(collectInvalidEditorGenerationPricingLabels(invalid)).toEqual([
'gpt-image-2 2K',
'文生 3D 高清贴图',
'图生 3D v3.1-20260211 无贴图',
]);
});
test('保存请求整段回传两段且不带定价版本,3D 缺失时回传 null', () => {
const pricing = pricingFixture();
expect(buildAdminEditorGenerationPricingRequest(pricing)).toEqual({
models: pricing.models,
model3d: pricing.model3d,
});
expect(
buildAdminEditorGenerationPricingRequest({ ...pricing, model3d: null }),
).toEqual({
models: pricing.models,
model3d: null,
});
});
@@ -1,115 +0,0 @@
import type {
AdminUpsertEditorGenerationPricingRequest,
EditorGenerationModel3dEndpointPricingPayload,
EditorGenerationModel3dPricingPayload,
EditorGenerationPricingConfigPayload,
} from '../api/adminApiTypes';
/** 3D 端点在两个并列段里的字段名与后台展示名。 */
export const EDITOR_MODEL3D_ENDPOINT_SECTIONS = [
{ key: 'textToModelPricing', label: '文生 3D' },
{ key: 'imageToModelPricing', label: '图生 3D' },
] as const satisfies ReadonlyArray<{
key: keyof EditorGenerationModel3dPricingPayload;
label: string;
}>;
/**
* 3D 加价项键到中文标签。键来自接口返回,这里只负责展示;遇到未登记的键回退显示原键名,
* 不因为标签缺失就把该项漏掉。
*/
const EDITOR_MODEL3D_ADD_ON_LABELS: Record<string, string> = {
hdTexture: '高清贴图',
ultraTexture: '超高清贴图',
hdGeometry: '高清几何',
quadMesh: '四边形网格',
smartLowPoly: '智能低面',
generateParts: '分件生成',
};
export function editorModel3dAddOnLabel(addOn: string) {
return EDITOR_MODEL3D_ADD_ON_LABELS[addOn] ?? addOn;
}
export function isPositiveMudPoints(value: number | null | undefined) {
return typeof value === 'number' && Number.isInteger(value) && value >= 1;
}
/**
* 提交前校验:所有泥点数值都必须是不小于 1 的整数,返回不合法项的展示名。
*
* 后端仍会独立校验一遍;这里只是不把明显非法的 payload 发出去,避免保存后才报错。
*/
export function collectInvalidEditorGenerationPricingLabels(
pricing: EditorGenerationPricingConfigPayload,
) {
const labels: string[] = [];
for (const [model, modelPricing] of Object.entries(pricing.models)) {
const tieredPrices = modelPricing.prices;
// `prices: {}` 没有档位可校验,不能算「这一项走分层计价」——否则底价会被顺手跳过校验。
if (tieredPrices && Object.keys(tieredPrices).length > 0) {
for (const [tier, price] of Object.entries(tieredPrices)) {
if (!isPositiveMudPoints(price)) {
labels.push(`${model} ${tier}`);
}
}
continue;
}
if (!isPositiveMudPoints(modelPricing.price)) {
labels.push(`${model} 泥点`);
}
}
const model3d = pricing.model3d;
if (model3d) {
for (const { key, label } of EDITOR_MODEL3D_ENDPOINT_SECTIONS) {
// 段与子表都来自接口返回:缺段或缺子表时只跳过这一段,不能让整页校验崩掉。
const endpointPricing = model3d[key];
if (!endpointPricing) {
continue;
}
for (const [version, price] of Object.entries(
endpointPricing.versionPrices ?? {},
)) {
if (!isPositiveMudPoints(price.noTexture)) {
labels.push(`${label} ${version} 无贴图`);
}
if (!isPositiveMudPoints(price.texture)) {
labels.push(`${label} ${version} 带贴图`);
}
}
for (const [addOn, price] of Object.entries(
endpointPricing.addOnPrices ?? {},
)) {
if (!isPositiveMudPoints(price)) {
labels.push(`${label} ${editorModel3dAddOnLabel(addOn)}`);
}
}
}
}
return labels;
}
/**
* 组装保存请求:`models` 与 3D 两段整段回传,不带定价版本(保存即覆盖,服务端不比对版本)。
* 3D 段缺失时回传 `null`——服务端会以 400 拒绝,后台不允许在这里静默新建或丢弃整段。
*/
export function buildAdminEditorGenerationPricingRequest(
pricing: EditorGenerationPricingConfigPayload,
): AdminUpsertEditorGenerationPricingRequest {
return {
models: pricing.models,
model3d: pricing.model3d ?? null,
};
}
/** 单个端点段的不可变更新:底价与加价项各改一处,其余原样保留。 */
export function updateEditorModel3dEndpointPricing(
model3d: EditorGenerationModel3dPricingPayload,
section: keyof EditorGenerationModel3dPricingPayload,
updater: (
current: EditorGenerationModel3dEndpointPricingPayload,
) => EditorGenerationModel3dEndpointPricingPayload,
): EditorGenerationModel3dPricingPayload {
return { ...model3d, [section]: updater(model3d[section]) };
}
-13
View File
@@ -1,18 +1,5 @@
import { formatAdminApiError, isAdminApiError } from '../api/adminApiClient';
/**
* 泥点 / 积分类输入框文本转正整数:空串、非数字、小数、0 与负数一律收敛成 0,
* 由各页的提交前校验拦住。
*
* 用 `Number` 而不是 `parseInt`:`parseInt` 会把 `3.9` 截成 3、`12abc` 截成 12,
* 等于把编辑中的半截输入静默当成合法值存下去;再用 `isSafeInteger` 挡掉超出安全整数
* 范围的值(那种值在别处会被静默改写)。后台各页统一用这一份,不再各写一遍。
*/
export function parsePositiveInteger(value: string) {
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
}
export function handlePageError(
error: unknown,
onUnauthorized: (message?: string) => void,
-29
View File
@@ -2972,34 +2972,6 @@ button:disabled {
gap: 10px;
}
.admin-pricing-model3d-list {
display: grid;
gap: 10px;
}
.admin-pricing-model3d-row {
display: grid;
grid-template-columns: minmax(0, 1.2fr) repeat(2, minmax(0, 1fr));
align-items: end;
gap: 10px;
}
.admin-pricing-model3d-row-label {
color: #5c3a26;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
overflow-wrap: anywhere;
padding-bottom: 10px;
}
.admin-pricing-model3d-hint {
color: #7b5a45;
font-size: 13px;
line-height: 1.5;
margin: 0;
}
.admin-pricing-unit {
flex: 0 0 auto;
border-radius: 999px;
@@ -3050,7 +3022,6 @@ button:disabled {
.admin-two-column-wide,
.admin-accounts-layout,
.admin-pricing-grid,
.admin-pricing-model3d-row,
.admin-form-row,
.admin-filter-grid,
.admin-table-query-grid,
+4 -3
View File
@@ -6312,7 +6312,8 @@ dependencies = [
[[package]]
name = "ts-rs"
version = "12.0.1"
source = "git+https://github.com/Aleph-Alpha/ts-rs?rev=fd8679ef20f866f747c046b30bd29c15e3d7a003#fd8679ef20f866f747c046b30bd29c15e3d7a003"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8"
dependencies = [
"thiserror 2.0.18",
"ts-rs-macros 12.0.1",
@@ -6333,9 +6334,9 @@ dependencies = [
[[package]]
name = "ts-rs-macros"
version = "12.0.1"
source = "git+https://github.com/Aleph-Alpha/ts-rs?rev=fd8679ef20f866f747c046b30bd29c15e3d7a003#fd8679ef20f866f747c046b30bd29c15e3d7a003"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d90eea51bc7988ef9e674bf80a85ba6804739e535e9cab48e4bb34a8b652aa"
dependencies = [
"indexmap 2.14.0",
"proc-macro2",
"quote",
"syn 2.0.118",
@@ -29,10 +29,7 @@ tauri-build = { version = "2.6.2", features = [] }
[dependencies]
codex-patch-parser = { path = "vendor/codex-patch-parser" }
chrono = { version = "0.4", default-features = false, features = ["std"] }
# 与 server-rs 同一口径:已发布的 ts-rs 12.0.1 解析不了 enum 级 `serde(deny_unknown_fields)`
# (见 agent/direct_codex_user_item/model.rs),上游修复 #491 未发版,故固定到该 commit;
# 等 crates.io 发布 > 12.0.1 后改回 registry 版本。不要改用 `no-serde-warnings` 关告警。
ts-rs = { git = "https://github.com/Aleph-Alpha/ts-rs", rev = "fd8679ef20f866f747c046b30bd29c15e3d7a003" }
ts-rs = "12.0.1"
typed_floats = { version = "1.0.7", features = ["serde"] }
nalgebra = { version = "0.35.0", features = ["serde-serialize"] }
agent-runtime-core = { path = "../../../server-rs/crates/agent-runtime-core" }
@@ -69,7 +66,7 @@ platform-agent = { path = "../../../server-rs/crates/platform-agent" }
portable-pty = "0.9"
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "native-tls", "stream"] }
regex = "1"
shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false }
shared-contracts = { path = "../../../server-rs/crates/shared-contracts", default-features = false, features = ["ts-bindings"] }
tauri = { version = "2.11.2", features = [] }
tauri-plugin-dialog = "2.7.1"
tauri-plugin-http = { version = "2.5.9", default-features = false, features = ["charset", "cookies", "http2", "rustls-tls"] }
@@ -29,6 +29,7 @@ mod direct_project_history;
mod direct_project_turn_history;
mod direct_runtime;
mod direct_thread_manager;
mod direct_thread_queue;
mod direct_thread_wire;
mod direct_tool_bridge;
mod direct_tool_calls;
@@ -65,6 +66,7 @@ pub(crate) use direct_project_history::*;
pub(crate) use direct_project_turn_history::*;
pub(crate) use direct_runtime::*;
pub(crate) use direct_thread_manager::*;
pub(crate) use direct_thread_queue::*;
pub(crate) use direct_thread_wire::*;
pub(crate) use direct_tool_bridge::*;
pub(crate) use direct_tool_calls::*;
@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};
use ts_rs::TS;
/// DirectProject 本轮 user input 的唯一结构化入口。
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
#[serde(tag = "type", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
pub(crate) enum DirectCodexUserItem {
@@ -10,7 +10,7 @@ pub(crate) enum DirectCodexUserItem {
Message(DirectCodexUserMessageItem),
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, 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 DirectCodexUserMessageItem {
@@ -19,14 +19,14 @@ pub(crate) struct DirectCodexUserMessageItem {
pub(crate) id: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
#[serde(rename_all = "lowercase")]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
pub(crate) enum DirectCodexUserRole {
User,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
#[serde(tag = "type", rename_all_fields = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
pub(crate) enum DirectCodexUserContentPart {
@@ -43,7 +43,7 @@ pub(crate) enum DirectCodexUserContentPart {
AgcAttachmentReference(DirectCodexUserAttachmentReferencePart),
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, 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 DirectCodexUserAttachmentReferencePart {
@@ -55,7 +55,7 @@ pub(crate) struct DirectCodexUserAttachmentReferencePart {
pub(crate) status: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, TS)]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, 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 DirectCodexUserRuntimeRegionPart {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,200 @@
//! DirectProject 待发消息队列的条目与规则。
//!
//! 队列的成员与顺序**就是 Thread Manager 的事件列表本身**:一条待发消息在队期间,它的
//! `queue.enqueued` 事件不可回收;离开队列(取消或放行)时才转成可回收。新订阅者的 bootstrap 因此
//! 天然看得见当前队列,不需要第二张队列表,也不会有"事件与队列不一致"的窗口。
//!
//! 这个模块只放三件事:一条待发消息带走什么([`PendingDirectTurn`])、容量规则
//! ([`MAX_PENDING_DIRECT_TURNS`])、以及它在线上长什么样([`PendingDirectTurn::enqueued_event`])。
//! 它不碰锁、不碰 Tauri、不写盘:入队检查在命令侧,放行顺序在 Thread Manager。
use serde_json::Value;
use crate::agent::{
direct_codex_user_item_id_for_client_turn_id, DirectCodexUserItem, DirectThreadEvent,
};
/// 一个项目最多能同时排队的待发消息条数。
///
/// 只数**在队**条目,不算正在跑的那一轮。上限只落在宿主这一处:前端不再自己数,满队由命令返回
/// typed 入队失败。
pub(crate) const MAX_PENDING_DIRECT_TURNS: usize = 5;
/// 一条已经通过入队检查、正在等放行的用户消息。
///
/// 只在内存里,进程重启即消失(与 ADR 记的边界一致)。它同时是**放行时要用的全部输入**:放行
/// 没有失败出口,所以检查产物在入队时就地冻结,放行只搬运、不重算。
#[derive(Clone, Debug)]
pub(crate) struct PendingDirectTurn {
/// 这条消息的回合身份;放行后同一轮的 `turn.started` / `turn.completed` 用它。
pub(crate) client_turn_id: String,
/// canonical 用户条目:事件与界面 chip 都读它,Rust 不渲染展示形状。
pub(crate) user_item: DirectCodexUserItem,
/// canonical 用户条目的 JSON 形状:入队时算好,放行时直接落盘。
pub(crate) canonical_user_item: Value,
/// 入队检查产出的 prompt:放行不重算。
pub(crate) prompt: String,
pub(crate) creation_type: Option<String>,
/// 入队那一刻的宿主毫秒钟。
pub(crate) at: u64,
}
impl PendingDirectTurn {
/// 组一条待发消息:入队检查已经全部通过,这里只把放行要用的产物冻结下来。
///
/// 冻结是刻意的:放行没有失败出口,所以任何可能在放行时才失败的计算都必须提前到这里
/// (canonical 形状与 prompt 都是)。
pub(crate) fn prepare(
client_turn_id: String,
user_item: DirectCodexUserItem,
prompt: String,
creation_type: Option<String>,
at: u64,
) -> Result<Self, serde_json::Error> {
let canonical_user_item = serde_json::to_value(&user_item)?;
Ok(Self {
client_turn_id,
user_item,
canonical_user_item,
prompt,
creation_type,
at,
})
}
/// 入队事件的投影:带 canonical 用户条目与 `creationType`,**不带 prompt**(prompt 只留在宿主的
/// 队列条目里,它不是要下发的展示形状)。
pub(crate) fn enqueued_event(&self) -> DirectThreadEvent {
DirectThreadEvent::queue_enqueued(
self.client_turn_id.clone(),
self.user_item.clone(),
self.creation_type.clone(),
self.at,
)
}
/// 这条待发消息在历史里的用户条目 id:前端用它把 chip 与回合边界对上。
pub(crate) fn user_item_id(&self) -> Option<String> {
direct_codex_user_item_id_for_client_turn_id(&self.client_turn_id)
}
}
/// 入队的结果。
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum EnqueueOutcome {
/// 这次真的排进队尾了。
Enqueued,
/// 同一 `clientTurnId` 已经在队(或正在跑):按幂等返回成功,不排第二条、不发事件。
AlreadyKnown,
}
/// 入队被检查挡下来的原因。满队之外的原因由入队半自己的 typed 错误表达。
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum EnqueueRejection {
/// 在队条目已达 [`MAX_PENDING_DIRECT_TURNS`]。
QueueFull,
}
/// 队列还有没有位置。`pending_count` 只数在队条目。
pub(crate) fn queue_has_room(pending_count: usize) -> Result<(), EnqueueRejection> {
if pending_count >= MAX_PENDING_DIRECT_TURNS {
return Err(EnqueueRejection::QueueFull);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn user_item(text: &str, id: &str) -> DirectCodexUserItem {
serde_json::from_value(json!({
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": text}],
"id": id,
}))
.expect("canonical user item")
}
fn pending(client_turn_id: &str, creation_type: Option<&str>) -> PendingDirectTurn {
PendingDirectTurn::prepare(
client_turn_id.to_string(),
user_item("生成一个游戏", "direct-codex:turn-1:user"),
"生成一个游戏".to_string(),
creation_type.map(str::to_string),
1_700_000_000_123,
)
.expect("prepare pending turn")
}
/// 入队事件只带 canonical 用户条目与 `creationType`:prompt 是宿主的入队检查产物,
/// 不许顺着事件下发。
#[test]
fn enqueued_event_carries_the_canonical_item_and_no_prompt() {
let event = pending("turn-1", Some("web-game")).enqueued_event();
let value = serde_json::to_value(&event).expect("serialize queue.enqueued");
assert_eq!(
value,
json!({
"type": "queue.enqueued",
"clientTurnId": "turn-1",
"userItem": {
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "生成一个游戏"}],
"id": "direct-codex:turn-1:user",
},
"creationType": "web-game",
"at": 1_700_000_000_123u64,
})
);
assert!(value.get("prompt").is_none(), "{value}");
// 没有创建类型时不写字段,也不补 `null`。
let bare = serde_json::to_value(pending("turn-2", None).enqueued_event())
.expect("serialize queue.enqueued without creation type");
assert!(bare.get("creationType").is_none(), "{bare}");
// 事件读得出自己的待发消息身份。
assert_eq!(event.queue_client_turn_id(), Some("turn-1"));
assert_eq!(event.queue_removal_reason(), None);
}
/// canonical 形状在入队时就冻结:放行时落盘的就是这一份,不再重算。
#[test]
fn prepare_freezes_the_canonical_item() {
let turn = pending("turn-1", None);
assert_eq!(
turn.canonical_user_item["id"],
json!("direct-codex:turn-1:user")
);
assert_eq!(
turn.canonical_user_item,
serde_json::to_value(&turn.user_item).expect("serialize user item")
);
}
/// 用户条目身份由 `clientTurnId` 派生,与落盘 / 下发用的是同一个函数。
#[test]
fn user_item_id_derives_from_the_client_turn_id() {
assert_eq!(
pending("turn-1", None).user_item_id().as_deref(),
Some("direct-codex:turn-1:user")
);
assert_eq!(pending(" ", None).user_item_id(), None);
}
/// 容量只数在队条目,5 条封口;在跑的那一轮不算进去。
#[test]
fn capacity_closes_at_five_pending_turns() {
for count in 0..MAX_PENDING_DIRECT_TURNS {
assert_eq!(queue_has_room(count), Ok(()), "{count} 条时仍该有位置");
}
assert_eq!(
queue_has_room(MAX_PENDING_DIRECT_TURNS),
Err(EnqueueRejection::QueueFull)
);
}
}
@@ -13,6 +13,7 @@
use crate::agent::redact_secret_tokens;
use crate::agent::sanitize_error_context;
use crate::agent::DirectCodexUserItem;
use crate::agent::DirectTurnFailureKind;
use crate::redact_absolute_path_tokens;
use serde::{Deserialize, Serialize};
@@ -212,6 +213,33 @@ impl DirectThreadRequestKind {
}
}
/// 一条待发消息离开队列的原因。
///
/// typed 枚举,取值即语义:取消是用户在输入盒上撤掉这条消息,放行是它已经接单并成为回合
/// (同一临界区里另有 `turn.started`)。界面按它分流,不解析字符串。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
pub(crate) enum DirectQueueRemovalReason {
/// 用户取消了这条待发消息。
Cancelled,
/// 放行:这条待发消息已经接单并成为回合。
Dispatched,
}
/// 取消一条待发消息的结果。
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
pub(crate) enum DirectQueueRemovalOutcome {
/// 已从队列移除。
Removed,
/// 这条消息已经被放行(正在跑的那一轮就是它),不能按待发消息取消。
AlreadyDispatched,
/// 队列里没有这个身份,也没有在跑的一轮是它。
NotFound,
}
/// 失败终态的可下发载荷(`turn.completed.status == "failed"` 时必有,其余终态没有)。
///
/// `kind` 是稳定分类,只给界面选语气,不参与流程分支;`message` 是**已在宿主侧脱敏并截断**的
@@ -259,7 +287,7 @@ impl DirectTurnFailure {
/// 不带回合身份,这个字段只用来把"这一轮的边界属于哪条用户消息"讲清楚:前端在只有生命周期锚点
/// + 历史切片、运行态一直为空时也能按身份认领开口条目,不必靠时间戳猜。缺失表示身份不可证明
/// (旧事件、没有开口用户条目、取消时拿不到 clientTurnId),此时前端不得补造。
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, TS)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "type", rename_all_fields = "camelCase", deny_unknown_fields)]
#[ts(export, export_to = concat!(env!("CARGO_MANIFEST_DIR"), "/../src/view/project-development/chat/generated/"))]
pub(crate) enum DirectThreadEvent {
@@ -321,6 +349,34 @@ pub(crate) enum DirectThreadEvent {
#[serde(default)]
request_id: Option<String>,
},
/// 待发消息入队:数组顺序就是队首到队尾的顺序。
///
/// 这条事件在条目仍在队期间**不可回收**,离开队列(取消或放行)时才转成可回收——新订阅者
/// 靠这一点在 bootstrap 里看到当前队列,`is_bootstrap_event` 不需要为它加特例。
///
/// 事件不带 prompt:prompt 是入队检查的产物,只留在宿主的队列条目里。
#[serde(rename = "queue.enqueued")]
QueueEnqueued {
/// 这条待发消息的回合身份;放行后同一轮的 `turn.started` / `turn.completed` 用它。
client_turn_id: String,
/// canonical 用户条目:前端据此派生 chip 文案,Rust 不渲染展示形状。
user_item: DirectCodexUserItem,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
creation_type: Option<String>,
/// 入队那一刻的宿主毫秒钟。
#[ts(as = "f64")]
at: u64,
},
/// 待发消息离开队列:`reason` 是取消还是放行。
#[serde(rename = "queue.removed")]
QueueRemoved {
client_turn_id: String,
reason: DirectQueueRemovalReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional, as = "Option<f64>")]
at: Option<u64>,
},
}
impl DirectThreadEvent {
@@ -417,6 +473,51 @@ impl DirectThreadEvent {
Self::Request { kind, request_id }
}
/// 待发消息入队事件。
pub(crate) fn queue_enqueued(
client_turn_id: String,
user_item: DirectCodexUserItem,
creation_type: Option<String>,
at: u64,
) -> Self {
Self::QueueEnqueued {
client_turn_id,
user_item,
creation_type,
at,
}
}
/// 待发消息离开队列事件。
pub(crate) fn queue_removed(
client_turn_id: String,
reason: DirectQueueRemovalReason,
at: u64,
) -> Self {
Self::QueueRemoved {
client_turn_id,
reason,
at: Some(at),
}
}
/// 这条事件属于哪条待发消息:只有队列事件有。
pub(crate) fn queue_client_turn_id(&self) -> Option<&str> {
match self {
Self::QueueEnqueued { client_turn_id, .. }
| Self::QueueRemoved { client_turn_id, .. } => Some(client_turn_id),
_ => None,
}
}
/// 待发消息离开队列的原因:只有 `queue.removed` 有。
pub(crate) fn queue_removal_reason(&self) -> Option<DirectQueueRemovalReason> {
match self {
Self::QueueRemoved { reason, .. } => Some(*reason),
_ => None,
}
}
/// 事件级阶段时间(毫秒):只有四种生命周期事件有,其余事件返回 `None`。
///
/// 只读已存入事件的值,不在读取时取钟——重放要用的就是原事件的时间。
@@ -427,6 +528,8 @@ impl DirectThreadEvent {
| Self::TurnCompleted { at, .. }
| Self::ItemStarted { at, .. }
| Self::ItemCompleted { at, .. } => *at,
Self::QueueEnqueued { at, .. } => Some(*at),
Self::QueueRemoved { at, .. } => *at,
Self::ItemDelta { .. } | Self::Request { .. } => None,
}
}
@@ -456,7 +559,7 @@ impl DirectThreadEvent {
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, TS)]
#[derive(Clone, Debug, 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 DirectThreadSubscriptionBootstrap {
@@ -468,7 +571,7 @@ pub(crate) struct DirectThreadSubscriptionBootstrap {
pub(crate) events: Vec<DirectThreadEvent>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, TS)]
#[derive(Clone, Debug, 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 DirectThreadConsumeResult {
@@ -1466,4 +1569,61 @@ mod tests {
.expect("failed turn without failure payload");
assert_eq!(sparse.failure(), None);
}
/// 待发消息离开队列:`reason` 是 typed 枚举(`cancelled` / `dispatched`),界面按取值分流,
/// 不解析字符串。`at` 缺省时反序列化仍是 `None`。
#[test]
fn queue_removed_carries_a_typed_reason() {
let dispatched = DirectThreadEvent::queue_removed(
"turn-1".to_string(),
DirectQueueRemovalReason::Dispatched,
2_000,
);
assert_eq!(
serde_json::to_value(&dispatched).expect("serialize queue.removed"),
json!({
"type": "queue.removed",
"clientTurnId": "turn-1",
"reason": "dispatched",
"at": 2_000u64,
})
);
assert_eq!(
serde_json::from_value::<DirectThreadEvent>(
serde_json::to_value(&dispatched).expect("serialize")
)
.expect("round trip"),
dispatched
);
assert_eq!(dispatched.queue_client_turn_id(), Some("turn-1"));
assert_eq!(
dispatched.queue_removal_reason(),
Some(DirectQueueRemovalReason::Dispatched)
);
// 未识别的取值必须失败关闭:队列归属是宿主事实,不能让界面猜。
serde_json::from_value::<DirectThreadEvent>(json!({
"type": "queue.removed",
"clientTurnId": "turn-1",
"reason": "timeout",
}))
.expect_err("unknown queue removal reason must fail closed");
// 没有 `at` 的老形状仍能反序列化,回写不补 `null`。
let legacy: DirectThreadEvent = serde_json::from_value(json!({
"type": "queue.removed",
"clientTurnId": "turn-1",
"reason": "cancelled",
}))
.expect("queue.removed without at");
assert_eq!(legacy.at(), None);
assert_eq!(
serde_json::to_value(legacy).expect("serialize legacy"),
json!({
"type": "queue.removed",
"clientTurnId": "turn-1",
"reason": "cancelled",
})
);
}
}
@@ -1266,11 +1266,13 @@
max-width: calc(100% - 28px);
}
/* 「生成规范」的二级菜单(`bottom:100%+6px`)必须可见:换行与不裁剪由共享工具栏保证
(`@genarrative/image-canvas-react` 的 `.genarrative-image-canvas__toolbar` 已从
`overflow-x: auto` 改成 `flex-wrap: wrap`),这里只限宽,不再重复覆盖 overflow。 */
/* 共享 chrome 的 `.genarrative-image-canvas__toolbar` 是横向滚动条(`overflow-x:auto`),
会把它自己弹出的二级菜单(`bottom:100%+6px`)裁掉。这里改成换行、不裁切:
「生成规范」的二级菜单必须可见,窄屏用换行兜底而不是横向滚动。 */
.game-resource-bottom-toolbar-strip {
max-width: 100%;
overflow: visible;
flex-wrap: wrap;
}
.game-resource-bottom-toolbar-action {
@@ -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 DirectQueueRemovalOutcome =
| 'removed'
| 'alreadyDispatched'
| 'notFound';
@@ -0,0 +1,9 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* 一条待发消息离开队列的原因。
*
* typed 枚举,取值即语义:取消是用户在输入盒上撤掉这条消息,放行是它已经接单并成为回合
* (同一临界区里另有 `turn.started`)。界面按它分流,不解析字符串。
*/
export type DirectQueueRemovalReason = 'cancelled' | 'dispatched';

Some files were not shown because too many files have changed in this diff Show More